特征提取器
特征提取器负责为音频或视觉模型准备输入特征。这包括从序列中提取特征,例如预处理音频文件以生成对数梅尔频谱图特征,从图像中提取特征,例如裁剪图像文件,还包括填充、归一化以及转换为NumPy、PyTorch和TensorFlow张量。
FeatureExtractionMixin
这是一个特征提取混入,用于为序列和图像特征提取器提供保存/加载功能。
from_pretrained
< source >( 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 (
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
) — 是否强制(重新)下载特征提取器文件并覆盖缓存版本(如果存在)。 - resume_download — 已弃用并被忽略。现在默认情况下,所有下载在可能的情况下都会自动恢复。 将在Transformers的v5版本中移除。
- proxies (
Dict[str, str]
, 可选) — 一个按协议或端点使用的代理服务器字典,例如{'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}.
这些代理会在每个请求中使用。 - token (
str
或bool
, 可选) — 用于远程文件的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
< source >( save_directory: typing.Union[str, os.PathLike] push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
oros.PathLike
) — 特征提取器 JSON 文件将被保存的目录(如果不存在将被创建)。 - push_to_hub (
bool
, optional, defaults toFalse
) — 是否在保存后将模型推送到 Hugging Face 模型中心。您可以使用repo_id
指定要推送到的仓库(默认为您命名空间中save_directory
的名称)。 - kwargs (
Dict[str, Any]
, 可选) — 传递给 push_to_hub() 方法的额外关键字参数。
将feature_extractor对象保存到目录save_directory
中,以便可以使用
from_pretrained()类方法重新加载。
SequenceFeatureExtractor
类 transformers.SequenceFeatureExtractor
< source >( feature_size: int sampling_rate: int padding_value: float **kwargs )
这是一个用于语音识别的通用特征提取类。
pad
< source >( 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]]
orList[Dict[str, List[float]]]
) — Processed inputs. Can represent one input (BatchFeature orDict[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 toTrue
) — 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 argumentmax_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 (
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张量的情况下,你将失去张量的特定设备信息。
批量特征
类 transformers.BatchFeature
< source >( data: typing.Optional[typing.Dict[str, typing.Any]] = None tensor_type: typing.Union[NoneType, str, transformers.utils.generic.TensorType] = None )
保存 pad() 和特征提取器特定的 __call__
方法的输出。
这个类是从Python字典派生的,可以用作字典。
convert_to_tensors
< source >( tensor_type: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None )
参数
- tensor_type (
str
或 TensorType, 可选) — 要使用的张量类型。如果是str
,应该是枚举 TensorType 的值之一。如果是None
,则不进行任何修改。
将内部内容转换为张量。
通过调用v.to(*args, **kwargs)
(仅限PyTorch)将所有值发送到设备。这应该支持在不同的dtypes
中进行类型转换,并将BatchFeature
发送到不同的device
。
ImageFeatureExtractionMixin
包含用于准备图像特征的实用程序的Mixin。
center_crop
< source >( image size ) → new_image
将image
裁剪到给定大小,使用中心裁剪。请注意,如果图像太小无法裁剪到给定大小,它将被填充(因此返回的结果具有请求的大小)。
将 PIL.Image.Image
转换为 RGB 格式。
将二维image
扩展到三维。
flip_channel_order
< source >( image )
将image
的通道顺序从RGB翻转为BGR,或者反之。请注意,如果image
是PIL图像,这将触发将其转换为NumPy数组。
normalize
< source >( image mean std rescale = False )
使用mean
和std
对image
进行归一化。请注意,如果image
是PIL图像,这将触发将其转换为NumPy数组。
按比例缩放numpy图像
调整大小
< source >( image size resample = None default_to_square = True max_size = None ) → image
参数
- 图像 (
PIL.Image.Image
或np.ndarray
或torch.Tensor
) — 要调整大小的图像。 - size (
int
orTuple[int, int]
) — The size to use for resizing the image. Ifsize
is a sequence like (h, w), output size will be matched to this.如果
size
是一个整数且default_to_square
为True
,则图像将被调整为 (size, size)。如果size
是一个整数且default_to_square
为False
,则图像的较小边将与此数字匹配。 即,如果高度 > 宽度,则图像将被重新缩放为 (size * 高度 / 宽度, size)。 - resample (
int
, optional, defaults toPILImageResampling.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。
旋转
< source >( image angle resample = None expand = 0 center = None translate = None fillcolor = None ) → image
返回image
的旋转副本。此方法返回image
的副本,围绕其中心逆时针旋转给定的度数。
to_numpy_array
< source >( image rescale = 无 channel_first = 真 )
将image
转换为numpy数组。可以选择性地重新缩放它,并将通道维度作为第一个维度。
to_pil_image
< source >( image rescale = 无 )
将image
转换为PIL图像。如果需要,可以选择重新缩放并将通道维度放回最后一个轴。