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

yipeiwu_com5年前Python基础

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构造简单全链接层实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python实现合并两个数组的方法

本文实例讲述了python实现合并两个数组的方法。分享给大家供大家参考。具体如下: python合并两个数组,将两个数组连接成一个数组,例如,数组 a=[1,2,3] ,数组 b=[4,...

python保存文件方法小结

1>保存为二进制文件,pkl格式 import pickle pickle.dump(data,open('file_path','wb')) #后缀.pkl可加可不加 若文...

python中django框架通过正则搜索页面上email地址的方法

本文实例讲述了python中django框架通过正则搜索页面上email地址的方法。分享给大家供大家参考。具体实现方法如下: import re from django.shortc...

Python中的单继承与多继承实例分析

本文实例讲述了Python中的单继承与多继承。分享给大家供大家参考,具体如下: 单继承 一、介绍 Python 同样支持类的继承,如果一种语言不支持继承,类就没有什么意义。派生类的定义如...

Python3 关于pycharm自动导入包快捷设置的方法

Python3 关于pycharm自动导入包快捷设置的方法

正常开发的时候,我们都手动去写要引入到包,有过java开发的同事,用过快捷键ctrl + alt + o 会自动引入所有的依赖包,pycharm也有这样的设置,看看怎么设置吧。 设置快...