python - 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.]]
但我仍然收到相同的错误消息
解决方案
我有一个类似的问题,我能找到的解决方案是扩大“标签”的尺寸。我已经使用以下代码完成了此操作:
labels = torch.nn.functional.one_hot(labels)
这会将您的标签列表转换为一次性编码。这应该与标签和输入的尺寸相匹配。
推荐阅读
- sql-server - 存储过程重复插入相同的记录,而不是从 SELECT 循环遍历列表
- typescript - 在 Typescript 中重载类类型定义
- pandas - 如何删除列中的重复值但保留与一行中其他列相对应的唯一值?
- reactjs - 当我多次单击选项卡时,后退按钮无法正常工作
- visual-studio-code - 我的 VS 代码出错了(图形故障)
- java - 将对象流转换为地图
- javascript - 当文本碰到右边框时,将文本在侧边栏中的“a”片段中向下移动
- android - Flutter - 线性渐变不将颜色作为颜色数组
- flutter - 使用颤振创建响应式散点图
- materialize - 在 Sapper 中实现 CSS