Transformers 4.37 中文文档(六十九)(3)

简介: Transformers 4.37 中文文档(六十九)

Transformers 4.37 中文文档(六十九)(2)https://developer.aliyun.com/article/1564102


MobileNetV1Model

class transformers.MobileNetV1Model

<来源>

( config: MobileNetV1Config add_pooling_layer: bool = True )

参数

  • config(MobileNetV1Config) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。查看 from_pretrained()方法以加载模型权重。

裸的 MobileNetV1 模型输出原始的隐藏状态,没有特定的头部。这个模型是 PyTorch 的torch.nn.Module子类。将其用作常规的 PyTorch 模块,并参考 PyTorch 文档以获取有关一般用法和行为的所有相关信息。

forward

<来源>

( pixel_values: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → export const metadata = 'undefined';transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为(batch_size, num_channels, height, width)) — 像素值。可以使用 AutoImageProcessor 获取像素值。有关详细信息,请参阅 MobileNetV1ImageProcessor.call()。
  • output_hidden_states (booloptional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通的元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention或一个torch.FloatTensor元组(如果传递return_dict=Falseconfig.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), optional, 当传递output_hidden_states=Trueconfig.output_hidden_states=True时返回) — 形状为(batch_size, num_channels, height, width)torch.FloatTensor元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)。
    模型在每一层输出处的隐藏状态以及可选的初始嵌入输出。

MobileNetV1Model 的前向方法,覆盖了__call__特殊方法。

虽然前向传递的方法需要在这个函数内定义,但应该在此之后调用Module实例,而不是这个,因为前者会处理运行前后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoImageProcessor, MobileNetV1Model
>>> 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 = MobileNetV1Model.from_pretrained("google/mobilenet_v1_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, 1024, 7, 7]

MobileNetV1ForImageClassification

class transformers.MobileNetV1ForImageClassification

<来源>

( config: MobileNetV1Config )

参数

  • config (MobileNetV1Config) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型相关的权重,只加载配置。查看 from_pretrained()方法以加载模型权重。

MobileNetV1 模型,顶部带有图像分类头(在池化特征之上的线性层),例如用于 ImageNet。

这个模型是 PyTorch torch.nn.Module的子类。将其用作常规的 PyTorch 模块,并参考 PyTorch 文档以获取有关一般用法和行为的所有信息。

forward

<来源>

( pixel_values: Optional = None output_hidden_states: Optional = None labels: Optional = None return_dict: Optional = None ) → export const metadata = 'undefined';transformers.modeling_outputs.ImageClassifierOutputWithNoAttention or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor,形状为(batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 MobileNetV1ImageProcessor.call()。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关更多详细信息,请查看返回张量下的hidden_states
  • return_dict (bool可选) — 是否返回 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时)包含各种元素,这取决于配置(MobileNetV1Config)和输入。

  • 损失 (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), optional, 当传递output_hidden_states=Trueconfig.output_hidden_states=True时返回) — torch.FloatTensor 元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每个阶段的输出),形状为 (batch_size, num_channels, height, width)。模型在每个阶段输出的隐藏状态(也称为特征图)。

MobileNetV1ForImageClassification 的前向方法,覆盖了__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])
tabby, tabby cat

MobileNet V2

原文链接:huggingface.co/docs/transformers/v4.37.2/en/model_doc/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 填充行为,请创建一个 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

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, optional, defaults to 3) — 输入通道数。
  • image_size (int, optional, defaults to 224) — 每个图像的大小(分辨率)。
  • depth_multiplier (float, optional, defaults to 1.0) — 收缩或扩展每一层的通道数。默认为 1.0,网络从 32 个通道开始。有时也称为“alpha”或“宽度乘数”。
  • depth_divisible_by (int, optional, defaults to 8) — 每一层的通道数将始终是这个数字的倍数。
  • min_depth (int, optional, defaults to 8) — 所有层至少具有这么多通道。
  • expand_ratio (float, optional, defaults to 6.0) — 每个块中第一层的输出通道数是输入通道数乘以扩展比率。
  • output_stride (int, optional, defaults to 32) — 输入和输出特征图的空间分辨率之间的比率。默认情况下,模型将输入维度减小 32 倍。如果output_stride为 8 或 16,则模型在深度层上使用扩张卷积而不是常规卷积,以确保特征图永远不会比输入图像小 8 倍或 16 倍。
  • first_layer_is_expansion (bool, optional, defaults to True) — 如果第一个卷积层也是第一个扩展块的扩展层,则为 True。
  • finegrained_output (bool, optional, defaults to True) — 如果为真,则最终卷积层中的输出通道数将保持较大(1280),即使depth_multiplier小于 1。
  • hidden_act (strfunction可选,默认为 "relu6") — Transformer 编码器和卷积层中的非线性激活函数(函数或字符串)。
  • tf_padding (bool可选,默认为 True) — 是否在卷积层上使用 TensorFlow 填充规则。
  • classifier_dropout_prob (float可选,默认为 0.8) — 附加分类器的丢失比率。
  • initializer_range (float可选,默认为 0.02) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • 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: Union do_resize: Optional = None size: Dict = None resample: Resampling = None do_center_crop: bool = None crop_size: Dict = None do_rescale: Optional = None rescale_factor: Optional = None do_normalize: Optional = None image_mean: Union = None image_std: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None **kwargs )

参数

  • 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: 图像格式为 (通道数, 高度, 宽度)。
  • "channels_last"ChannelDimension.LAST: 图像格式为 (高度, 宽度, 通道数)。
  • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr可选) — 输入图像的通道维度格式。如果未设置,则从输入图像中推断通道维度格式。可以是以下之一:
  • "channels_first"ChannelDimension.FIRST: 图像格式为 (通道数, 高度, 宽度)。
  • "channels_last"ChannelDimension.LAST: 图像格式为 (高度, 宽度, 通道数)。
  • "none"ChannelDimension.NONE: 图像格式为 (高度, 宽度)。

预处理图像或图像批处理。

post_process_semantic_segmentation

<来源>

( outputs target_sizes: List = None ) → export const metadata = 'undefined';semantic_segmentation

参数

  • outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (List[Tuple],长度为 batch_size可选) — 每个预测的请求最终尺寸 (高度, 宽度) 对应的元组列表。如果未设置,预测将不会被调整大小。

返回

语义分割

List[torch.Tensor],长度为 batch_size,其中每个项目是形状为 (高度, 宽度) 的语义分割地图,对应于 target_sizes 条目(如果指定了 target_sizes)。每个 torch.Tensor 的每个条目对应一个语义类别 id。

将 MobileNetV2ForSemanticSegmentation 的输出转换为语义分割地图。仅支持 PyTorch。

MobileNetV2ImageProcessor

class transformers.MobileNetV2ImageProcessor

<来源>

( do_resize: bool = True size: Optional = None resample: Resampling = <Resampling.BILINEAR: 2> do_center_crop: bool = True crop_size: Dict = None do_rescale: bool = True rescale_factor: Union = 0.00392156862745098 do_normalize: bool = True image_mean: Union = None image_std: Union = 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 (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。可以被 preprocess 方法中的 rescale_factor 参数覆盖。是否归一化图像。可以被 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatList[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果归一化图像,则使用的均值。这是一个浮点数或与图像中通道数相同长度的浮点数列表。可以被 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatList[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果归一化图像,则使用的标准差。这是一个浮点数或与图像中通道数相同长度的浮点数列表。可以被 preprocess 方法中的 image_std 参数覆盖。

构建一个 MobileNetV2 图像处理器。

preprocess

< source >

( images: Union do_resize: Optional = None size: Dict = None resample: Resampling = None do_center_crop: bool = None crop_size: Dict = None do_rescale: Optional = None rescale_factor: Optional = None do_normalize: Optional = None image_mean: Union = None image_std: Union = None return_tensors: Union = None data_format: Union = <ChannelDimension.FIRST: 'channels_first'> input_data_format: Union = None **kwargs )

参数

  • 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:图像以(高度,宽度,通道数)格式。
  • "none"ChannelDimension.NONE:图像以(高度,宽度)格式。

预处理一张图片或一批图片。

post_process_semantic_segmentation

< source >

( outputs target_sizes: List = None ) → export const metadata = 'undefined';semantic_segmentation

参数

  • outputs (MobileNetV2ForSemanticSegmentation) — 模型的原始输出。
  • target_sizes (List[Tuple] of length batch_size, optional) — 与每个预测的请求最终大小(高度,宽度)对应的元组列表。如果未设置,预测将不会被调整大小。

返回

语义分割

List[torch.Tensor],长度为batch_size,每个项目是一个形状为(高度,宽度)的语义分割地图,对应于目标大小条目(如果指定了target_sizes)。每个torch.Tensor的每个条目对应于一个语义类别 ID。

将 MobileNetV2ForSemanticSegmentation 的输出转换为语义分割地图。仅支持 PyTorch。

MobileNetV2Model

class transformers.MobileNetV2Model

< source >

( config: MobileNetV2Config add_pooling_layer: bool = True )

参数

  • config (MobileNetV2Config) — 具有模型所有参数的模型配置类。使用配置文件初始化不会加载与模型关联的权重,只加载配置。查看 from_pretrained()方法以加载模型权重。

裸的 MobileNetV2 模型输出原始的隐藏状态,没有特定的头部。这个模型是一个 PyTorch torch.nn.Module子类。将其用作常规的 PyTorch 模块,并参考 PyTorch 文档以获取有关一般用法和行为的所有相关信息。

forward

< source >

( pixel_values: Optional = None output_hidden_states: Optional = None return_dict: Optional = None ) → export const metadata = 'undefined';transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention or tuple(torch.FloatTensor)

参数

  • pixel_values (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 像素值。像素值可以使用 AutoImageProcessor 获取。有关详细信息,请参阅 MobileNetV2ImageProcessor.call()。
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关更多详细信息,请参阅返回张量下的hidden_states
  • return_dict (bool, optional) — 是否返回一个 ModelOutput 而不是一个普通元组。

返回

transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttentiontuple(torch.FloatTensor)

一个transformers.modeling_outputs.BaseModelOutputWithPoolingAndNoAttention或一个torch.FloatTensor元组(如果传递了return_dict=Falseconfig.return_dict=False时)包含根据配置(MobileNetV2Config)和输入的不同元素。

  • last_hidden_state (torch.FloatTensor of shape (batch_size, num_channels, height, width)) — 模型最后一层的隐藏状态序列。
  • pooler_output (torch.FloatTensor of shape (batch_size, hidden_size)) — 空间维度上进行池化操作后的最后一层隐藏状态。
  • hidden_statestuple(torch.FloatTensor)可选,当传递output_hidden_states=True或当config.output_hidden_states=True时返回)— 形状为(batch_size, num_channels, height, width)torch.FloatTensor元组(一个用于嵌入层的输出,如果模型有嵌入层,+ 一个用于每一层的输出)。
    模型在每一层输出处的隐藏状态以及可选的初始嵌入输出。

MobileNetV2Model 的 forward 方法覆盖了__call__特殊方法。

虽然前向传递的步骤需要在此函数内定义,但应该在此之后调用Module实例,而不是在此处调用,因为前者会处理运行前后处理步骤,而后者会默默地忽略它们。

示例:

>>> from transformers import AutoImageProcessor, MobileNetV2Model
>>> 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 = 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]


Transformers 4.37 中文文档(六十九)(4)https://developer.aliyun.com/article/1564104

相关文章
|
3月前
|
编解码 PyTorch 算法框架/工具
Transformers 4.37 中文文档(七十一)(3)
Transformers 4.37 中文文档(七十一)
30 1
|
3月前
|
自然语言处理 PyTorch TensorFlow
Transformers 4.37 中文文档(六十一)(2)
Transformers 4.37 中文文档(六十一)
48 1
|
3月前
|
算法框架/工具 异构计算 索引
Transformers 4.37 中文文档(六十一)(3)
Transformers 4.37 中文文档(六十一)
25 1
|
3月前
|
PyTorch 定位技术 算法框架/工具
Transformers 4.37 中文文档(六十九)(1)
Transformers 4.37 中文文档(六十九)
19 0
|
3月前
|
机器学习/深度学习 编解码 PyTorch
Transformers 4.37 中文文档(六十九)(4)
Transformers 4.37 中文文档(六十九)
29 0
|
3月前
|
编解码 PyTorch TensorFlow
Transformers 4.37 中文文档(六十九)(2)
Transformers 4.37 中文文档(六十九)
17 0
|
3月前
|
PyTorch TensorFlow 算法框架/工具
Transformers 4.37 中文文档(六十九)(5)
Transformers 4.37 中文文档(六十九)
30 0
|
3月前
|
存储 PyTorch 定位技术
Transformers 4.37 中文文档(七十一)(1)
Transformers 4.37 中文文档(七十一)
51 0
|
3月前
|
机器学习/深度学习 PyTorch TensorFlow
Transformers 4.37 中文文档(七十一)(2)
Transformers 4.37 中文文档(七十一)
25 0
|
3月前
|
PyTorch TensorFlow 算法框架/工具
Transformers 4.37 中文文档(七十一)(4)
Transformers 4.37 中文文档(七十一)
20 0