【问题标题】:The size of tensor a (707) must match the size of tensor b (512) at non-singleton dimension 1张量 a (707) 的大小必须与非单维 1 处的张量 b (512) 的大小相匹配
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 如果encode() 函数不起作用,那么batch_encode_plus() 肯定起作用。
    • 附带说明:如果在另一种语言上使用单语 Bert 模型,则极有可能出现此错误 ;)
    • @AshwinGeetD'Sa。我正在使用 batch_encode_plus() ,但仍然出现此错误。这是我使用的代码:tokenizer.batch_encode_plus( df.abstract.values, add_special_tokens=True, return_attention_mask=True, padding='longest', max_length=256, return_tensors='pt' )
    • 错误是什么?
    • 这并没有向我们展示如何解决转换器的 pipeline() 设置中的问题。将这些参数传递给 AutoTokenizer.from_pretrained() 不会影响调用管道时的行为。
    猜你喜欢
    • 2021-03-09
    • 2020-12-13
    • 2020-11-24
    • 2019-11-09
    • 2021-07-12
    • 2020-12-18
    • 1970-01-01
    • 2022-08-13
    • 2019-09-02
    相关资源
    最近更新 更多