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 上更新