我无法将我的代码pytorch_pretrained_bert
从pytorch_transformers
. 我正在尝试进行余弦相似度练习。我想提取 12 个隐藏嵌入层中倒数第二个的文本嵌入值。
import torch
from pytorch_pretrained_bert import BertTokenizer, BertModel
#from pytorch_transofmers import BertTokenizer, BertModel
import pandas as pd
import numpy as np
model = BertModel.from_pretrained('bert-base-uncased')
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# This is done by default in the pytorch_transformers
model.eval()
input_query = "This is my test input query text"
marked_text = "[CLS] " + input_query + " [SEP]"
tokenized_text = tokenizer.tokenize(marked_text)
indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
segments_ids = [1] * len(tokenized_text)
tokens_tensor = torch.tensor([indexed_tokens])
segments_tensors = torch.tensor([segments_ids])
with torch.no_grad():
encoded_layers, _ = model(tokens_tensor, segments_tensors)
sentence_embedding = torch.mean(encoded_layers[10], 1)
使用 pytorch_pretrained_bert 与上述代码完美配合。我的encoded_layers
对象是 12 个隐藏层张量的列表,允许我通过取平均值来选择和减少第 11 层,从而得到sentence_embedding
可以运行余弦相似度的对象。
但是,当我将代码迁移到pytorch_transformers
库时,生成的encoded_layers
对象不再是 12 个隐藏层的完整列表,而是一个 shape 的火炬张量对象torch.Size([1, 7, 768])
,这在我尝试创建sentence_embedding
对象时导致以下错误:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-23-7f877a7d2f9c> in <module>
9 encoded_layers, _ = model(tokens_tensor, segments_tensors)
10 test = encoded_layers[0]
---> 11 sentence_embedding = torch.mean(test[10], 1)
12
IndexError: index 10 is out of bounds for dimension 0 with size 7
迁移文档 ( https://huggingface.co/transformers/migration.html ) 指出我应该将encoded_layers
对象的第一个元素作为替换,但这并不能让我访问嵌入的倒数第二个隐藏层。
我怎样才能访问它?
谢谢!