用pytorch的nn.Module构造简单全链接层实例
python版本3.7,用的是虚拟环境安装的pytorch,这样随便折腾,不怕影响其他的python框架
1、先定义一个类Linear,继承nn.Module
importtorchast fromtorchimportnn fromtorch.autogradimportVariableasV classLinear(nn.Module): '''因为Variable自动求导,所以不需要实现backward()''' def__init__(self,in_features,out_features): super().__init__() self.w=nn.Parameter(t.randn(in_features,out_features))#权重w注意Parameter是一个特殊的Variable self.b=nn.Parameter(t.randn(out_features))#偏值b defforward(self,x):#参数x是一个Variable对象 x=x.mm(self.w) returnx+self.b.expand_as(x)#让b的形状符合输出的x的形状
2、验证一下
layer=Linear(4,3) input=V(t.randn(2,4))#包装一个Variable作为输入 out=layer(input) out
#成功运行,结果如下:
tensor([[-2.1934,2.5590,4.0233],[1.1098,-3.8182,0.1848]],grad_fn=
下面利用Linear构造一个多层网络
classPerceptron(nn.Module): def__init__(self,in_features,hidden_features,out_features): super().__init__() self.layer1=Linear(in_features,hidden_features) self.layer2=Linear(hidden_features,out_features) defforward(self,x): x=self.layer1(x) x=t.sigmoid(x)#用sigmoid()激活函数 returnself.layer2(x)
测试一下
perceptron=Perceptron(5,3,1) forname,paraminperceptron.named_parameters(): print(name,param.size())
输出如预期:
layer1.wtorch.Size([5,3]) layer1.btorch.Size([3]) layer2.wtorch.Size([3,1]) layer2.btorch.Size([1])
以上这篇用pytorch的nn.Module构造简单全链接层实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。