Transformers 文档
特征提取器
并获得增强的文档体验
开始使用
特征提取器
特征提取器负责为音频或视觉模型准备输入特征。这包括从序列中提取特征(例如,预处理音频文件以生成对数梅尔频谱图特征)、从图像中提取特征(例如,裁剪图像文件),以及进行填充、归一化,并转换为 NumPy、PyTorch 和 TensorFlow 张量。
FeatureExtractionMixin
这是一个特征提取的 mixin(混入类),用于为序列和图像特征提取器提供保存/加载功能。
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[str, bool, NoneType] = None revision: str = 'main' **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.PathLike
) — 可以是以下之一:- 一个字符串,即托管在 huggingface.co 模型仓库中的预训练 feature_extractor 的 *model id*。
- 一个包含使用 save_pretrained() 方法保存的特征提取器文件的 *目录* 的路径,例如
./my_model_directory/
。 - 一个指向已保存的特征提取器 JSON *文件* 的路径或 URL,例如
./my_model_directory/preprocessor_config.json
。
- cache_dir (
str
或os.PathLike
, *可选*) — 如果不使用标准缓存目录,则指定一个目录路径,用于缓存下载的预训练模型特征提取器。 - force_download (
bool
, *可选*, 默认为False
) — 是否强制(重新)下载特征提取器文件并覆盖已存在的缓存版本。 - resume_download — 已弃用并忽略。现在所有下载在可能时都会默认恢复。将在 Transformers v5 版本中移除。
- proxies (
dict[str, str]
, *可选*) — 一个根据协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}
。代理将在每个请求中使用。 - token (
str
或bool
, *可选*) — 用于远程文件的 HTTP Bearer 授权的令牌。如果为True
或未指定,将使用运行huggingface-cli login
时生成的令牌(存储在~/.huggingface
)。 - revision (
str
, *可选*, 默认为"main"
) — 要使用的特定模型版本。它可以是分支名、标签名或提交 ID,因为我们在 huggingface.co 上使用基于 git 的系统来存储模型和其他文件,所以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
或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: typing.Union[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: 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, 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 张量或 TensorFlow 张量),请参阅上面关于返回类型的说明。 - 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
, *可选*) — 如果设置,将把序列填充到所提供值的倍数。这对于在计算能力
>= 7.5
(Volta)的 NVIDIA 硬件上启用 Tensor Cores,或者在 TPU 上特别有用,因为这些设备受益于序列长度是 128 的倍数。 - return_attention_mask (
bool
, *可选*) — 是否返回注意力掩码。如果保留为默认值,将根据特定 feature_extractor 的默认设置返回注意力掩码。 - return_tensors (
str
或 TensorType, *可选*) — 如果设置,将返回张量而不是 Python 整数列表。可接受的值为:'tf'
:返回 TensorFlowtf.constant
对象。'pt'
:返回 PyTorchtorch.Tensor
对象。'np'
:返回 Numpynp.ndarray
对象。
将输入值/输入向量或一批输入值/输入向量填充到预定义的长度或批次中的最大序列长度。
填充方向(左/右)和填充值在特征提取器级别定义(通过 self.padding_side
, self.padding_value
)
如果传入的 processed_features
是 numpy 数组、PyTorch 张量或 TensorFlow 张量的字典,则结果将使用相同的类型,除非您使用 return_tensors
提供不同的张量类型。但在 PyTorch 张量的情况下,您将丢失张量的特定设备信息。
BatchFeature
class transformers.BatchFeature
< 源文件 >( data: typing.Optional[dict[str, typing.Any]] = None tensor_type: typing.Union[NoneType, str, transformers.utils.generic.TensorType] = None )
保存 pad() 和特定于特征提取器的 __call__
方法的输出。
这个类派生自 Python 字典,可以像字典一样使用。
convert_to_tensors
< 源文件 >( tensor_type: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None )
参数
- tensor_type (
str
或 TensorType, *可选*) — 要使用的张量类型。如果为str
,则应为枚举 TensorType 的值之一。如果为None
,则不进行修改。
将内部内容转换为张量。
到
< 源文件 >( *args **kwargs ) → BatchFeature
通过调用 v.to(*args, **kwargs)
将所有值发送到设备(仅限 PyTorch)。这应该支持转换为不同的 dtypes
并将 BatchFeature
发送到不同的 device
。
ImageFeatureExtractionMixin
包含准备图像特征实用程序的 Mixin (混入类)。
center_crop
< 源文件 >( image size ) → new_image
使用中心裁剪将 image
裁剪至给定尺寸。请注意,如果图像太小无法裁剪到给定尺寸,它将被填充(因此返回的结果具有所要求的尺寸)。
将 PIL.Image.Image
转换为 RGB 格式。
将二维 image
扩展为三维。
flip_channel_order
< 源代码 >( image )
翻转 image
的通道顺序,从 RGB 变为 BGR,或从 BGR 变为 RGB。注意,如果 image
是一个 PIL 图像,此操作将触发其向 NumPy 数组的转换。
归一化
< 源代码 >( image mean std rescale = False )
使用 mean
和 std
对 image
进行归一化。注意,如果 image
是一个 PIL 图像,此操作将触发其向 NumPy 数组的转换。
按指定比例缩放 numpy 图像
resize
< 源代码 >( image size resample = None default_to_square = True max_size = None ) → image
参数
- image (
PIL.Image.Image
或np.ndarray
或torch.Tensor
) — 要调整大小的图像。 - size (
int
或tuple[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
, 可选, 默认为PILImageResampling.BILINEAR
) — 用于重采样的滤波器。 - default_to_square (
bool
, 可选, 默认为True
) — 如何转换当size
是单个整数时。如果设置为True
,size
将被转换为正方形 (size
,size
)。如果设置为False
,将复制torchvision.transforms.Resize
的行为,支持仅调整最短边并提供可选的max_size
。 - max_size (
int
, 可选, 默认为None
) — 调整大小后图像较长边的最大允许值:如果根据size
调整大小后图像的较长边大于max_size
,则图像将再次调整大小,使较长边等于max_size
。因此,size
可能会被覆盖,即较短边可能会比size
更短。仅当default_to_square
为False
时使用。
返回
图像
一个调整大小后的 PIL.Image.Image
。
调整 image
的大小。强制将输入转换为 PIL.Image。
rotate
< 源代码 >( image angle resample = None expand = 0 center = None translate = None fillcolor = None ) → image
返回一个 image
的旋转副本。此方法返回一个围绕其中心逆时针旋转给定度数的 image
副本。
to_numpy_array
< 源代码 >( image rescale = None channel_first = True )
将 image
转换为 numpy 数组。可选地对其进行缩放并将通道维度作为第一个维度。
to_pil_image
< 源代码 >( image rescale = None )
将 image
转换为 PIL 图像。如果需要,可选择性地对其进行缩放并将通道维度放回最后一个轴。