torch中常见的错误信息

运行代码过程中,遇到的一些问题,今天汇总了一些,希望可以帮助大家,解决一些类似的错误问题。

1.报错信息:RuntimeError: mat1 dim 1 must match mat2 dim 0

错误原因:全连接层 前网络结构 的输出 与全连接层的输入层维度不符合,如下列错误所示:

self.fc1 = nn.Linear(124, 121)
self.fc2 = nn.Linear(120, 81)

解决方案:print下 全连接层前网络结构 的输出 将其输出与全连接层输入层相对应。

假设forward中要依次执行fc1和fc2,fc1的out_features 等于fc2的in_features就不会有错误,这里都是120不会有错误,修改后,如下所示:

self.fc1 = nn.Linear(124, 120)
self.fc2 = nn.Linear(120, 81)

扩展:nn.Linear()

in_features指的是输入的二维张量的大小,即输入的[batch_size, size]中的size。
out_features指的是输出的二维张量的大小,即输出的二维张量的形状为[batch_size,output_size],当然,它也代表了该全连接层的神经元个数。

2.报错信息:IndexError: Dimension out of range (expected to be in range of [-2, 1], but got 2)

报错原因:问题出在维度上,因为少了一个维度,输入的是二维的,而人家需要的是三维的。

解决方案:

a.数据进行reshape

data = data.reshape(height, weight, 1)
#从二维增加到三维

b.或者使用unsqueeze()函数

data = data.unsqueeze(1)
#在第二维增加一维

扩展: unsqueeze()函数是对数据维数进行扩展,squeeze()函数是对数据维数进行压缩,但是两个函数只能对一的维度进行扩展或压缩处理,括号数字为几,就是指定数据data的的第几维数 进行维度为1的处理。

3.报错信息:AttributeError: 'Tensor' object has no attribute 'gpu' 或者TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

    在使用GPU进行神经网络的训练或者进一步操作时,会遇到AttributeError: 'Tensor' object has no attribute 'gpu' 或者TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.这样的问题。

报错原因:在我们想把 GPU tensor 转换成 Numpy 变量的时候,需要先将 tensor 转换到 CPU 去,因为 Numpy 是 CPU的only 专属。

解决方案:把报错代码中的所有gpu改为cpu,如下列所示:

改之前:

loss_list.append(loss.data.gpu().numpy())
y_pred = np.argmax(y_pred_prob.data.gpu().numpy(), axis=1)
batch_accu = np.sum(y_pred == y.data.gpu().numpy(), dtype=np.float32) / y_pred.shape[0]

改之后:

loss_list.append(loss.data.cpu().numpy())
y_pred = np.argmax(y_pred_prob.data.cpu().numpy(), axis=1)
batch_accu = np.sum(y_pred == y.data.cpu().numpy(), dtype=np.float32) / y_pred.shape[0]

3.报错信息:IndexError: scatter_(): Expected dtype int64 for index.

报错原因:
scatter要求数据是int64类型,而我在定义tensor时写的是torch.Tensor(x),应该写成torch.LongTensor(x),指定为int64类型。

解决方案:找到原数据的定义方式,一般在dtype=np.int64;dtype=np.float32中(多数定义函数都有dtype属性最好int和float的位数要一致torch.from_numpy()产生的tensor类型为int32,因此需要用data = torch.tensor(data,dtype = torch.int64)进行数据类型的转换

data = torch.tensor(data,dtype = torch.int64)

4.报错信息:TypeError: expected np.ndarray (got int)

解决方案:出现此错误时将torch.from_numpy()改为torch.Tensor()即可

5.报错信息:RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target'

报错原因:是关于label的错误。修改办法总结一下:
1、RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target',在这个报错中,标红的地方是关键,找到程序中的label,比如说在loss处,如下所示:

解决方案:改变下标签的数据类型

修改前:

Loss = torch.nn.CrossEntropyLoss()
loss = Loss(out, label)

修改后:

Loss = torch.nn.CrossEntropyLoss()
loss = Loss(out, label.long())

补充:多次报这个错误后发现,它说是什么类型,直接在label后面加上对应的类型即可。

6.报错信息:AttributeError: 'xx' object has no attribute xx

报错原因:报错所在的地方可能多空了一格。

解决方案:按“TAB"+"SHIFT" 删除空格。

修改前:

class MyLed(QAbstractButton):
    def __init__(self, parent=None):
        super(MyLed, self).__init__(parent)
        self.initUI()

        def initUI(self):
            self.setMinimumSize(24, 24)
            self.setCheckable(True)
            self.scaledSize = 1000.0    #为方便计算,将窗口短边值映射为1000
            self.setLedDefaultOption()

    def setLedDefaultOption(self):
        for attr, val in zip(allAttributes, allDefaultVal):
            setattr(self, attr, val)
        self.update()

修改后:

class MyLed(QAbstractButton):
    def __init__(self, parent=None):
        super(MyLed, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setMinimumSize(24, 24)
        self.setCheckable(True)
        self.scaledSize = 1000.0    #为方便计算,将窗口短边值映射为1000
        self.setLedDefaultOption()

    def setLedDefaultOption(self):
        for attr, val in zip(allAttributes, allDefaultVal):
            setattr(self, attr, val)
        self.update()

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月4日 下午12:05
下一篇 2023年3月4日 下午12:07

相关推荐