pytorch神经网络工具箱nn

1、全连接

import torch as t
from torch.autograd import Variable as V
from torch import nn


class Linear(nn.Module):
    def __init__(self, in_features, out_features):
        super(Linear, self).__init__() 
        self.w = nn.Parameter(t.randn(in_features, out_features))
        self.b = nn.Parameter(t.randn(out_features))

    def forward(self, x):
        x = x.mm(self.w)
        return x + self.b.expand_as(x)


if __name__ == '__main__':
    layer = Linear(4, 3)
    input = V(t.randn(2, 4))
    output = layer(input)
    print(output)


out:
tensor([[ 0.1976, -2.5591,  1.7264],
        [-1.3980, -1.9007,  2.3434]], grad_fn=<AddBackward0>)

(1) 自定义层Linear必须继承nn.Module,  super(Linear, self).__init__()等价与nn.Module.__init__(self).

(2)在构造函数__init__中必须自己定义可学习的参数,并封装成Parameter,  Parameter是一种特殊的Variable, 其默认是自动求导的。

(3)forward函数实现前向传播,

(4)无需写反向传播函数,因为前向传播都是对variable进行操作。

(5)Module中学习的参数可以通过named_parameters()或者parameters()返回迭代器,

 

2、前馈网络的两种简化方式--ModuleList和Sequential

(1)Sequential的三种写法

# 方式1
net1 = nn.Sequential()
net1.add_module('conv', nn.Conv2d(3, 3, 3))
net1.add_module('batchnorm', nn.BatchNorm2d(3))
net1.add_module('activation_layer', nn.ReLU())

# 方式2
net2 = nn.Sequential(
    nn.Conv2d(3, 3, 3),
    nn.BatchNorm2d(3),
    nn.ReLU()
)

# 方式3
from collections import OrderedDict
net3 = nn.Sequential(OrderedDict([
    ('conv', nn.Conv2d(3, 3, 3)),
    ('bn1', nn.BatchNorm2d(3)),
    ('relu1', nn.ReLU())
]))

(2) ModuleList

nn.ModuleList([nn.Linear(3, 4), nn.ReLU(), nn.Linear(4, 2)])

3、 优化器

from torch import optim

 

4、nn.functional

与nn.Module会自动提取可学习的参数,而nn.functional 中的函数更像是纯函数。何时使用,如果模型有可学习的参数,最好用nn.Module,否则两者都可使用。

 

5、初始化策略

from torch.nn import init

如果不支持初始化,也可以自己进行初始化。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值