【问题标题】:ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 3]))ValueError: 目标尺寸 (torch.Size([32])) 必须与输入尺寸 (torch.Size([32, 3])) 相同
【发布时间】:2021-09-29 09:46:37
【问题描述】:

我看过一些解释。

Here

但我明白我认为出了什么问题,但我的错误发生在不知不觉中。例如,发生错误的 sn-p 是 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.]]

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

【问题讨论】:

    标签: python machine-learning neural-network bert-language-model


    【解决方案1】:

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

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

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

    【讨论】:

    • 谢谢,所以基本上错误的意思是目标大小只有1,而应该是3,例如[1,0,0]?
    • 没错。这正是我的问题。
    • 那么显然我的数据框有一个“标签”列,它的值是 1,0,-1,我需要在拆分数据之前对其进行一次热编码吗?
    • 分割后可以单热编码。这实际上更可取!
    • 所以基本上这些列看起来像 ['id','text','positive','neutral','negative'] 其中正、中性和负是 3 个类别标签,将是分别是 1 还是 0?
    猜你喜欢
    • 2021-11-12
    • 2020-01-07
    • 2021-04-08
    • 2022-01-21
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2022-06-24
    相关资源
    最近更新 更多