Transformers 文档
MobileNet V2
并获得增强的文档体验
开始使用
MobileNet V2
MobileNet V2 通过更高效的架构提升了在移动设备上的性能。它使用倒置残差块(inverted residual blocks)和线性瓶颈(linear bottlenecks)来处理数据,首先将数据压缩到一个较小的表示,然后扩展进行处理,最后再次收缩以减少计算量。该模型还移除了非线性激活函数,以在简化设计的同时保持准确性。与 MobileNet V1 类似,它也使用深度可分离卷积(depthwise separable convolutions)来提高效率。
你可以在 Google 组织下找到所有原始的 MobileNet checkpoints。
点击右侧边栏中的 MobileNet V2 模型,查看更多关于如何将 MobileNet 应用于不同视觉任务的示例。
以下示例演示了如何使用 Pipeline 或 AutoModel 类对图像进行分类。
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 (
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
< 源码 >( 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
或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
< 源码 >( 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 toTrue
) — 是否将图像的(高度、宽度)尺寸调整为指定的size
。可在preprocess
方法中通过 `do_resize` 参数覆盖。 - size (
dict[str, int]
optional, defaults to{"shortest_edge": 256}
): 调整大小后的图像尺寸。图像的最短边将调整为 size["shortest_edge"],最长边则按比例调整以保持输入图像的宽高比。可在preprocess
方法中通过size
参数覆盖。 - resample (
PILImageResampling
, optional, defaults toPILImageResampling.BILINEAR
) — 调整图像大小时使用的重采样过滤器。可在preprocess
方法中通过resample
参数覆盖。 - do_center_crop (
bool
, optional, defaults toTrue
) — 是否对图像进行中心裁剪。如果输入尺寸的任何一边小于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 toTrue
) — 是否按指定的缩放比例rescale_factor
对图像进行缩放。可在preprocess
方法中通过do_rescale
参数覆盖。 - rescale_factor (
int
orfloat
, optional, defaults to1/255
) — 缩放图像时使用的缩放因子。可在preprocess
方法中通过rescale_factor
参数覆盖。 - do_normalize — 是否对图像进行归一化。可在
preprocess
方法中通过do_normalize
参数覆盖。 - image_mean (
float
orlist[float]
, optional, defaults toIMAGENET_STANDARD_MEAN
) — 对图像进行归一化时使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可在preprocess
方法中通过image_mean
参数覆盖。 - image_std (
float
orlist[float]
, optional, defaults toIMAGENET_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.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 toself.do_resize
) — 是否调整图像大小。 - size (
dict[str, int]
, optional, defaults toself.size
) — 调整大小后的图像尺寸。图像的最短边调整为 size["shortest_edge"],最长边则按比例调整以保持输入图像的宽高比。 - resample (
PILImageResampling
filter, optional, defaults toself.resample
) — 如果要调整图像大小,使用的PILImageResampling
过滤器,例如PILImageResampling.BILINEAR
。仅当do_resize
设置为True
时生效。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
dict[str, int]
, optional, defaults toself.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
orlist[float]
, optional, defaults toself.image_mean
) — 当do_normalize
设置为True
时,用于归一化的图像均值。 - image_std (
float
orlist[float]
, optional, defaults toself.image_std
) — 当do_normalize
设置为True
时,用于归一化的图像标准差。 - return_tensors (
str
orTensorType
, 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
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。- 未设置:使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
orstr
, 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
< source >( **kwargs: typing_extensions.Unpack[transformers.image_processing_utils_fast.DefaultFastImageProcessorKwargs] )
构建一个快速的 Mobilenet V2 图像处理器。
preprocess
< source >( 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
< source >( outputs target_sizes: typing.Optional[list[tuple]] = None ) → semantic_segmentation
参数
- outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
- target_sizes (长度为
batch_size
的list[Tuple]
,optional) — 与每个预测请求的最终尺寸(高度,宽度)相对应的元组列表。如果未设置,则不会调整预测大小。
返回
语义分割
长度为 `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() 方法来加载模型权重。
- add_pooling_layer (
bool
, optional, defaults toTrue
) — 是否添加池化层
基础的 Mobilenet V2 模型,输出原始的隐藏状态,顶部没有任何特定的头。
该模型继承自 PreTrainedModel。请查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个 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 (
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.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
实例而不是此函数,因为前者会处理运行前处理和后处理步骤,而后者会静默地忽略它们。
MobileNetV2ForImageClassification
class transformers.MobileNetV2ForImageClassification
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
带有一个图像分类头的 MobileNetV2 模型(在池化特征之上加一个线性层),例如用于 ImageNet。
该模型继承自 PreTrainedModel。请查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个 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 (
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.ImageClassifierOutputWithNoAttention 或 tuple(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=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")
>>> 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
< source >( config: MobileNetV2Config )
参数
- config (MobileNetV2Config) — 包含模型所有参数的模型配置类。使用配置文件进行初始化不会加载与模型关联的权重,只会加载配置。请查看 from_pretrained() 方法来加载模型权重。
带有一个语义分割头的 MobileNetV2 模型,例如用于 Pascal VOC。
该模型继承自 PreTrainedModel。请查看超类文档,了解库为所有模型实现的通用方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。
该模型也是一个 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.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.SemanticSegmenterOutput 或 tuple(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=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