写在前面:最近刚开始入门深入学习,找来了相关书籍,大概了解了一下原理后跟着书敲代码,结果遇到了如题所示的报错,看了CSDN上的几篇相关文章后,基本确定这类报错一般是由于代码某一部分输入不当引起的,不同的人有不同的引起代码错误的原因,下面来贴一下我的错误。所用系统:linux;

pytorch版本:1.8;

参考书籍:《pytorch深度学习实战,从新手小白到数据科学家》 2020年8月第一版(距离我写这篇文章不过几个月,还是比较新的,但是技术更迭太快,框架也在不断更新,如果再过几年的朋友再看这篇文章,最下面的正确代码可能也会不适用了,跟框架相比,懂基础原理显得更为重要)

一开始的版本

#build netual network inplement nn.Module,need to def  __init__ and forward function
import torch
class Layertry(torch.nn.Module):
    def __init__ (self,l_in,h,l_out):
        super(Layertry,self).__init__ ()
        self.linear1=torch.nn.Linear(l_in,h)
        self.relu=torch.nn.Relu()
        self.linear2=torch.nn.Linear(h,l_out)
    def forward(self,x):
        h_relu=self.relu(self.linear1(x).clamp(min=0))
        y_pred=self.linear2(h_relu)
        return y_pred
model2=Layertry(10,20,2)

失误原因:对ReLU()不熟悉,只是依葫芦画瓢地打代码,连拼写出错都没检查出来……

修正后

#build netual network inplement nn.Module,need to def  _init_ and forward function
import torch
class Layertry(torch.nn.Module):
    def __init__ (self,l_in,h,l_out):
        super(Layertry,self).__init__ ()
        self.linear1=torch.nn.Linear(l_in,h)
        self.relu=torch.nn.ReLU()
        self.linear2=torch.nn.Linear(h,l_out)
    def forward(self,x):
        h_relu=self.relu(self.linear1(x).clamp(min=0))
        y_pred=self.linear2(h_relu)
        return y_pred
model2=Layertry(10,20,2)

修改后运行结果如下:

Layertry(
  (linear1): Linear(in_features=10, out_features=20, bias=True)
  (relu): ReLU()
  (linear2): Linear(in_features=20, out_features=2, bias=True)
)

写在最后:屏幕前的你刚好与我遇到同一个问题的可能性不大,不过我还是希望这篇文章也能对你有所启发和帮助。

GitHub 加速计划 / li / linux-dash
10
2
下载
A beautiful web dashboard for Linux
最近提交(Master分支:19 天前 )
186a802e added ecosystem file for PM2 5 年前
5def40a3 Add host customization support for the NodeJS version 5 年前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐