Transformers 文件

MobileNet V2

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

PyTorch

MobileNet V2

MobileNet V2 透過更高效的架構提升了在移動裝置上的效能。它使用倒置殘差塊(inverted residual blocks)和線性瓶頸(linear bottlenecks)來處理資料,首先將資料壓縮到一個較小的表示,然後擴充套件進行處理,最後再次收縮以減少計算量。該模型還移除了非線性啟用函式,以在簡化設計的同時保持準確性。與 MobileNet V1 類似,它也使用深度可分離卷積(depthwise separable convolutions)來提高效率。

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

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

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

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

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

注意

  • 分類 checkpoint 的名稱遵循 `mobilenet_v2_{depth_multiplier}_{resolution}` 的模式,例如 `mobilenet_v2_1.4_224`。其中 `1.4` 是深度乘數,`224` 是影像解析度。分割 checkpoint 的名稱遵循 `deeplabv3_mobilenet_v2_{depth_multiplier}_{resolution}` 的模式。

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

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

  • 分割模型使用 DeepLabV3+ 頭,該頭通常在 PASCAL VOC 等資料集上進行預訓練。

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

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

    • 使用全域性平均池化,而不是可選的步長為 2 的 7x7 平均池化。對於較大的輸入,這會產生一個大於 1x1 畫素的池化輸出。
    • 設定 `output_hidden_states=True` 會返回*所有*中間隱藏狀態。無法從特定層提取輸出用於其他下游目的。
    • 不包括來自原始 checkpoints 的量化模型,因為它們包含“FakeQuantization”操作來反量化權重。
    • 對於分割模型,即使 DeepLabV3+ 頭不使用它,主幹網路的最後一個卷積層也會被計算。

MobileNetV2Config

class transformers.MobileNetV2Config

< >

( num_channels = 3 image_size = 224 depth_multiplier = 1.0 depth_divisible_by = 8 min_depth = 8 expand_ratio = 6.0 output_stride = 32 first_layer_is_expansion = True finegrained_output = True hidden_act = 'relu6' tf_padding = True classifier_dropout_prob = 0.8 initializer_range = 0.02 layer_norm_eps = 0.001 semantic_loss_ignore_index = 255 **kwargs )

引數

  • num_channels (int, 可選, 預設為 3) — 輸入通道的數量。
  • image_size (int, 可選, 預設為 224) — 每張影像的大小(解析度)。
  • depth_multiplier (float, 可選, 預設為 1.0) — 縮小或擴充套件每層通道的數量。預設為 1.0,此時網路以 32 個通道開始。這有時也被稱為“alpha”或“寬度乘數”。
  • depth_divisible_by (int, 可選, 預設為 8) — 每層通道數將始終是該數字的倍數。
  • min_depth (int, 可選, 預設為 8) — 所有層將至少有這麼多通道。
  • expand_ratio (float, 可選, 預設為 6.0) — 每個塊中第一層的輸出通道數是輸入通道數乘以擴充套件比率。
  • output_stride (int, 可選, 預設為 32) — 輸入和輸出特徵圖的空間解析度之比。預設情況下,模型將輸入維度縮小 32 倍。如果 `output_stride` 為 8 或 16,模型將在深度卷積層上使用空洞卷積(dilated convolutions)而不是常規卷積,這樣特徵圖的大小不會超過輸入影像的 8 倍或 16 倍。
  • first_layer_is_expansion (bool, 可選, 預設為 `True`) — 如果為 True,則第一個卷積層也是第一個擴充套件塊的擴充套件層。
  • finegrained_output (bool, 可選, 預設為 `True`) — 如果為 true,即使 `depth_multiplier` 小於 1,最後一個卷積層的輸出通道數也將保持較大值(1280)。
  • hidden_act (strfunction, 可選, 預設為 `"relu6"`) — Transformer 編碼器和卷積層中的非線性啟用函式(函式或字串)。
  • tf_padding (bool, 可選, 預設為 `True`) — 是否在卷積層上使用 TensorFlow 的填充規則。
  • classifier_dropout_prob (float, 可選, 預設為 0.8) — 附加分類器的 dropout 比率。
  • initializer_range (float, 可選, 預設為 0.02) — 用於初始化所有權重矩陣的 truncated_normal_initializer 的標準差。
  • layer_norm_eps (float, 可選, 預設為 0.001) — 層歸一化層使用的 epsilon 值。
  • semantic_loss_ignore_index (int, 可選, 預設為 255) — 語義分割模型的損失函式忽略的索引。

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

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

示例

>>> from transformers import MobileNetV2Config, MobileNetV2Model

>>> # Initializing a "mobilenet_v2_1.0_224" style configuration
>>> configuration = MobileNetV2Config()

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

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

MobileNetV2FeatureExtractor

class transformers.MobileNetV2FeatureExtractor

< >

( *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 (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)。

預處理一張或一批影像。

post_process_semantic_segmentation

< >

( outputs target_sizes: typing.Optional[list[tuple]] = None ) semantic_segmentation

引數

  • outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始輸出。
  • target_sizes (長度為 `batch_size` 的 `list[Tuple]`, 可選) — 對應每個預測請求的最終尺寸(高,寬)的元組列表。如果未設定,預測將不會被調整大小。

返回

語義分割

長度為 `batch_size` 的 `list[torch.Tensor]`,其中每個元素是一個形狀為 (height, width) 的語義分割圖,對應於 target_sizes 中的條目(如果指定了 `target_sizes`)。每個 `torch.Tensor` 的每個條目對應一個語義類別 ID。

MobileNetV2ForSemanticSegmentation 的輸出轉換為語義分割圖。僅支援 PyTorch。

MobileNetV2ImageProcessor

class transformers.MobileNetV2ImageProcessor

< >

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

構建一個 MobileNetV2 影像處理器。

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, optional, defaults to self.do_resize) — 是否調整影像大小。
  • size (dict[str, int], optional, defaults to self.size) — 調整大小後的影像尺寸。影像的最短邊調整為 size["shortest_edge"],最長邊則按比例調整以保持輸入影像的寬高比。
  • resample (PILImageResampling filter, optional, defaults to self.resample) — 如果要調整影像大小,使用的 PILImageResampling 過濾器,例如 PILImageResampling.BILINEAR。僅當 do_resize 設定為 True 時生效。
  • do_center_crop (bool, optional, defaults to self.do_center_crop) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], optional, defaults to self.crop_size) — 中心裁剪的尺寸。僅當 do_center_crop 設定為 True 時生效。
  • do_rescale (bool, optional, defaults to self.do_rescale) — 是否將影像畫素值縮放到 [0 - 1] 之間。
  • rescale_factor (float, optional, defaults to self.rescale_factor) — 當 do_rescale 設定為 True 時,用於縮放影像的因子。
  • do_normalize (bool, optional, defaults to self.do_normalize) — 是否對影像進行歸一化。
  • image_mean (float or list[float], optional, defaults to self.image_mean) — 當 do_normalize 設定為 True 時,用於歸一化的影像均值。
  • image_std (float or list[float], optional, defaults to self.image_std) — 當 do_normalize 設定為 True 時,用於歸一化的影像標準差。
  • return_tensors (str or TensorType, optional) — 返回的張量型別。可以是以下之一:
    • 未設定:返回一個 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, optional, defaults to ChannelDimension.FIRST) — 輸出影像的通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • 未設定:使用輸入影像的通道維度格式。
  • input_data_format (ChannelDimension or str, optional) — 輸入影像的通道維度格式。如果未設定,則從輸入影像中推斷通道維度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:影像格式為 (num_channels, height, width)。
    • "channels_last"ChannelDimension.LAST:影像格式為 (height, width, num_channels)。
    • "none"ChannelDimension.NONE:影像格式為 (height, width)。

預處理一張或一批影像。

MobileNetV2ImageProcessorFast

class transformers.MobileNetV2ImageProcessorFast

< >

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

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

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, optional) — 是否調整影像大小。
  • size (dict[str, int], optional) — 描述模型的最大輸入尺寸。
  • default_to_square (bool, optional) — 如果 size 是一個整數,在調整大小時是否預設為方形影像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 調整影像大小時使用的重取樣過濾器。可以是 PILImageResampling 列舉之一。僅當 do_resize 設定為 True 時生效。
  • do_center_crop (bool, optional) — 是否對影像進行中心裁剪。
  • crop_size (dict[str, int], optional) — 應用 center_crop 後輸出影像的尺寸。
  • do_rescale (bool, optional) — 是否對影像進行縮放。
  • rescale_factor (Union[int, float, NoneType]) — 當 do_rescale 設定為 True 時,用於縮放影像的因子。
  • do_normalize (bool, optional) — 是否對影像進行歸一化。
  • image_mean (Union[float, list[float], NoneType]) — 用於歸一化的影像均值。僅當 do_normalize 設定為 True 時生效。
  • image_std (Union[float, list[float], NoneType]) — 用於歸一化的影像標準差。僅當 do_normalize 設定為 True 時生效。
  • do_convert_rgb (bool, optional) — 是否將影像轉換為 RGB 格式。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果設定為 `pt`,則返回堆疊的張量,否則返回張量列表。
  • data_format (~image_utils.ChannelDimension, optional) — 僅支援 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, optional) — 處理影像的裝置。如果未設定,則從輸入影像中推斷裝置。
  • disable_grouping (bool, optional) — 是否停用按尺寸對影像進行分組,以便單獨處理而不是分批處理。如果為 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張量。

post_process_semantic_segmentation

< >

( outputs target_sizes: typing.Optional[list[tuple]] = None ) semantic_segmentation

引數

  • outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始輸出。
  • target_sizes (長度為 batch_sizelist[Tuple]optional) — 與每個預測請求的最終尺寸(高度,寬度)相對應的元組列表。如果未設定,則不會調整預測大小。

返回

語義分割

長度為 `batch_size` 的 `list[torch.Tensor]`,其中每個元素是一個形狀為 (height, width) 的語義分割圖,對應於 target_sizes 中的條目(如果指定了 `target_sizes`)。每個 `torch.Tensor` 的每個條目對應一個語義類別 ID。

MobileNetV2ForSemanticSegmentation 的輸出轉換為語義分割圖。僅支援 PyTorch。

MobileNetV2Model

class transformers.MobileNetV2Model

< >

( config: MobileNetV2Config add_pooling_layer: bool = True )

引數

  • config (MobileNetV2Config) — 包含模型所有引數的模型配置類。使用配置檔案初始化不會載入與模型相關的權重,只會載入配置。請檢視 from_pretrained() 方法來載入模型權重。
  • add_pooling_layer (bool, optional, defaults to True) — 是否新增池化層

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

該模型繼承自 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 時),根據配置(MobileNetV2Config)和輸入包含不同的元素。

  • 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)

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

MobileNetV2Model 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會靜默地忽略它們。

示例

MobileNetV2ForImageClassification

class transformers.MobileNetV2ForImageClassification

< >

( config: MobileNetV2Config )

引數

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

帶有一個影像分類頭的 MobileNetV2 模型(在池化特徵之上加一個線性層),例如用於 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=False 或當 config.return_dict=False 時),根據配置(MobileNetV2Config)和輸入包含不同的元素。

  • 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)。模型在每個階段輸出的隱藏狀態(也稱為特徵圖)。

MobileNetV2ForImageClassification 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import AutoImageProcessor, MobileNetV2ForImageClassification
>>> 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_v2_1.0_224")
>>> model = MobileNetV2ForImageClassification.from_pretrained("google/mobilenet_v2_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])
...

MobileNetV2ForSemanticSegmentation

class transformers.MobileNetV2ForSemanticSegmentation

< >

( config: MobileNetV2Config )

引數

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

帶有一個語義分割頭的 MobileNetV2 模型,例如用於 Pascal VOC。

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

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

forward

< >

( pixel_values: typing.Optional[torch.Tensor] = None labels: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) transformers.modeling_outputs.SemanticSegmenterOutputtuple(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} 處理影像)。
  • labels (torch.LongTensor,形狀為 (batch_size, height, width)可選) — 用於計算損失的真實語義分割圖。索引應在 [0, ..., config.num_labels - 1] 範圍內。如果 config.num_labels > 1,則計算分類損失(交叉熵)。
  • output_hidden_states (bool可選) — 是否返回所有層的隱藏狀態。有關更多詳細資訊,請參閱返回張量下的 hidden_states
  • return_dict (bool可選) — 是否返回一個 ModelOutput 而不是一個普通的元組。

返回

transformers.modeling_outputs.SemanticSegmenterOutputtuple(torch.FloatTensor)

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

  • loss (形狀為 (1,)torch.FloatTensor可選,當提供 labels 時返回) — 分類損失(如果 config.num_labels==1,則為迴歸損失)。

  • logits (形狀為 (batch_size, config.num_labels, logits_height, logits_width)torch.FloatTensor) — 每個畫素的分類分數。

    返回的 logits 的尺寸不一定與作為輸入傳遞的 pixel_values 相同。這是為了避免進行兩次插值並在使用者需要將 logits 調整到原始影像尺寸作為後處理時損失一些質量。您應始終檢查 logits 的形狀並根據需要進行調整。

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

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

  • attentions (tuple(torch.FloatTensor)可選,當傳遞 output_attentions=Trueconfig.output_attentions=True 時返回) — torch.FloatTensor 的元組(每層一個),形狀為 (batch_size, num_heads, patch_size, sequence_length)

    注意力 softmax 後的注意力權重,用於計算自注意力頭中的加權平均值。

MobileNetV2ForSemanticSegmentation 的前向方法,重寫了 __call__ 特殊方法。

雖然前向傳播的流程需要在此函式內定義,但之後應呼叫 Module 例項而不是此函式,因為前者會處理執行前處理和後處理步驟,而後者會靜默地忽略它們。

示例

>>> from transformers import AutoImageProcessor, MobileNetV2ForSemanticSegmentation
>>> from PIL import Image
>>> import requests

>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> image_processor = AutoImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")
>>> model = MobileNetV2ForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513")

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

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

>>> # logits are of shape (batch_size, num_labels, height, width)
>>> logits = outputs.logits
< > 在 GitHub 上更新

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