debug

构建卷积神经网络时,进行的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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值