Transformers 文档

特征提取器

特征提取器

特征提取器负责为音频或视觉模型准备输入特征。这包括从序列中提取特征,例如预处理音频文件以生成对数梅尔频谱图特征,从图像中提取特征,例如裁剪图像文件,还包括填充、归一化以及转换为NumPy、PyTorch和TensorFlow张量。

FeatureExtractionMixin

transformers.FeatureExtractionMixin

< >

( **kwargs )

这是一个特征提取混入,用于为序列和图像特征提取器提供保存/加载功能。

from_pretrained

< >

( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[bool, str, NoneType] = None revision: str = 'main' **kwargs )

参数

  • pretrained_model_name_or_path (stros.PathLike) — 这可以是以下之一:
    • 一个字符串,表示托管在 huggingface.co 上的模型仓库中的预训练特征提取器的 模型 id
    • 一个包含使用 save_pretrained() 方法保存的特征提取器文件的 目录 的路径,例如, ./my_model_directory/
    • 一个保存的特征提取器 JSON 文件 的路径或 URL,例如, ./my_model_directory/preprocessor_config.json
  • cache_dir (stros.PathLike, 可选) — 如果不应使用标准缓存,则应缓存下载的预训练模型特征提取器的目录路径。
  • force_download (bool, 可选, 默认为 False) — 是否强制(重新)下载特征提取器文件并覆盖缓存版本(如果存在)。
  • resume_download — 已弃用并被忽略。现在默认情况下,所有下载在可能的情况下都会自动恢复。 将在Transformers的v5版本中移除。
  • proxies (Dict[str, str], 可选) — 一个按协议或端点使用的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. 这些代理会在每个请求中使用。
  • token (strbool, 可选) — 用于远程文件的HTTP承载授权的令牌。如果为 True 或未指定,将使用运行 huggingface-cli login 时生成的令牌(存储在 ~/.huggingface 中)。
  • revision (str, 可选, 默认为 "main") — 要使用的特定模型版本。它可以是分支名称、标签名称或提交ID,因为我们使用基于git的系统在huggingface.co上存储模型和其他工件,所以revision可以是git允许的任何标识符。

从特征提取器实例化一种FeatureExtractionMixin类型,例如一个 SequenceFeatureExtractor的派生类。

示例:

# We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
# derived class: *Wav2Vec2FeatureExtractor*
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
    "facebook/wav2vec2-base-960h"
)  # Download feature_extraction_config from huggingface.co and cache.
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
    "./test/saved_model/"
)  # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')*
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json")
feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
    "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False
)
assert feature_extractor.return_attention_mask is False
feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
    "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
)
assert feature_extractor.return_attention_mask is False
assert unused_kwargs == {"foo": False}

save_pretrained

< >

( save_directory: typing.Union[str, os.PathLike] push_to_hub: bool = False **kwargs )

参数

  • save_directory (str or os.PathLike) — 特征提取器 JSON 文件将被保存的目录(如果不存在将被创建)。
  • push_to_hub (bool, optional, defaults to False) — 是否在保存后将模型推送到 Hugging Face 模型中心。您可以使用 repo_id 指定要推送到的仓库(默认为您命名空间中 save_directory 的名称)。
  • kwargs (Dict[str, Any], 可选) — 传递给 push_to_hub() 方法的额外关键字参数。

将feature_extractor对象保存到目录save_directory中,以便可以使用 from_pretrained()类方法重新加载。

SequenceFeatureExtractor

transformers.SequenceFeatureExtractor

< >

( feature_size: int sampling_rate: int padding_value: float **kwargs )

参数

  • feature_size (int) — 提取特征的特征维度。
  • sampling_rate (int) — 音频文件应被数字化的采样率,以赫兹(Hz)表示。
  • padding_value (float) — 用于填充填充值/向量的值。

这是一个用于语音识别的通用特征提取类。

pad

< >

( processed_features: typing.Union[transformers.feature_extraction_utils.BatchFeature, typing.List[transformers.feature_extraction_utils.BatchFeature], typing.Dict[str, transformers.feature_extraction_utils.BatchFeature], typing.Dict[str, typing.List[transformers.feature_extraction_utils.BatchFeature]], typing.List[typing.Dict[str, transformers.feature_extraction_utils.BatchFeature]]] padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = True max_length: typing.Optional[int] = None truncation: bool = False pad_to_multiple_of: typing.Optional[int] = None return_attention_mask: typing.Optional[bool] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None )

参数

  • processed_features (BatchFeature, list of BatchFeature, Dict[str, List[float]], Dict[str, List[List[float]] or List[Dict[str, List[float]]]) — Processed inputs. Can represent one input (BatchFeature or Dict[str, List[float]]) or a batch of input values / vectors (list of BatchFeature, Dict[str, List[List[float]]] or List[Dict[str, List[float]]]) so you can use this method during preprocessing as well as in a PyTorch Dataloader collate function.

    你可以使用张量(numpy数组、PyTorch张量或TensorFlow张量)代替List[float],有关返回类型的说明,请参见上面的注释。

  • padding (bool, str or PaddingStrategy, optional, defaults to True) — Select a strategy to pad the returned sequences (according to the model’s padding side and padding index) among:
    • True or 'longest': Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    • 'max_length': Pad to a maximum length specified with the argument max_length or to the maximum acceptable input length for the model if that argument is not provided.
    • False or 'do_not_pad' (default): No padding (i.e., can output a batch with sequences of different lengths).
  • max_length (int, optional) — 返回列表的最大长度以及可选的填充长度(见上文)。
  • 截断 (bool) — 激活截断功能,将超过max_length的输入序列截断至max_length
  • pad_to_multiple_of (int, optional) — If set will pad the sequence to a multiple of the provided value.

    这对于在计算能力>= 7.5(Volta)的NVIDIA硬件上启用Tensor Cores特别有用,或者对于TPUs来说,序列长度为128的倍数是有益的。

  • return_attention_mask (bool, optional) — Whether to return the attention mask. If left to the default, will return the attention mask according to the specific feature_extractor’s default.

    什么是注意力掩码?

  • return_tensors (strTensorType, 可选) — 如果设置,将返回张量而不是Python整数列表。可接受的值有:
    • 'tf': 返回 TensorFlow tf.constant 对象。
    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。

将输入值/输入向量或一批输入值/输入向量填充到预定义的长度或批次中的最大序列长度。

填充边(左/右)的填充值在特征提取器级别定义(使用 self.padding_side, self.padding_value

如果传递的processed_features是numpy数组、PyTorch张量或TensorFlow张量的字典,结果将使用相同的类型,除非你通过return_tensors提供了不同的张量类型。在PyTorch张量的情况下,你将失去张量的特定设备信息。

批量特征

transformers.BatchFeature

< >

( data: typing.Optional[typing.Dict[str, typing.Any]] = None tensor_type: typing.Union[NoneType, str, transformers.utils.generic.TensorType] = None )

参数

  • data (dict, 可选) — 由 call/pad 方法返回的列表/数组/张量的字典(‘input_values’, ‘attention_mask’, 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 你可以在这里提供一个tensor_type,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

保存 pad() 和特征提取器特定的 __call__ 方法的输出。

这个类是从Python字典派生的,可以用作字典。

convert_to_tensors

< >

( tensor_type: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None )

参数

  • tensor_type (strTensorType, 可选) — 要使用的张量类型。如果是 str,应该是枚举 TensorType 的值之一。如果是 None,则不进行任何修改。

将内部内容转换为张量。

< >

( *args **kwargs ) BatchFeature

参数

  • args (Tuple) — 将被传递给张量的to(...)函数。
  • kwargs (Dict, 可选) — 将被传递给张量的 to(...) 函数。

返回

BatchFeature

修改后的相同实例。

通过调用v.to(*args, **kwargs)(仅限PyTorch)将所有值发送到设备。这应该支持在不同的dtypes中进行类型转换,并将BatchFeature发送到不同的device

ImageFeatureExtractionMixin

transformers.ImageFeatureExtractionMixin

< >

( )

包含用于准备图像特征的实用程序的Mixin。

center_crop

< >

( image size ) new_image

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor 形状为 (n_channels, height, width) 或 (height, width, n_channels)) — 要调整大小的图像。
  • size (intTuple[int, int]) — 裁剪图像的目标大小。

返回

新图像

一个中心裁剪的 PIL.Image.Imagenp.ndarraytorch.Tensor,形状为:(n_channels, height, width)。

image裁剪到给定大小,使用中心裁剪。请注意,如果图像太小无法裁剪到给定大小,它将被填充(因此返回的结果具有请求的大小)。

convert_rgb

< >

( image )

参数

  • image (PIL.Image.Image) — 要转换的图像.

PIL.Image.Image 转换为 RGB 格式。

expand_dims

< >

( image )

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor) — 要扩展的图像.

将二维image扩展到三维。

flip_channel_order

< >

( image )

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor) — 要翻转颜色通道的图像。如果是 np.ndarraytorch.Tensor,通道维度应为第一个维度。

image的通道顺序从RGB翻转为BGR,或者反之。请注意,如果image是PIL图像,这将触发将其转换为NumPy数组。

normalize

< >

( image mean std rescale = False )

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor) — 要标准化的图像。
  • mean (List[float] or np.ndarray or torch.Tensor) — 用于归一化的均值(每个通道)。
  • std (List[float] or np.ndarray or torch.Tensor) — 用于归一化的标准差(每个通道)。
  • rescale (bool, 可选, 默认为 False) — 是否将图像重新缩放到0到1之间。如果提供了PIL图像,缩放将自动进行。

使用meanstdimage进行归一化。请注意,如果image是PIL图像,这将触发将其转换为NumPy数组。

重新缩放

< >

( image: ndarray scale: typing.Union[float, int] )

按比例缩放numpy图像

调整大小

< >

( image size resample = None default_to_square = True max_size = None ) image

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor) — 要调整大小的图像。
  • size (int or Tuple[int, int]) — The size to use for resizing the image. If size is a sequence like (h, w), output size will be matched to this.

    如果 size 是一个整数且 default_to_squareTrue,则图像将被调整为 (size, size)。如果 size 是一个整数且 default_to_squareFalse,则图像的较小边将与此数字匹配。 即,如果高度 > 宽度,则图像将被重新缩放为 (size * 高度 / 宽度, size)。

  • resample (int, optional, defaults to PILImageResampling.BILINEAR) — 用于重新采样的过滤器。
  • default_to_square (bool, 可选, 默认为 True) — 当 size 为单个整数时如何转换。如果设置为 Truesize 将被转换为正方形 (size,size)。如果设置为 False,将复制 torchvision.transforms.Resize 并支持仅调整最小边缘的大小,并提供可选的 max_size
  • max_size (int, 可选, 默认为 None) — 调整大小后的图像较长边的最大允许值:如果图像的较长边在根据 size 调整大小后大于 max_size,则图像将再次调整大小,以使较长边等于 max_size。因此,size 可能会被覆盖,即较短边可能比 size 更短。仅在 default_to_squareFalse 时使用。

返回

图片

一个调整大小的 PIL.Image.Image

调整image的大小。强制将输入转换为PIL.Image。

旋转

< >

( image angle resample = None expand = 0 center = None translate = None fillcolor = None ) image

参数

  • 图像 (PIL.Image.Imagenp.ndarraytorch.Tensor) — 要旋转的图像。如果是 np.ndarraytorch.Tensor,将在旋转前转换为 PIL.Image.Image.

返回

图片

一个旋转的 PIL.Image.Image

返回image的旋转副本。此方法返回image的副本,围绕其中心逆时针旋转给定的度数。

to_numpy_array

< >

( image rescale = 无 channel_first = 真 )

参数

  • image (PIL.Image.Image or np.ndarray or torch.Tensor) — 要转换为NumPy数组的图像。
  • rescale (bool, 可选) — 是否应用缩放因子(使像素值变为0到1之间的浮点数)。如果图像是PIL图像或整数数组/张量,则默认为True,否则为False
  • channel_first (bool, 可选, 默认为 True) — 是否对图像的维度进行排列,将通道维度放在第一位。

image转换为numpy数组。可以选择性地重新缩放它,并将通道维度作为第一个维度。

to_pil_image

< >

( image rescale = 无 )

参数

  • image (PIL.Image.Image or numpy.ndarray or torch.Tensor) — 要转换为PIL图像格式的图像。
  • rescale (bool, 可选) — 是否应用缩放因子(使像素值在0到255之间的整数)。如果图像类型是浮点类型,则默认为True,否则为False

image转换为PIL图像。如果需要,可以选择重新缩放并将通道维度放回最后一个轴。

< > Update on GitHub