【发布时间】:2021-01-26 22:41:51
【问题描述】:
我正在尝试使用预训练的 BERT 模型进行文本分类。我在我的数据集上训练了模型,并且处于测试阶段;我知道 BERT 只能接受 512 个标记,所以我写了 if 条件来检查我的数据框中测试句的长度。如果它长于 512,我将句子分成序列,每个序列有 512 个标记。然后做分词器编码。 seqience 的长度是 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)
【问题讨论】:
标签: python tensorflow pytorch tokenize bert-language-model