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

yipeiwu_com6年前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数据预处理的具体代码,供大家参考,具体内容如下 1.导入标准库 import numpy as np import matplotlib.pyplo...

分析在Python中何种情况下需要使用断言

这个问题是如何在一些场景下使用断言表达式,通常会有人误用它,所以我决定写一篇文章来说明何时使用断言,什么时候不用。 为那些还不清楚它的人,Python的assert是用来检查一个条件,如...

Python迭代和迭代器详解

迭代器 迭代器(iterator)有时又称游标(cursor)是程式设计的软件设计模式,可在容器物件(container,例如链表或阵列)上遍访的界面,设计人员无需关心容器物件的内存分配...

Python enumerate函数遍历数据对象组合过程解析

这篇文章主要介绍了Python enumerate函数遍历数据对象组合过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 介绍...

一份python入门应该看的学习资料

一份python入门应该看的学习资料

网上学习的时候总会遇到一些好的文章,分享给大家,也谢谢作者的分享。 Python 简介 Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。 Python...