预期输入 batch_size (1) 以匹配目标 batch_size (11)

Expected input batch_size (1) to match target batch_size (11)

我知道这似乎是一个常见问题,但我找不到解决方案。我是 运行 一个多标签分类模型,在张量大小方面存在问题。

我的完整代码如下所示:

from transformers import DistilBertTokenizerFast, DistilBertForSequenceClassification
import torch

# Instantiating tokenizer and model
tokenizer = DistilBertTokenizerFast.from_pretrained('distilbert-base-cased')
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-cased')

# Instantiating quantized model
quantized_model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)

# Forming data tensors
input_ids = torch.tensor(tokenizer.encode(x_train[0], add_special_tokens=True)).unsqueeze(0)
labels = torch.tensor(Y[0]).unsqueeze(0)

# Train model
outputs = quantized_model(input_ids, labels=labels)
loss, logits = outputs[:2]

产生错误:

ValueError: Expected input batch_size (1) to match target batch_size (11)

Input_ids 看起来像:

tensor([[  101,   789,   160,  1766,  1616,  1110,   170,  1205,  7727,  1113,
           170,  2463,  1128,  1336,  1309,  1138,   112,   119, 11882, 11545,
           119,   108, 15710,   108,  3645,   108,  3994,   102]])

形状:

torch.Size([1, 28])

标签看起来像:

tensor([[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1]])

形状:

torch.Size([1, 11])

input_ids的大小会随着要编码的字符串大小的不同而变化。

我还注意到,当输入 5 个 Y 值来生成 5 个标签时,它会产生错误:

ValueError: Expected input batch_size (1) to match target batch_size (55).

标签形状:

torch.Size([1, 5, 11])

(注意我没有喂 5 input_ids,这大概是输入大小保持不变的原因)

我已经尝试了几种不同的方法来使它们正常工作,但我目前不知所措。我真的很感激一些指导。谢谢!

DistilBertForSequenceClassification 的标签需要具有 torch.Size([batch_size]) 的大小,如文档中所述:

  • labels (torch.LongTensor of shape (batch_size,), optional, defaults to None) – Labels for computing the sequence classification/regression loss. Indices should be in [0, ..., config.num_labels - 1]. If config.num_labels == 1 a regression loss is computed (Mean-Square loss), If config.num_labels > 1 a classification loss is computed (Cross-Entropy).

在你的情况下,你的 labels 应该有大小 torch.Size([1])

这对于您的数据是不可能的,那是因为序列分类对每个序列都有一个标签,但您希望将其设为多标签分类。

据我所知,HuggingFace 的转换器库中没有您可以开箱即用的多标签模型。您需要创建自己的模型,这并不是特别困难,因为这些额外的模型都使用相同的基础模型并在末尾添加适当的分类器,具体取决于要解决的任务。 HuggingFace - Multi-label Text Classification using BERT – The Mighty Transformer 解释如何做到这一点。