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
#成功运行,结果如下:
tenso