繁体   English   中英

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

[英]The size of tensor a (707) must match the size of tensor b (512) at non-singleton dimension 1

我正在尝试使用预训练的 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)

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

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

如果您使用 HuggingFace 运行转换器模型,则输入句子之一的长度可能超过 512 个标记。 截断或拆分句子。 我怀疑较短的句子被填充到 512 个标记中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM