Transformers 文档
MobileNet V2
并获取增强的文档体验
开始使用
MobileNet V2
概述
MobileNet 模型在 MobileNetV2: Inverted Residuals and Linear Bottlenecks 中被提出,作者是 Mark Sandler、Andrew Howard、Menglong Zhu、Andrey Zhmoginov、Liang-Chieh Chen。
以下是论文的摘要
在本文中,我们描述了一种新的移动架构 MobileNetV2,它提高了移动模型在多项任务和基准测试中的最先进性能,以及不同模型尺寸范围内的性能。我们还描述了将这些移动模型应用于对象检测的有效方法,在一个我们称之为 SSDLite 的新框架中。此外,我们还演示了如何通过简化形式的 DeepLabv3 构建移动语义分割模型,我们称之为 Mobile DeepLabv3。
MobileNetV2 架构基于倒残差结构,其中残差块的输入和输出是薄瓶颈层,这与传统的残差模型相反,后者在输入中使用扩展表示。MobileNetV2 使用轻量级深度可分离卷积来过滤中间扩展层中的特征。此外,我们发现去除窄层中的非线性对于保持表示能力非常重要。我们证明这提高了性能,并提供了一个导致这种设计的直觉。最后,我们的方法允许将输入/输出域与转换的表达性解耦,这为进一步分析提供了方便的框架。我们在 Imagenet 分类、COCO 对象检测、VOC 图像分割上衡量了我们的性能。我们评估了准确率与操作次数(以乘加运算 (MAdd) 衡量)以及参数数量之间的权衡。
此模型由 matthijs 贡献。原始代码和权重可以在 此处找到主模型,以及 此处找到 DeepLabV3+。
使用技巧
检查点被命名为 mobilenet_v2_depth_size,例如 mobilenet_v2_1.0_224,其中 1.0 是深度乘数(有时也称为 “alpha” 或宽度乘数),而 224 是模型训练所用输入图像的分辨率。
即使检查点是在特定尺寸的图像上训练的,该模型也适用于任何尺寸的图像。最小支持的图像尺寸为 32x32。
可以使用 MobileNetV2ImageProcessor 来为模型准备图像。
可用的图像分类检查点是在 ImageNet-1k(也称为 ILSVRC 2012,包含 130 万张图像和 1,000 个类别的集合)上预训练的。但是,该模型预测 1001 个类别:来自 ImageNet 的 1000 个类别加上一个额外的 “背景” 类别(索引 0)。
分割模型使用 DeepLabV3+ 头部。可用的语义分割检查点是在 PASCAL VOC 上预训练的。
原始 TensorFlow 检查点使用的填充规则与 PyTorch 不同,需要模型在推理时确定填充量,因为这取决于输入图像的大小。要使用原生 PyTorch 填充行为,请创建一个
tf_padding = False
的 MobileNetV2Config。
不支持的功能
MobileNetV2Model 输出最后一个隐藏状态的全局池化版本。在原始模型中,可以使用固定 7x7 窗口和步幅 1 的平均池化层来代替全局池化。对于大于建议图像尺寸的输入,这将产生大于 1x1 的池化输出。Hugging Face 实现不支持此功能。
原始 TensorFlow 检查点包含量化模型。我们不支持这些模型,因为它们包含额外的 “FakeQuantization” 操作来反量化权重。
通常的做法是从索引 10 和 13 的扩展层以及最终的 1x1 卷积层中提取输出,用于下游目的。使用
output_hidden_states=True
返回所有中间层的输出。目前无法将其限制为特定层。DeepLabV3+ 分割头不使用来自骨干网络的最终卷积层,但无论如何都会计算该层。目前无法告知 MobileNetV2Model 它应该运行到哪一层。
资源
以下是官方 Hugging Face 和社区(🌎 表示)资源列表,可帮助您开始使用 MobileNetV2。
- MobileNetV2ForImageClassification 由此 示例脚本 和 notebook 支持。
- 另请参阅:图像分类任务指南
语义分割
如果您有兴趣提交资源以包含在此处,请随时打开 Pull Request,我们将对其进行审核!该资源最好能展示一些新的东西,而不是重复现有资源。
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,则模型在深度卷积层上使用空洞卷积而不是常规卷积,以便特征图永远不会比输入图像小 8 倍或 16 倍以上。 - first_layer_is_expansion (
bool
, 可选, 默认为True
) — 如果第一个卷积层也是第一个扩展块的扩展层,则为 True。 - finegrained_output (
bool
, 可选, 默认为True
) — 如果为 true,即使depth_multiplier
小于 1,最终卷积层中的输出通道数也将保持较大值 (1280)。 - hidden_act (
str
或function
, 可选, 默认为"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
preprocess
< source >( 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.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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 (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果do_normalize
设置为True
,则使用的图像均值。 - image_std (
float
或List[float]
, 可选, 默认值是self.image_std
) — 如果do_normalize
设置为True
,则使用的图像标准差。 - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认值是ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"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
< source >( outputs target_sizes: typing.List[typing.Tuple] = None ) → semantic_segmentation
参数
- outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes (长度为
batch_size
的List[Tuple]
, 可选) — 与每个预测请求的最终尺寸(高度,宽度)相对应的元组列表。如果未设置,则不会调整预测大小。
返回值
semantic_segmentation
长度为 batch_size
的 List[torch.Tensor]
,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes
条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MobileNetV2ForSemanticSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
MobileNetV2ImageProcessor
class transformers.MobileNetV2ImageProcessor
< source >( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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
或float
, 可选, 默认值是1/255
) — 如果重新缩放图像,则使用的比例因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize — 是否标准化图像。可以被
preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认值是IMAGENET_STANDARD_MEAN
) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度是图像中通道的数量。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认值是IMAGENET_STANDARD_STD
) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度是图像中通道的数量。可以被preprocess
方法中的image_std
参数覆盖。
构建 MobileNetV2 图像处理器。
preprocess
< source >( 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.Dict[str, int] = None resample: Resampling = None do_center_crop: bool = None crop_size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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 (
float
或List[float]
, 可选, 默认为self.image_mean
) — 如果do_normalize
设置为True
,则使用的图像均值。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 如果do_normalize
设置为True
,则使用的图像标准差。 - return_tensors (
str
或TensorType
, 可选) — 返回张量的类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:"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
< source >( outputs target_sizes: typing.List[typing.Tuple] = None ) → semantic_segmentation
参数
- outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes (长度为
batch_size
的List[Tuple]
, 可选) — 与每个预测的请求最终尺寸(高度,宽度)相对应的元组列表。如果未设置,则不会调整预测大小。
返回值
semantic_segmentation
长度为 batch_size
的 List[torch.Tensor]
,其中每个项目是形状为 (height, width) 的语义分割图,对应于 target_sizes
条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将 MobileNetV2ForSemanticSegmentation 的输出转换为语义分割图。仅支持 PyTorch。
MobileNetV2Model
class transformers.MobileNetV2Model
< source >( config: MobileNetV2Config add_pooling_layer: bool = True )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
裸 MobileNetV2 模型,输出原始隐藏状态,顶部没有任何特定的 head。此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( pixel_values: typing.Optional[torch.Tensor] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参见 MobileNetV2ImageProcessor.call()。 - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回 ModelOutput 而不是普通元组。
返回值
transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention
或 torch.FloatTensor
元组 (如果传递 return_dict=False
或当 config.return_dict=False
时),包含各种元素,具体取决于配置 (MobileNetV2Config) 和输入。
-
last_hidden_state (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 模型最后一层输出端的隐藏状态序列。 -
pooler_output (形状为
(batch_size, hidden_size)
的torch.FloatTensor
) — 在空间维度上进行池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
元组(对于嵌入的输出,如果模型具有嵌入层,则为一个;对于每一层的输出,则为一个),形状为(batch_size, num_channels, height, width)
。模型在每一层输出端的隐藏状态,加上可选的初始嵌入输出。
MobileNetV2Model 的 forward 方法,覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, MobileNetV2Model
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> image = dataset["test"]["image"][0]
>>> image_processor = AutoImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224")
>>> model = MobileNetV2Model.from_pretrained("google/mobilenet_v2_1.0_224")
>>> inputs = image_processor(image, return_tensors="pt")
>>> with torch.no_grad():
... outputs = model(**inputs)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 1280, 7, 7]
MobileNetV2ForImageClassification
class transformers.MobileNetV2ForImageClassification
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,仅加载配置。查看 from_pretrained() 方法来加载模型权重。
MobileNetV2 模型,顶部带有图像分类 head(池化特征之上的线性层),例如用于 ImageNet。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( 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.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
参数
- pixel_values (形状为
(batch_size, num_channels, height, width)
的torch.FloatTensor
) — 像素值。像素值可以使用 AutoImageProcessor 获得。有关详细信息,请参见 MobileNetV2ImageProcessor.call()。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
的形状为(batch_size,)
,可选) — 用于计算图像分类/回归损失的标签。索引应在[0, ..., config.num_labels - 1]
中。如果config.num_labels == 1
,则计算回归损失(均方损失)。如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.ImageClassifierOutputWithNoAttention 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (MobileNetV2Config) 和输入。
- loss (
torch.FloatTensor
的形状为(1,)
,可选,当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 - logits (
torch.FloatTensor
的形状为(batch_size, config.num_labels)
) — 分类(或回归,如果 config.num_labels==1)得分(在 SoftMax 之前)。 - hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(如果模型具有嵌入层,则为嵌入输出一个,+ 每个阶段的输出一个),形状为(batch_size, num_channels, height, width)
。 模型在每个阶段输出的隐藏状态(也称为特征图)。
MobileNetV2ForImageClassification forward 方法覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 Module
实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者会静默地忽略它们。
示例
>>> from transformers import AutoImageProcessor, MobileNetV2ForImageClassification
>>> import torch
>>> from datasets import load_dataset
>>> dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
>>> 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])
tabby, tabby cat
MobileNetV2ForSemanticSegmentation
class transformers.MobileNetV2ForSemanticSegmentation
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 模型配置类,包含模型的所有参数。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
带有语义分割头的 MobileNetV2 模型,例如用于 Pascal VOC。
此模型是 PyTorch torch.nn.Module 子类。将其用作常规 PyTorch 模块,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( 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.SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
参数
- pixel_values (
torch.FloatTensor
的形状为(batch_size, num_channels, height, width)
) — 像素值。 像素值可以使用 AutoImageProcessor 获得。 有关详细信息,请参见 MobileNetV2ImageProcessor.call()。 - output_hidden_states (
bool
, optional) — 是否返回所有层的隐藏状态。 有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, optional) — 是否返回 ModelOutput 而不是普通元组。 - labels (
torch.LongTensor
的形状为(batch_size, height, width)
,可选) — 用于计算损失的真值语义分割图。 索引应在[0, ..., config.num_labels - 1]
中。 如果config.num_labels > 1
,则计算分类损失(交叉熵损失)。
返回值
transformers.modeling_outputs.SemanticSegmenterOutput 或 tuple(torch.FloatTensor)
一个 transformers.modeling_outputs.SemanticSegmenterOutput 或一个 torch.FloatTensor
元组(如果传递了 return_dict=False
或当 config.return_dict=False
时),其中包含各种元素,具体取决于配置 (MobileNetV2Config) 和输入。
-
loss (
torch.FloatTensor
的形状为(1,)
,可选,当提供labels
时返回) — 分类(或回归,如果 config.num_labels==1)损失。 -
logits (
torch.FloatTensor
的形状为(batch_size, config.num_labels, logits_height, logits_width)
) — 每个像素的分类得分。返回的 logits 不一定与作为输入传递的
pixel_values
具有相同的大小。 这是为了避免进行两次插值,并在用户需要将 logits 调整为原始图像大小作为后处理时损失一些质量。 您应始终检查 logits 形状并根据需要调整大小。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(如果模型具有嵌入层,则为嵌入输出一个,+ 每个层的输出一个),形状为(batch_size, patch_size, hidden_size)
。模型在每一层输出端的隐藏状态,加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或当config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个),形状为(batch_size, num_heads, patch_size, sequence_length)
。注意力 softmax 之后的注意力权重,用于计算自注意力头中的加权平均值。
MobileNetV2ForSemanticSegmentation forward 方法覆盖了 __call__
特殊方法。
尽管 forward 传递的配方需要在该函数中定义,但应该在之后调用 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