MobileNet V2
概述
MobileNet模型由Mark Sandler、Andrew Howard、Menglong Zhu、Andrey Zhmoginov和Liang-Chieh Chen在MobileNetV2: Inverted Residuals and Linear Bottlenecks中提出。
论文的摘要如下:
在本文中,我们描述了一种新的移动架构,MobileNetV2,它在多个任务和基准测试中提高了移动模型的最先进性能,并且适用于各种不同的模型大小。我们还描述了在我们称为SSDLite的新框架中应用这些移动模型进行目标检测的有效方法。此外,我们展示了如何通过我们称为Mobile DeepLabv3的简化形式的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万张图像和1000个类别)上预训练的。然而,模型预测1001个类别:来自ImageNet的1000个类别加上一个额外的“背景”类别(索引0)。
分割模型使用了一个DeepLabV3+头。可用的语义分割检查点是在PASCAL VOC上预训练的。
原始的TensorFlow检查点使用与PyTorch不同的填充规则,要求模型在推理时确定填充量,因为这取决于输入图像的大小。要使用原生的PyTorch填充行为,请创建一个MobileNetV2Config,并设置
tf_padding = False
。
不支持的功能:
MobileNetV2Model 输出了最后一个隐藏状态的全局池化版本。在原始模型中,可以使用一个固定7x7窗口和步幅为1的平均池化层来代替全局池化。对于大于推荐图像尺寸的输入,这将产生一个大于1x1的池化输出。Hugging Face 的实现不支持这一点。
原始的TensorFlow检查点包括量化模型。我们不支持这些模型,因为它们包含额外的“FakeQuantization”操作来反量化权重。
通常为了下游目的,会从索引10和13的扩展层以及最终的1x1卷积层提取输出。使用
output_hidden_states=True
会返回所有中间层的输出。目前没有办法将其限制在特定层。DeepLabV3+ 分割头不使用来自主干的最终卷积层,但这一层仍然会被计算。目前没有办法告诉 MobileNetV2Model 它应该运行到哪一层。
资源
一份官方的Hugging Face和社区(由🌎表示)资源列表,帮助您开始使用MobileNetV2。
- MobileNetV2ForImageClassification 由这个 示例脚本 和 笔记本 支持。
- 另请参阅:图像分类任务指南
语义分割
如果您有兴趣提交资源以包含在此处,请随时打开一个 Pull Request,我们将进行审核!理想情况下,资源应展示一些新内容,而不是重复现有资源。
MobileNetV2Config
类 transformers.MobileNetV2Config
< source >( 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
, optional, defaults to 3) — 输入通道的数量。 - image_size (
int
, optional, defaults to 224) — 每张图片的大小(分辨率)。 - depth_multiplier (
float
, 可选, 默认为 1.0) — 缩小或扩展每层中的通道数。默认值为 1.0,这意味着网络从 32 个通道开始。这有时也被称为“alpha”或“宽度乘数”。 - depth_divisible_by (
int
, optional, defaults to 8) — 每一层的通道数将始终是这个数字的倍数。 - min_depth (
int
, optional, 默认为 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
) — 如果为真,即使depth_multiplier
小于 1,最终卷积层中的输出通道数仍将保持较大(1280)。 - hidden_act (
str
或function
, 可选, 默认为"relu6"
) — Transformer编码器和卷积层中的非线性激活函数(函数或字符串)。 - tf_padding (
bool
, optional, defaults toTrue
) — 是否在卷积层上使用TensorFlow的填充规则。 - classifier_dropout_prob (
float
, optional, defaults to 0.8) — 附加分类器的丢弃比率。 - initializer_range (
float
, 可选, 默认为 0.02) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - layer_norm_eps (
float
, optional, defaults to 0.001) — 层归一化层使用的epsilon值。 - semantic_loss_ignore_index (
int
, optional, 默认为 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
MobileNetV2特征提取器
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.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
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪. - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.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
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- 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 ) → 语义分割
参数
- 输出 (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
List[Tuple]
长度为batch_size
, 可选) — 对应于每个预测请求的最终大小(高度,宽度)的元组列表。如果未设置,预测将不会调整大小。
返回
语义分割
List[torch.Tensor]
长度为 batch_size
,其中每个项目是一个形状为 (高度, 宽度) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将MobileNetV2ForSemanticSegmentation的输出转换为语义分割图。仅支持PyTorch。
MobileNetV2ImageProcessor
类 transformers.MobileNetV2ImageProcessor
< source >( do_resize: bool = True size: typing.Optional[typing.Dict[str, int]] = None resample: Resampling =
参数
- 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图像处理器。
预处理
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List[ForwardRef('PIL.Image.Image')], typing.List[numpy.ndarray], typing.List[ForwardRef('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] =
参数
- 图像 (
ImageInput
) — 要预处理的图像。期望输入单个或批量的图像,像素值范围在0到255之间。如果传入的图像像素值在0到1之间,请设置do_rescale=False
. - do_resize (
bool
, optional, defaults toself.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
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 中心裁剪的大小。仅在do_center_crop
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的重新缩放因子。 - do_normalize (
bool
, optional, defaults toself.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
, 可选) — 返回的张量类型。可以是以下之一:- 未设置:返回一个
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
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- 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 ) → 语义分割
参数
- 输出 (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes (
List[Tuple]
长度为batch_size
, 可选) — 对应于每个预测请求的最终大小(高度,宽度)的元组列表。如果未设置, 预测将不会调整大小。
返回
语义分割
List[torch.Tensor]
长度为 batch_size
,其中每个项目是一个形状为 (高度, 宽度) 的语义分割图,对应于 target_sizes 条目(如果指定了 target_sizes
)。每个 torch.Tensor
的每个条目对应于一个语义类别 ID。
将MobileNetV2ForSemanticSegmentation的输出转换为语义分割图。仅支持PyTorch。
MobileNetV2Model
类 transformers.MobileNetV2Model
< source >( config: MobileNetV2Config add_pooling_layer: bool = True )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
裸的MobileNetV2模型输出原始隐藏状态,没有任何特定的头部。 这个模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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 (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用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 (
torch.FloatTensor
形状为(batch_size, num_channels, height, width)
) — 模型最后一层输出的隐藏状态序列。 -
pooler_output (
torch.FloatTensor
形状为(batch_size, hidden_size)
) — 在空间维度上进行池化操作后的最后一层隐藏状态。 -
hidden_states (
tuple(torch.FloatTensor)
, 可选, 当传递output_hidden_states=True
或当config.output_hidden_states=True
时返回) — 由torch.FloatTensor
组成的元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)形状为(batch_size, num_channels, height, width)
。模型在每一层输出处的隐藏状态加上可选的初始嵌入输出。
MobileNetV2Model 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
类 transformers.MobileNetV2ForImageClassification
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
MobileNetV2 模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于 ImageNet。
该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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 (
torch.FloatTensor
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileNetV2ImageProcessor.call(). - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个 ModelOutput 而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size,)
, optional) — 用于计算图像分类/回归损失的标签。索引应在[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 的前向方法,重写了 __call__
特殊方法。
尽管前向传递的配方需要在此函数内定义,但之后应该调用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
类 transformers.MobileNetV2ForSemanticSegmentation
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型相关的权重,只会加载配置。查看 from_pretrained() 方法以加载模型权重。
MobileNetV2模型,顶部带有语义分割头,例如用于Pascal VOC。
该模型是一个PyTorch torch.nn.Module 子类。将其用作常规的PyTorch模块,并参考PyTorch文档以获取与一般使用和行为相关的所有信息。
前进
< 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
of shape(batch_size, num_channels, height, width)
) — 像素值。像素值可以使用AutoImageProcessor获取。详情请参见 MobileNetV2ImageProcessor.call(). - output_hidden_states (
bool
, 可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请参见返回张量下的hidden_states
。 - return_dict (
bool
, 可选) — 是否返回一个ModelOutput而不是一个普通的元组。 - labels (
torch.LongTensor
of shape(batch_size, height, width)
, optional) — 用于计算损失的真实语义分割图。索引应在[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 的前向方法,重写了 __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