张量a(707)的大小必须与非单维度1上的张量b(512)的大小匹配

时间:2020-10-12 15:34:18

标签: python tensorflow pytorch tokenize bert-language-model

我正在尝试使用预训练的BERT模型进行文本分类。我在数据集中以及测试阶段对模型进行了训练。我知道BERT最多只能使用512个令牌,因此我写了if条件来检查数据帧中测试的持续时间的长度。如果它长于512,则将句子分成多个序列,每个序列具有512个标记。然后做令牌化器编码。 seqience的长度为512,但是,在进行令牌化编码后,长度变为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)

1 个答案:

答案 0 :(得分:0)

这是因为,BERT使用词片标记法。因此,当某些单词不在词汇表中时,它会将单词拆分为单词片段。例如:如果单词playing不在词汇表中,则可以分解为play, ##ing。在标记化之后,这会增加给定句子中标记的数量。 您可以指定某些参数以获得固定长度的标记:

tokenized_sentence = tokenizer.encode(test_sentence, padding=True, truncation=True,max_length=50, add_special_tokens = True)