用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去除空格和换行符的实现方法(推荐)

一、去除空格 strip() "   xyz   ".strip()      &nb...

在django admin中添加自定义视图的例子

django admin提供了完善的用户管理和数据模型管理,方便实用。研究了一下在admin里面添加自己的页面。 在admin.py里继承django.contrib.admin.Mod...

python禁用键鼠与提权代码实例

要求 利用python实现禁用键盘鼠标 思路 经过查阅资料目前最好的办法是采用ctypes中的dll文件进行编写 from ctypes import * improt time...

python3调用R的示例代码

由于工作需要,在做最优分箱的时候,始终写不出来高效的代码,所以就找到了R语言中的最优分箱的包,这个时候考虑到了在python中调用R语言,完美结合。在国内的中文网站搜了半天,搭建环境的时...

python图像处理入门(一)

python图像处理入门(一)

一、环境 由于这学期开了图像处理这门课,所以想着在各种实验开始之前自己先动手试一下 图像处理那首先要配个环境嘛,配环境真的是我长久以来的噩梦了,每次都会出现奇奇怪怪的问题,首先上网查找了...