您的位置:首页 > 其它

用pytorch的nn.Module构造简单全链接层实例

2020-02-13 11:33 495 查看

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构造简单全链接层实例就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息