Transformers 文档
特征提取器
并获得增强的文档体验
开始使用
特征提取器
特征提取器负责准备音频模型的输入特征。这包括从序列中提取特征,例如,预处理音频文件以生成对数梅尔频谱图特征,以及转换为 NumPy 和 PyTorch 张量。
FeatureExtractionMixin
这是一个特征提取混合器,用于为序列和音频特征提取器提供保存/加载功能。
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 (
str或os.PathLike) — 可以是:- 一个字符串,即托管在 huggingface.co 模型仓库中的预训练特征提取器的模型 ID。
- 一个指向包含使用 save_pretrained() 方法保存的特征提取器文件的目录,例如
./my_model_directory/。 - 一个指向已保存的特征提取器 JSON文件的路径或 URL,例如
./my_model_directory/preprocessor_config.json。
- cache_dir (
str或os.PathLike, 可选) — 下载的预训练模型特征提取器应缓存的目录路径,如果标准缓存不应被使用。 - force_download (
bool, 可选, 默认为False) — 是否强制(重新)下载特征提取器文件,并覆盖存在的缓存版本。 - proxies (
dict[str, str], 可选) — 用于按协议或端点代理的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}。每次请求都会使用代理。 - token (
str或bool, 可选) — 作为远程文件进行 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 (
str或os.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 )
这是一个用于语音识别的通用特征提取类。
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]]]) — 已处理的输入。可以表示一个输入(BatchFeature 或dict[str, list[float]])或一批输入值/向量(BatchFeature 的列表,dict[str, list[list[float]]] 或 list[dict[str, list[float]]]),因此您可以在预处理期间以及在 PyTorch Dataloader collate 函数中使用此方法。代替
list[float],您可以使用张量(numpy 数组或 PyTorch 张量),请参阅上面的返回类型说明。 - padding (
bool,str或 PaddingStrategy, 可选, 默认为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。 - return_tensors (
str或 TensorType, 可选) — 如果设置,将返回 tensors 而不是 python 整数列表。可接受的值包括:'pt': 返回 PyTorchtorch.Tensor对象。'np': 返回 Numpynp.ndarray对象。
使用预定义长度或批次中的最大序列长度来填充输入值/输入向量或输入值/输入向量的批次。
填充侧(左/右)填充值在 feature extractor 级别定义(使用 self.padding_side, self.padding_value)
如果传入的
processed_features是 numpy 数组或 PyTorch 张量的字典,则结果将使用相同的类型,除非您使用return_tensors提供不同的张量类型。对于 PyTorch 张量,您将丢失张量的特定设备。
BatchFeature
class transformers.BatchFeature
< source >( 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 )
保存由 pad() 和 feature extractor 特定的 __call__ 方法的输出。
此类派生自 python 字典,可用作字典。
convert_to_tensors
< source >( tensor_type: str | transformers.utils.generic.TensorType | None = None skip_tensor_conversion: list[str] | set[str] | None = None )
参数
- tensor_type (
str或 TensorType, 可选) — 要使用的张量类型。如果为str,则应为枚举 TensorType 的值之一。如果为None,则不进行修改。 - skip_tensor_conversion (
list[str]或set[str], 可选) — 不应转换为张量的键的列表或集合,即使指定了tensor_type。
将内部内容转换为张量。
注意:结构非数组式的值(例如,字符串、字典、字符串列表)将被自动跳过,不会转换为张量。参差不齐的数组(长度不同的数组列表)仍会尝试转换,但可能会在转换过程中引发错误。
到
< source >( *args **kwargs ) → BatchFeature
通过调用 v.to(*args, **kwargs)(仅限 PyTorch)将所有值发送到设备。这应该支持转换为不同的 dtypes 以及将 BatchFeature 发送到不同的 device。
ImageFeatureExtractionMixin
包含准备图像特征的实用程序的 Mixin。
center_crop
< source >( image size ) → new_image
使用中心裁剪将 image 裁剪到给定大小。请注意,如果图像太小而无法裁剪到指定大小,它将被填充(因此返回结果的大小将是请求的大小)。
将 PIL.Image.Image 转换为 RGB 格式。
将 2 维 image 扩展到 3 维。
flip_channel_order
< source >( image )
将 image 的通道顺序从 RGB 翻转到 BGR,或反之亦然。请注意,这将触发将 image 转换为 NumPy 数组(如果它是 PIL Image)。
归一化
< source >( image mean std rescale = False )
使用 mean 和 std 对 image 进行归一化。请注意,这将触发将 image 转换为 NumPy 数组(如果它是 PIL Image)。
按比例缩放 numpy 图像
resize
< source >( image size resample = None default_to_square = True max_size = None ) → image
参数
- image (
PIL.Image.Imageornp.ndarrayortorch.Tensor) — 要调整大小的图像。 - size (
intortuple[int, int]) — 用于调整图像大小的尺寸。如果size是一个像 (h, w) 这样的序列,输出大小将与之匹配。如果
size是一个整数,并且default_to_square为True,则图像将被调整为 (size, size)。如果size是一个整数,并且default_to_square为False,则图像的较短边将匹配此数字。即,如果 height > width,则图像将按比例缩放至 (size * height / width, size)。 - resample (
int, optional, defaults toPILImageResampling.BILINEAR) — 用于重采样。 - default_to_square (
bool, optional, defaults toTrue) — 当size为单个整数时如何将其转换为size。如果设置为True,则size将转换为正方形 (size,size)。如果设置为False,将模仿torchvision.transforms.Resize,支持仅调整最短边缘的大小并提供可选的max_size。 - max_size (
int, optional, defaults toNone) — 调整大小后的图像较长边缘的最大允许值:如果图像的较长边缘在根据size调整大小时大于max_size,则图像会再次调整大小,使其较长边缘等于max_size。因此,size可能会被覆盖,即较短边缘可能小于size。仅在default_to_square为False时使用。
返回
image
调整大小后的 PIL.Image.Image。
调整 image 的大小。强制将输入转换为 PIL.Image。
rotate
< source >( image angle resample = None expand = 0 center = None translate = None fillcolor = None ) → image
返回 image 的旋转副本。此方法返回 image 的副本,围绕其中心逆时针旋转指定的度数。
to_numpy_array
< source >( image rescale = None channel_first = True )
将 image 转换为 numpy 数组。可选地进行缩放并使通道维度成为第一个维度。
to_pil_image
< source >( image rescale = None )
将 image 转换为 PIL Image。可选地对其进行缩放,并在需要时将通道维度放回最后一个轴。