构建卷积神经网络时,进行的debug
1. NotImplementedError: Module [CNN_Mnist] is missing the required “forward” function
Traceback (most recent call last):
File "E:\cnn_mnist.py", line 66, in <module>
y_pred = model.forward(x_train)
File "E:\software\python\python3.8download\lib\site-packages\torch\nn\modules\module.py", line 246, in _forward_unimplemented
raise NotImplementedError(f"Module [{type(self).__name__}] is missing the required \"forward\" function")
NotImplementedError: Module [CNN_Mnist] is missing the required "forward" function
原因,在初始化时,对forward函数的定义,格式没有对齐,导致没有识别到forward函数。
修改forward函数的递进关系即可。
2.Boolean value of Tensor with more than one value is ambiguous
Traceback (most recent call last):
File "E:\cnn_mnist.py", line 86, in <module>
predicted = max(pred_labels, 1)[1]
RuntimeError: Boolean value of Tensor with more than one value is ambiguous
原因,此时的max函数时python的内置max函数,我们要用的是torch中的max函数,
torch.max(input) → Tensor #返回输入tensor中所有元素的最大值
troch.max()[1] #只返回最大值的每个索引
所以,进行一下修改。
predicted = tourch.max(pred_labels, 1)[1]
3.ValueError: only one element tensors can be converted to Python scalars
print("total acc: %.2f\n" % (correct_count / total))
对模型的准确率进行输出,是数据类型没有转为python 格式,导致报错。
找到correct_count和total的定义,分析。
correct_count += (predicted == test_labels.cuda()).sum().item()
total += len(test_labels)
对correct_count += (predicted == test_labels.cuda()).sum().item()进行理解。
如果预测值等于输出值,进行correct_count +1操作,
.sum() 将所有值相加,得到一个tensor类别的int值,
.item()用于取出tensor中的值,转为python类别。
如果tensor只有一个元素,那么调用item方法的时候就是将tensor转换成python的scalars