Transformers 文件

MobileNet V1

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

PyTorch

MobileNet V1

MobileNet V1 是一個高效的卷積神經網路系列,專為裝置上或嵌入式視覺任務而最佳化。它透過使用深度可分離卷積(depth-wise separable convolutions)代替標準卷積來實現這種高效率。該架構允許透過兩個主要超引數——寬度乘數(alpha)和影像解析度乘數,輕鬆地在延遲和準確性之間進行權衡。

你可以在 Google 組織下找到所有原始的 MobileNet checkpoints。

點選右側邊欄中的 MobileNet V1 模型,檢視更多關於如何將 MobileNet 應用於不同視覺任務的示例。

下面的示例演示瞭如何使用 PipelineAutoModel 類對影像進行分類。

流水線
自動模型
import torch
from transformers import pipeline

pipeline = pipeline(
    task="image-classification",
    model="google/mobilenet_v1_1.0_224",
    torch_dtype=torch.float16,
    device=0
)
pipeline(images="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg")

注意

  • Checkpoint 的名稱遵循 mobilenet_v1_{depth_multiplier}_{resolution} 的模式,例如 mobilenet_v1_1.0_224。其中 1.0 是深度乘數,224 是影像解析度。

  • 雖然模型是在特定尺寸的影像上訓練的,但其架構可以處理不同尺寸的影像(最小為 32x32)。MobileNetV1ImageProcessor 會處理必要的預處理工作。

  • MobileNet 是在 ImageNet-1k 上預訓練的,該資料集包含 1000 個類別。然而,該模型實際上預測 1001 個類別。額外的類別是一個“背景”類(索引為 0)。

  • 原始的 TensorFlow checkpoints 在推理時確定填充量,因為它取決於輸入影像的大小。要使用原生的 PyTorch 填充行為,請在 MobileNetV1Config 中設定 tf_padding=False

    from transformers import MobileNetV1Config
    
    config = MobileNetV1Config.from_pretrained("google/mobilenet_v1_1.0_224", tf_padding=True)
  • Transformers 實現不支援以下功能。

    • 使用全域性平均池化,而不是可選的步幅為 2 的 7x7 平均池化。對於較大的輸入,這會產生大於 1x1 畫素的池化輸出。
    • 不支援其他 output_stride 值(固定為 32)。對於較小的 output_strides,原始實現使用擴張卷積(dilated convolution)來防止空間解析度進一步降低(這將需要擴張卷積)。
    • output_hidden_states=True 會返回 *所有* 中間隱藏狀態。無法從特定層提取輸出用於其他下游目的。
    • 不包括原始 checkpoints 中的量化模型,因為它們包含“FakeQuantization”操作來反量化權重。

MobileNetV1Config

class transformers.MobileNetV1Config

< >

( num_channels = 3 image_size = 224 depth_multiplier = 1.0 min_depth = 8 hidden_act = 'relu6' tf_padding = True classifier_dropout_prob = 0.999 initializer_range = 0.02 layer_norm_eps = 0.001 **kwargs )

引數

  • num_channels (int, 可選, 預設為 3) — 輸入通道的數量。
  • image_size (int, 可選, 預設為 224) — 每張影像的大小(解析度)。
  • depth_multiplier (float, 可選, 預設為 1.0) — 縮小或擴大每層通道的數量。預設為 1.0,此時網路以 32 個通道開始。這有時也被稱為“alpha”或“寬度乘數”。
  • min_depth (int, 可選, 預設為 8) — 所有層將至少有這麼多通道。
  • hidden_act (str or function, 可選, 預設為 "relu6") — Transformer 編碼器和卷積層中的非線性啟用函式(函式或字串)。
  • tf_padding (bool, 可選, 預設為 True) — 是否在卷積層上使用 TensorFlow 的填充規則。
  • classifier_dropout_prob (float, 可選, 預設為 0.999) — 附加分類器的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • layer_norm_eps (float, 可選, 預設為 0.001) — 層歸一化層使用的 epsilon 值。

這是用於儲存 MobileNetV1Model 配置的配置類。它用於根據指定的引數例項化 MobileNetV1 模型,定義模型架構。使用預設值例項化配置將產生與 MobileNetV1 google/mobilenet_v1_1.0_224 架構類似的配置。

配置物件繼承自 PretrainedConfig,可用於控制模型輸出。有關更多資訊,請閱讀 PretrainedConfig 的文件。

示例

>>> from transformers import MobileNetV1Config, MobileNetV1Model

>>> # Initializing a "mobilenet_v1_1.0_224" style configuration
>>> configuration = MobileNetV1Config()

>>> # Initializing a model from the "mobilenet_v1_1.0_224" style configuration
>>> model = MobileNetV1Model(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

MobileNetV1FeatureExtractor

class transformers.MobileNetV1FeatureExtractor

< >

( *args **kwargs )

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

引數

  • images (ImageInput) — 待預處理的影像。需要單張或一批畫素值範圍在 0 到 255 的影像。如果傳入畫素值在 0 和 1 之間的影像,請設定 do_rescale=False
  • do_resize (bool, 可選, 預設為 self.do_resize) — 是否調整影像大小。
  • size (dict[str, int], 可選, 預設為 self.size) — 調整大小後圖像的尺寸。影像的最短邊將調整為 size[“shortest_edge”],最長邊則按比例調整以保持原始寬高比。
  • resample (PILImageResampling filter, 可選, 預設為 self.resample) — 用於調整影像大小的 `PILImageResampling` 濾鏡,例如 `PILImageResampling.BILINEAR`。僅當 `do_resize` 設定為 `True` 時生效。
  • do_center_crop (bool, 可選, 預設為 self.do_center_crop) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], 可選, 預設為 self.crop_size) — 中心裁剪的尺寸。僅當 `do_center_crop` 設定為 `True` 時生效。
  • do_rescale (bool, 可選, 預設為 self.do_rescale) — 是否將影像值重新縮放到 [0 - 1] 之間。
  • rescale_factor (float, 可選, 預設為 self.rescale_factor) — 如果 `do_rescale` 設定為 `True`,則用於重新縮放影像的縮放因子。
  • do_normalize (bool, 可選, 預設為 self.do_normalize) — 是否對影像進行歸一化。
  • image_mean (float or list[float], 可選, 預設為 self.image_mean) — 如果 `do_normalize` 設定為 `True`,則使用的影像均值。
  • image_std (float or list[float], 可選, 預設為 self.image_std) — 如果 `do_normalize` 設定為 `True`,則使用的影像標準差。
  • return_tensors (str or TensorType, 可選) — 要返回的張量型別。可以是以下之一:
    • 未設定:返回 `np.ndarray` 列表。
    • `TensorType.TENSORFLOW` 或 `'tf'`:返回 `tf.Tensor` 型別的批次。
    • `TensorType.PYTORCH` 或 `'pt'`:返回 `torch.Tensor` 型別的批次。
    • `TensorType.NUMPY` 或 `'np'`:返回 `np.ndarray` 型別的批次。
    • `TensorType.JAX` 或 `'jax'`:返回 `jax.numpy.ndarray` 型別的批次。
  • data_format (ChannelDimension or str, 可選, 預設為 ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • `"channels_first"` 或 `ChannelDimension.FIRST`:影像格式為 (num_channels, height, width)。
    • `"channels_last"` 或 `ChannelDimension.LAST`:影像格式為 (height, width, num_channels)。
    • 未設定:使用輸入影像的通道維度格式。
  • input_data_format (ChannelDimension or str, 可選) — 輸入影像的通道維度格式。如果未設定,將從輸入影像中推斷通道維度格式。可以是以下之一:
    • `"channels_first"` 或 `ChannelDimension.FIRST`:影像格式為 (num_channels, height, width)。
    • `"channels_last"` 或 `ChannelDimension.LAST`:影像格式為 (height, width, num_channels)。
    • `"none"` 或 `ChannelDimension.NONE`:影像格式為 (height, width)。

預處理一張或一批影像。

MobileNetV1ImageProcessor

class transformers.MobileNetV1ImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.Optional[dict[str, int]] = None do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None **kwargs )

引數

  • do_resize (bool, 可選, 預設為 True) — 是否將影像的(高度,寬度)尺寸調整為指定的 `size`。可在 `preprocess` 方法中透過 `do_resize` 引數覆蓋。
  • size (dict[str, int] 可選, 預設為 {"shortest_edge" -- 256}): 調整大小後圖像的尺寸。影像的最短邊將調整為 size[“shortest_edge”],最長邊則按比例調整以保持原始寬高比。可在 `preprocess` 方法中透過 `size` 引數覆蓋。
  • resample (PILImageResampling, 可選, 預設為 PILImageResampling.BILINEAR) — 用於調整影像大小的重取樣濾鏡。可在 `preprocess` 方法中透過 `resample` 引數覆蓋。
  • do_center_crop (bool, 可選, 預設為 True) — 是否對影像進行中心裁剪。如果輸入的任何一邊小於 `crop_size`,影像將用 0 填充,然後進行中心裁剪。可在 `preprocess` 方法中透過 `do_center_crop` 引數覆蓋。
  • crop_size (dict[str, int], 可選, 預設為 {"height" -- 224, "width": 224}): 應用中心裁剪時的期望輸出尺寸。僅當 `do_center_crop` 設定為 `True` 時生效。可在 `preprocess` 方法中透過 `crop_size` 引數覆蓋。
  • do_rescale (bool, 可選, 預設為 True) — 是否按指定的比例 `rescale_factor` 重新縮放影像。可在 `preprocess` 方法中透過 `do_rescale` 引數覆蓋。
  • rescale_factor (int or float, 可選, 預設為 1/255) — 用於重新縮放影像的比例因子。可在 `preprocess` 方法中透過 `rescale_factor` 引數覆蓋。
  • do_normalize — 是否對影像進行歸一化。可在 preprocess 方法中使用 do_normalize 引數進行覆蓋。
  • image_mean (floatlist[float], 可選, 預設為 IMAGENET_STANDARD_MEAN) — 歸一化影像時使用的均值。這是一個浮點數或浮點數列表,長度等於影像中的通道數。可在 preprocess 方法中使用 image_mean 引數進行覆蓋。
  • image_std (floatlist[float], 可選, 預設為 IMAGENET_STANDARD_STD) — 歸一化影像時使用的標準差。這是一個浮點數或浮點數列表,長度等於影像中的通道數。可在 preprocess 方法中使用 image_std 引數進行覆蓋。

構建一個 MobileNetV1 影像處理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_center_crop: typing.Optional[bool] = None crop_size: typing.Optional[dict[str, int]] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, list[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Union[str, transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

引數

  • images (ImageInput) — 待預處理的影像。需要單個或一批畫素值在 0 到 255 之間的影像。如果傳入的影像畫素值在 0 和 1 之間,請設定 do_rescale=False
  • do_resize (bool, 可選, 預設為 self.do_resize) — 是否調整影像大小。
  • size (dict[str, int], 可選, 預設為 self.size) — 調整大小後的影像尺寸。影像的最短邊將被調整為 size[“shortest_edge”],最長邊則按比例縮放以保持輸入影像的寬高比。
  • resample (PILImageResampling 過濾器, 可選, 預設為 self.resample) — 調整影像大小時使用的 PILImageResampling 過濾器,例如 PILImageResampling.BILINEAR。僅當 do_resize 設定為 True 時生效。
  • do_center_crop (bool, 可選, 預設為 self.do_center_crop) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], 可選, 預設為 self.crop_size) — 中心裁剪的尺寸。僅當 do_center_crop 設定為 True 時生效。
  • do_rescale (bool, 可選, 預設為 self.do_rescale) — 是否將影像畫素值縮放到 [0 - 1] 之間。
  • rescale_factor (float, 可選, 預設為 self.rescale_factor) — 如果 do_rescale 設定為 True,用於縮放影像的比例因子。
  • do_normalize (bool, 可選, 預設為 self.do_normalize) — 是否對影像進行歸一化。
  • image_mean (floatlist[float], 可選, 預設為 self.image_mean) — 如果 do_normalize 設定為 True,則使用此影像均值。
  • image_std (floatlist[float], 可選, 預設為 self.image_std) — 如果 do_normalize 設定為 True,則使用此影像標準差。
  • return_tensors (strTensorType, 可選) — 返回張量的型別。可以是以下之一:
    • 未設定:返回 np.ndarray 列表。
    • TensorType.TENSORFLOW'tf':返回一個 tf.Tensor 型別的批次。
    • TensorType.PYTORCH'pt':返回一個 torch.Tensor 型別的批次。
    • TensorType.NUMPY'np':返回一個 np.ndarray 型別的批次。
    • TensorType.JAX'jax':返回一個 jax.numpy.ndarray 型別的批次。
  • data_format (ChannelDimensionstr, 可選, 預設為 ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • 未設定:使用輸入影像的通道維度格式。
  • input_data_format (ChannelDimensionstr, 可選) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:影像格式為 (height, width)。

預處理一張或一批影像。

MobileNetV1ImageProcessorFast

class transformers.MobileNetV1ImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )

構建一個快速的 Mobilenet V1 影像處理器。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] *args **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

引數

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 待預處理的影像。需要單個或一批畫素值在 0 到 255 之間的影像。如果傳入的影像畫素值在 0 和 1 之間,請設定 do_rescale=False
  • do_resize (bool, 可選) — 是否調整影像大小。
  • size (dict[str, int], 可選) — 描述模型的最大輸入尺寸。
  • default_to_square (bool, 可選) — 當 size 是一個整數時,在調整大小時是否預設為方形影像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 調整影像大小時使用的重取樣過濾器。可以是 PILImageResampling 列舉之一。僅當 do_resize 設定為 True 時生效。
  • do_center_crop (bool, 可選) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], 可選) — 應用 center_crop 後輸出影像的尺寸。
  • do_rescale (bool, 可選) — 是否對影像進行縮放。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 設定為 True,用於縮放影像的比例因子。
  • do_normalize (bool, 可選) — 是否對影像進行歸一化。
  • image_mean (Union[float, list[float], NoneType]) — 用於歸一化的影像均值。僅當 do_normalize 設定為 True 時生效。
  • image_std (Union[float, list[float], NoneType]) — 用於歸一化的影像標準差。僅當 do_normalize 設定為 True 時生效。
  • do_convert_rgb (bool, 可選) — 是否將影像轉換為 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果設定為 `pt`,則返回堆疊的張量,否則返回張量列表。
  • data_format (~image_utils.ChannelDimension, 可選) — 僅支援 ChannelDimension.FIRST。為與慢速處理器相容而新增。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:影像格式為 (height, width)。
  • device (torch.device, 可選) — 處理影像的裝置。如果未設定,則從輸入影像中推斷裝置。
  • disable_grouping (bool, 可選) — 是否停用按尺寸對影像進行分組,以單獨處理而不是批次處理。如果為 None,則在影像位於 CPU 上時設定為 True,否則設定為 False。此選擇基於經驗觀察,詳情請見:https://github.com/huggingface/transformers/pull/38157

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/陣列/張量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可選) — 您可以在此處提供一個`tensor_type`,以便在初始化時將整數列表轉換為PyTorch/TensorFlow/Numpy張量。

MobileNetV1Model

class transformers.MobileNetV1Model

< >

( config: MobileNetV1Config add_pooling_layer: bool = True )

引數

  • config (MobileNetV1Config) — 模型配置類,包含模型的所有引數。使用配置檔案進行初始化時,不會載入與模型相關的權重,僅載入配置。請檢視 from_pretrained() 方法來載入模型權重。
  • add_pooling_layer (bool, 可選, 預設為 True) — 是否新增池化層

基礎的 Mobilenet V1 模型,輸出原始的隱藏狀態,頂部沒有任何特定的頭部。

該模型繼承自 PreTrainedModel。請檢視超類文件以瞭解該庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是 PyTorch torch.nn.Module 的子類。可以像使用常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

引數

  • pixel_values (torch.Tensor,形狀為 (batch_size, num_channels, image_size, image_size), 可選) — 對應於輸入影像的張量。畫素值可以使用 {image_processor_class} 獲取。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool, 可選) — 是返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一個 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention 或一個 torch.FloatTensor 元組(如果傳遞了 return_dict=False 或當 config.return_dict=False 時),包含各種元素,具體取決於配置(MobileNetV1Config)和輸入。

  • last_hidden_state (torch.FloatTensor, 形狀為 (batch_size, num_channels, height, width)) — 模型最後一層輸出的隱藏狀態序列。

  • pooler_output (torch.FloatTensor, 形狀為 (batch_size, hidden_size)) — 經過空間維度池化操作後的最後一層隱藏狀態。

  • hidden_states (tuple(torch.FloatTensor), 可選, 當傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 元組(一個用於嵌入層的輸出,如果模型有嵌入層,+ 一個用於每層輸出),形狀為 (batch_size, num_channels, height, width)

    模型在每個層輸出的隱藏狀態以及可選的初始嵌入輸出。

MobileNetV1Model 的 forward 方法,會覆蓋 __call__ 特殊方法。

雖然前向傳播的配方需要在此函式中定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會默默地忽略它們。

示例

MobileNetV1ForImageClassification

class transformers.MobileNetV1ForImageClassification

< >

( config: MobileNetV1Config )

引數

  • config (MobileNetV1Config) — 模型的配置類,包含模型的所有引數。使用配置檔案進行初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。

MobileNetV1 模型,其頂部帶有一個影像分類頭(在池化特徵之上是一個線性層),例如用於 ImageNet。

該模型繼承自 PreTrainedModel。請檢視超類文件以瞭解該庫為其所有模型實現的通用方法(例如下載或儲存、調整輸入嵌入大小、修剪頭部等)。

該模型也是 PyTorch torch.nn.Module 的子類。可以像使用常規 PyTorch 模組一樣使用它,並參考 PyTorch 文件瞭解所有與常規用法和行為相關的事項。

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None labels: typing.Optional[torch.Tensor] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

引數

  • pixel_values (torch.Tensor,形狀為 (batch_size, num_channels, image_size, image_size)可選) — 對應於輸入影像的張量。畫素值可以透過 {image_processor_class} 獲得。有關詳細資訊,請參閱 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 處理影像)。
  • output_hidden_states (bool, 可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • labels (torch.LongTensor,形狀為 (batch_size,)可選) — 用於計算影像分類/迴歸損失的標籤。索引應在 [0, ..., config.num_labels - 1] 範圍內。如果 config.num_labels == 1,則計算迴歸損失(均方損失)。如果 config.num_labels > 1,則計算分類損失(交叉熵)。
  • return_dict (bool, 可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.modeling_outputs.ImageClassifierOutputWithNoAttentiontuple(torch.FloatTensor)

一個 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一個 torch.FloatTensor 的元組(如果傳遞了 return_dict=Falseconfig.return_dict=False),根據配置 (MobileNetV1Config) 和輸入包含不同的元素。

  • loss (形狀為 (1,)torch.FloatTensor可選,當提供 labels 時返回) — 分類損失(如果 config.num_labels==1,則為迴歸損失)。
  • logits (形狀為 (batch_size, config.num_labels)torch.FloatTensor) — 分類(如果 config.num_labels==1,則為迴歸)分數(SoftMax 之前)。
  • hidden_states (tuple(torch.FloatTensor)可選,當傳遞 output_hidden_states=Trueconfig.output_hidden_states=True 時返回) — torch.FloatTensor 的元組(如果模型有嵌入層,則一個用於嵌入層的輸出,外加每個階段的輸出各一個),形狀為 (batch_size, num_channels, height, width)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。

MobileNetV1ForImageClassification 的 forward 方法重寫了 __call__ 特殊方法。

雖然前向傳播的配方需要在此函式中定義,但之後應該呼叫 Module 例項而不是這個函式,因為前者會處理預處理和後處理步驟,而後者會默默地忽略它們。

示例

>>> from transformers import AutoImageProcessor, MobileNetV1ForImageClassification
>>> import torch
>>> from datasets import load_dataset

>>> dataset = load_dataset("huggingface/cats-image")
>>> image = dataset["test"]["image"][0]

>>> image_processor = AutoImageProcessor.from_pretrained("google/mobilenet_v1_1.0_224")
>>> model = MobileNetV1ForImageClassification.from_pretrained("google/mobilenet_v1_1.0_224")

>>> inputs = image_processor(image, return_tensors="pt")

>>> with torch.no_grad():
...     logits = model(**inputs).logits

>>> # model predicts one of the 1000 ImageNet classes
>>> predicted_label = logits.argmax(-1).item()
>>> print(model.config.id2label[predicted_label])
...
< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.