当前位置:   article > 正文

pytorch训练数据类型错误_the dtype of attention mask (torch.int64) is not b

the dtype of attention mask (torch.int64) is not bool

RuntimeError: expected scalar type Long but found Float
先了解一个知识:torch.Tensor默认是torch.FloatTensor是32位浮点类型数据,torch.LongTensor是64位整型。
读取pandas数据后,在进行分类处理时,都是默认给定的torch.Tensor,如下:

X_train = torch.tensor(X_train.values)
y_train = torch.tensor(y_train.values)

X_test = torch.tensor(X_test.values)
y_test = torch.tensor(y_test.values)
  • 1
  • 2
  • 3
  • 4
  • 5

这个默认是根据X_train.values和y_train.values的数据类型来的,

X_train.dtype为torch.int64
y_train.dtype为torch.int64
  • 1
  • 2

我们再看看模型的权重值的类型:

for name, param in model.named_parameters():
    print(name,'-->',param.type(),'-->',param.dtype,'-->',param.shape)
  • 1
  • 2

结果:

linear_relu_stack.0.weight --> torch.FloatTensor --> torch.float32 --> torch.Size([512, 784])
linear_relu_stack.0.bias --> torch.FloatTensor --> torch.float32 --> torch.Size([512])
linear_relu_stack.2.weight --> torch.FloatTensor --> torch.float32 --> torch.Size([512, 512])
linear_relu_stack.2.bias --> torch.FloatTensor --> torch.float32 --> torch.Size([512])
linear_relu_stack.4.weight --> torch.FloatTensor --> torch.float32 --> torch.Size([10, 512])
linear_relu_stack.4.bias --> torch.FloatTensor --> torch.float32 --> torch.Size([10])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

可以看出权重值的类型是float32,所以这里有两个问题需要解决:
第一、把输入的数据类型变为float32的;
第二、把y值标签变为64位整型。
所以修改代码如下:

X_train = torch.tensor(X_train.values,dtype=torch.float)
y_train = torch.LongTensor(y_train.values)

X_test = torch.tensor(X_test.values,dtype=torch.float)
y_test = torch.LongTensor(y_test.values)
  • 1
  • 2
  • 3
  • 4
  • 5

再看看此时的值:

X_train.dtype为torch.float32
y_train.dtype为torch.int64
  • 1
  • 2

这样模型就能跑通了。
如图:
在这里插入图片描述
对应的ipynb代码链接:https://gitee.com/rengarwang/pytorch-coding/blob/master/pytorch_pandas_test.ipynb

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/356655
推荐阅读
相关标签
  

闽ICP备14008679号