我正在尝试使用预训练的 BERT 模型进行文本分类。我在我的数据集上训练了模型,并在测试阶段;我知道 BERT 只能接受 512 个标记,因此我编写了 if 条件来检查数据帧中测试语句的长度。如果它比 512 长,我将句子分成序列,每个序列有 512 个标记。然后进行分词器编码。序列的长度是 512,但是,在进行 tokenize 编码后,长度变为 707,并且出现此错误。
The size of tensor a (707) must match the size of tensor b (512) at non-singleton dimension 1
这是我用来执行前面步骤的代码:
tokenizer = BertTokenizer.from_pretrained('bert-base-cased', do_lower_case=False)
import math
pred=[]
if (len(test_sentence_in_df.split())>512):
n=math.ceil(len(test_sentence_in_df.split())/512)
for i in range(n):
if (i==(n-1)):
print(i)
test_sentence=' '.join(test_sentence_in_df.split()[i*512::])
else:
print("i in else",str(i))
test_sentence=' '.join(test_sentence_in_df.split()[i*512:(i+1)*512])
#print(len(test_sentence.split())) ##here's the length is 512
tokenized_sentence = tokenizer.encode(test_sentence)
input_ids = torch.tensor([tokenized_sentence]).cuda()
print(len(tokenized_sentence)) #### here's the length is 707
with torch.no_grad():
output = model(input_ids)
label_indices = np.argmax(output[0].to('cpu').numpy(), axis=2)
pred.append(label_indices)
print(pred)
这是因为,BERT 使用单词片段标记化。因此,当某些单词不在词汇表中时,它将单词分割成单词片段。例如:如果这个词playing
不在词汇表中,它可以分解为play, ##ing
。这会增加标记化后给定句子中的标记数量。
您可以指定某些参数来获得固定长度的标记化:
tokenized_sentence = tokenizer.encode(test_sentence, padding=True, truncation=True,max_length=50, add_special_tokens = True)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)