深度学习框架PyTorch:入门与实践 学习(三)

nn.Module

用nn.Module实现全连接层

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

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))
        print(self.w.shape)
        self.b = nn.Parameter(t.randn(out_features))

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

layer = Linear(4, 3)
input = V(t.randn(2, 4))
print(input.shape)
output = layer(input)
print(output)

for name, parameter in layer.named_parameters():
    print(name, parameter)

  1. 自定义层必须继承nn.Module,并在构造函数中调用nn.Module的构造函数,即super(Linear, self)__init__(),可利用前面自定义的层作为当前m
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值