Transformers 文档

特征提取器

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

特征提取器

特征提取器负责准备音频模型的输入特征。这包括从序列中提取特征,例如,预处理音频文件以生成对数梅尔频谱图特征,以及转换为 NumPy 和 PyTorch 张量。

FeatureExtractionMixin

class transformers.FeatureExtractionMixin

< >

( **kwargs )

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

from_pretrained

< >

( pretrained_model_name_or_path: str | os.PathLike cache_dir: str | os.PathLike | None = None force_download: bool = False local_files_only: bool = False token: str | bool | None = 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) — 是否强制(重新)下载特征提取器文件,并覆盖存在的缓存版本。
  • proxies (dict[str, str], 可选) — 用于按协议或端点代理的代理服务器字典,例如 {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。每次请求都会使用代理。
  • token (strbool, 可选) — 作为远程文件进行 HTTP bearer 授权使用的 token。如果为 True,或未指定,将使用运行 hf auth login 时生成的 token(存储在 ~/.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: str | os.PathLike push_to_hub: bool = False **kwargs )

参数

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

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

SequenceFeatureExtractor

class 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: transformers.feature_extraction_utils.BatchFeature | list[transformers.feature_extraction_utils.BatchFeature] | dict[str, transformers.feature_extraction_utils.BatchFeature] | dict[str, list[transformers.feature_extraction_utils.BatchFeature]] | list[dict[str, transformers.feature_extraction_utils.BatchFeature]] padding: bool | str | transformers.utils.generic.PaddingStrategy = True max_length: int | None = None truncation: bool = False pad_to_multiple_of: int | None = None return_attention_mask: bool | None = None return_tensors: str | transformers.utils.generic.TensorType | None = None )

参数

  • processed_features (BatchFeature, BatchFeature 的列表, dict[str, list[float]], dict[str, list[list[float]]]list[dict[str, list[float]]]) — 已处理的输入。可以表示一个输入(BatchFeaturedict[str, list[float]])或一批输入值/向量(BatchFeature 的列表,dict[str, list[list[float]]]list[dict[str, list[float]]]),因此您可以在预处理期间以及在 PyTorch Dataloader collate 函数中使用此方法。

    代替 list[float],您可以使用张量(numpy 数组或 PyTorch 张量),请参阅上面的返回类型说明。

  • padding (bool, strPaddingStrategy, 可选, 默认为 True) — 选择一个策略来填充返回的序列(根据模型的填充侧和填充索引),可选策略包括:

    • True'longest': 填充到批次中最长的序列(如果只提供单个序列,则不填充)。
    • 'max_length': 填充到由参数 max_length 指定的最大长度,或者如果未提供该参数,则填充到模型的最大可接受输入长度。
    • False'do_not_pad' (默认): 不填充(即,可以输出包含不同长度序列的批次)。
  • max_length (int, 可选) — 返回列表的最大长度,也是可选的填充长度(参见上面)。
  • truncation (bool) — 激活截断以将输入序列长度大于 max_length 的部分截断为 max_length
  • pad_to_multiple_of (int, 可选) — 如果设置,将填充序列以使其成为给定值的倍数。

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

  • return_attention_mask (bool, 可选) — 是否返回 attention mask。如果保持默认,将根据特定 feature_extractor 的默认值返回 attention mask。

    什么是 attention mask?

  • return_tensors (strTensorType, 可选) — 如果设置,将返回 tensors 而不是 python 整数列表。可接受的值包括:

    • 'pt': 返回 PyTorch torch.Tensor 对象。
    • 'np': 返回 Numpy np.ndarray 对象。

使用预定义长度或批次中的最大序列长度来填充输入值/输入向量或输入值/输入向量的批次。

填充侧(左/右)填充值在 feature extractor 级别定义(使用 self.padding_side, self.padding_value

如果传入的 processed_features 是 numpy 数组或 PyTorch 张量的字典,则结果将使用相同的类型,除非您使用 return_tensors 提供不同的张量类型。对于 PyTorch 张量,您将丢失张量的特定设备。

BatchFeature

class transformers.BatchFeature

< >

( data: dict[str, typing.Any] | None = None tensor_type: None | str | transformers.utils.generic.TensorType = None skip_tensor_conversion: list[str] | set[str] | None = None )

参数

  • data (dict, 可选) — 由 call/pad 方法返回的字典列表/数组/张量(‘input_values’, ‘attention_mask’ 等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供 tensor_type 以在初始化时将整数列表转换为 PyTorch/Numpy 张量。
  • skip_tensor_conversion (list[str]set[str], 可选) — 不应转换为张量的键的列表或集合,即使指定了 tensor_type

保存由 pad() 和 feature extractor 特定的 __call__ 方法的输出。

此类派生自 python 字典,可用作字典。

convert_to_tensors

< >

( tensor_type: str | transformers.utils.generic.TensorType | None = None skip_tensor_conversion: list[str] | set[str] | None = None )

参数

  • tensor_type (strTensorType, 可选) — 要使用的张量类型。如果为 str,则应为枚举 TensorType 的值之一。如果为 None,则不进行修改。
  • skip_tensor_conversion (list[str]set[str], 可选) — 不应转换为张量的键的列表或集合,即使指定了 tensor_type

将内部内容转换为张量。

注意:结构非数组式的值(例如,字符串、字典、字符串列表)将被自动跳过,不会转换为张量。参差不齐的数组(长度不同的数组列表)仍会尝试转换,但可能会在转换过程中引发错误。

< >

( *args **kwargs ) BatchFeature

参数

  • args (Tuple) — 将传递给张量的 to(...) 函数。
  • kwargs (Dict, 可选) — 将传递给张量的 to(...) 函数。要启用异步数据传输,请在 kwargs 中设置 non_blocking 标志(默认为 False)。

返回

批次特征

修改后的同一实例。

通过调用 v.to(*args, **kwargs)(仅限 PyTorch)将所有值发送到设备。这应该支持转换为不同的 dtypes 以及将 BatchFeature 发送到不同的 device

ImageFeatureExtractionMixin

class transformers.ImageFeatureExtractionMixin

< >

( )

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

center_crop

< >

( image size ) new_image

参数

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

返回

new_image

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

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

convert_rgb

< >

( image )

参数

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

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

expand_dims

< >

( image )

参数

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

将 2 维 image 扩展到 3 维。

flip_channel_order

< >

( image )

参数

  • image (PIL.Image.Image or np.ndarray or torch.Tensor) — 要翻转颜色通道的图像。如果为 np.ndarraytorch.Tensor,则通道维度应在第一位。

image 的通道顺序从 RGB 翻转到 BGR,或反之亦然。请注意,这将触发将 image 转换为 NumPy 数组(如果它是 PIL Image)。

归一化

< >

( image mean std rescale = False )

参数

  • image (PIL.Image.Image or np.ndarray or torch.Tensor) — 要归一化的图像。
  • mean (list[float] or np.ndarray or torch.Tensor) — 用于归一化的均值(每通道)。
  • std (list[float] or np.ndarray or torch.Tensor) — 用于归一化的标准差(每通道)。
  • rescale (bool, optional, defaults to False) — 是否将图像缩放到 0 到 1 之间。如果提供的是 PIL 图像,则会自动进行缩放。

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

rescale

< >

( image: ndarray scale: float | int )

按比例缩放 numpy 图像

resize

< >

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

参数

  • image (PIL.Image.Image or np.ndarray or torch.Tensor) — 要调整大小的图像。
  • size (int or tuple[int, int]) — 用于调整图像大小的尺寸。如果 size 是一个像 (h, w) 这样的序列,输出大小将与之匹配。

    如果 size 是一个整数,并且 default_to_squareTrue,则图像将被调整为 (size, size)。如果 size 是一个整数,并且 default_to_squareFalse,则图像的较短边将匹配此数字。即,如果 height > width,则图像将按比例缩放至 (size * height / width, size)。

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

返回

image

调整大小后的 PIL.Image.Image

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

rotate

< >

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

参数

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

返回

image

旋转后的 PIL.Image.Image

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

to_numpy_array

< >

( image rescale = None channel_first = True )

参数

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

image 转换为 numpy 数组。可选地进行缩放并使通道维度成为第一个维度。

to_pil_image

< >

( image rescale = None )

参数

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

image 转换为 PIL Image。可选地对其进行缩放,并在需要时将通道维度放回最后一个轴。

在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.