神剑山庄资源网 Design By www.hcban.com
python版本3.7,用的是虚拟环境安装的pytorch,这样随便折腾,不怕影响其他的python框架
1、先定义一个类Linear,继承nn.Module
import torch as t from torch import nn from torch.autograd import Variable as V class Linear(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 def forward( self, x ): #参数 x 是一个Variable对象 x = x.mm( self.w ) return x + 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=<AddBackward0>)
下面利用Linear构造一个多层网络
class Perceptron( 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 ) def forward ( self ,x ): x = self.layer1( x ) x = t.sigmoid( x ) #用sigmoid()激活函数 return self.layer2( x )
测试一下
perceptron = Perceptron ( 5,3 ,1 ) for name,param in perceptron.named_parameters(): print( name, param.size() )
输出如预期:
layer1.w torch.Size([5, 3]) layer1.b torch.Size([3]) layer2.w torch.Size([3, 1]) layer2.b torch.Size([1])
以上这篇用pytorch的nn.Module构造简单全链接层实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无用pytorch的nn.Module构造简单全链接层实例的评论...
更新日志
2024年09月30日
2024年09月30日
- 孙悦.1996-伙伴【正大国际】【WAV+CUE】
- 纪钧瀚《钢琴阅读时光 雨中书店聆听轻音乐》[FLAC/分轨][399.62MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[320K/MP3][87.4MB]
- 证声音乐图书馆《走向自然 疗心爵士乐》[FLAC/分轨][184.94MB]
- 陈慧娴.2018-Priscilla-Ism演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 郑秀文.1999-我应该得到(国)【华纳】【WAV+CUE】
- 陈家慧.2011-钢琴酒吧2CD【龙吟唱片】【WAV+CUE】
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[320K/MP3][45.01MB]
- 证声音乐图书馆《雨季 蓝调吉他 Rainy Blues》[FLAC/分轨][109.13MB]
- 赞多《序章》[320K/MP3][45.54MB]
- 许巍.2004-每一刻都是崭新的【步升大风】【WAV+CUE】
- 群星.2024-四方馆影视原声带【韶愔音乐】【FLAC分轨】
- 陈雷.1997-安锁咧【金圆唱片】【WAV+CUE】
- 关淑怡.2013-MY.FAVORITE.SK.3CD【环球】【WAV+CUE】
- Sweety.2006-花言乔语【丰华】【WAV+CUE】