首页 > 解决方案 > ValueError: 目标尺寸 (torch.Size([32])) 必须与输入尺寸 (torch.Size([32, 3])) 相同

问题描述

我看过一些解释。

这里

但我明白我认为出了什么问题,但我的错误发生在不知不觉中。例如,发生错误的代码段是 line outputs = model(**inputs)

 # INPUTS
        # Pulling out the inputs in the form of dictionary
        inputs = {'input_ids':      batch[0],
                  'attention_mask': batch[1],
                  'labels':         batch[2],
                  }
        # OUTPUTS
        # '**' Unpacking the dictionary stright into the input
        outputs = model(**inputs)

        loss = outputs[0]
        loss_train_total += loss.item()
        loss.backward()           # backpropagation

我得到的错误:

 File "c:\Users\#####\BERT.py", line 193, in <module>
    outputs = model(**inputs)
ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 3]))

现在我知道 32 是批量大小,但不确定这个目标在哪里。我知道这是标签,但我该如何解决它以使其运行?

谢谢。

编辑

我尝试了一种热编码标签,如下所示:

enc = OneHotEncoder(handle_unknown='ignore')
enc.fit(train_y.reshape(-1, 1))
train_y = enc.transform(train_y.reshape(-1, 1)).toarray()

enc.fit(test_y.reshape(-1, 1))
test_y = enc.transform(test_y.reshape(-1, 1)).toarray()

输出

[[1. 0. 0.]
 [0. 0. 1.]
 [0. 0. 1.]
 ...
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]]

但我仍然收到相同的错误消息

标签: pythonmachine-learningneural-networkbert-language-model

解决方案


我有一个类似的问题,我能找到的解决方案是扩大“标签”的尺寸。我已经使用以下代码完成了此操作:

labels = torch.nn.functional.one_hot(labels)

这会将您的标签列表转换为一次性编码。这应该与标签和输入的尺寸相匹配。


推荐阅读