从HuggingFace中的wav2vec2模型获取嵌入

2024-09-30 20:30:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用自己的数据集从预先训练的wav2vec2模型(例如,来自jonatasgrosman/wav2vec2-large-xlsr-53-german)中获取嵌入

我的目标是将这些功能用于下游任务(不特别是语音识别)。也就是说,由于数据集相对较小,我将使用这些嵌入来训练SVM,以进行最终分类

到目前为止,我已经尝试过:

model_name = "facebook/wav2vec2-large-xlsr-53-german"
feature_extractor = Wav2Vec2Processor.from_pretrained(model_name)
model = Wav2Vec2Model.from_pretrained(model_name)

input_values = feature_extractor(train_dataset[:10]["speech"], return_tensors="pt", padding=True, 
                                 feature_size=1, sampling_rate=16000 ).input_values 

然后,我不确定这里的嵌入是否对应于最后隐藏状态的顺序:

hidden_states = model(input_values).last_hidden_state

或模型最后一个conv层的特征序列:

features_last_cnn_layer = model(input_values).extract_features

此外,这是从预先训练的模型中提取特征的正确方法吗

如何从特定层获得嵌入

PD:在这里发布的HuggingFace论坛似乎不太活跃


Tags: 数据namefrom模型inputmodelhiddenfeature
1条回答
网友
1楼 · 发布于 2024-09-30 20:30:19

只需检查documentation

last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)) – Sequence of hidden-states at the output of the last layer of the model.

extract_features (torch.FloatTensor of shape (batch_size, sequence_length, conv_dim[-1])) – Sequence of extracted feature vectors of the last convolutional layer of the model.

  • 最后一个_hidden_状态向量表示所谓的contextualized embeddings(即,每个特征(CNN输出)都有一个向量表示,该向量表示在某种程度上受序列的其他标记的影响)
  • extract_features向量表示输入的嵌入(在CNN之后)。 .

Also, is this the correct way to extract features from a pre-trained model?
Yes.

How one can get embeddings from a specific layer? Set output_hidden_states=True:

o = model(input_values,output_hidden_states=True)
o.keys()

输出:

odict_keys(['last_hidden_state', 'extract_features', 'hidden_states'])

hidden_states值包含每个注意层的嵌入和上下文化嵌入

p.S.:jonatasgrosman/wav2vec2-large-xlsr-53-german模型用feat_extract_norm==层进行训练。也就是说,您还应该向模型传递一个注意遮罩:

model_name = "facebook/wav2vec2-large-xlsr-53-german"
feature_extractor = Wav2Vec2Processor.from_pretrained(model_name)
model = Wav2Vec2Model.from_pretrained(model_name)

i= feature_extractor(train_dataset[:10]["speech"], return_tensors="pt", padding=True, 
                                 feature_size=1, sampling_rate=16000 )
model(**i)

相关问题 更多 >