pytorch学习笔记(七)

一、全连接层

全连接层:通常所说的全连接层是指一个由多个神经元组成的层,其所有的输出和该层所有的输入都有连接,即每个输入都会影响所有的神经元的输出。在pytorch中的nn.Linear()表示线性变换,全连接层可以看作是nn.Linear()表示线性边层再加上一个激活函数层所构成的结构。
具体操作如下:
  torch.nn.Linear(in_features,out_features, bias = True)
  in_features:每个输入样本的特征数量(看作神经元个数)。
  out_features:每个样本输出的特征数量。
  bias :是否添加偏置。
Linear的输入为(N,in_features)的张量,输出为(N,out_features)的张量。

import torch
import torch.nn as nn
a = torch.randn([1, 784])
print(a.shape)

layer1 = nn.Linear(784, 200)
layer2 = nn.Linear(200, 200)
layer3 = nn.Linear(200, 10)

x = layer1(a)
print(x.shape)
x = layer2(a)
print(x.shape)
x = layer3(a)
print(x.shape)

输出结果

torch.Size([1, 784])
torch.Size([1, 200])
torch.Size([1, 200])
torch.Size([1, 10])

二、加入激活函数relu

import torch
import torch.nn as nn
a = torch.randn([1, 784])
print(a.shape)

x1 = layer1(a)
x1 = nn.functional.relu(x1, inplace=True)
print(x1.shape)

x2 = layer2(x1)
x2= nn.functional.relu(x2, inplace=True)
print(x2.shape)

x3 = layer3(x2)
x3 = nn.functional.relu(x3, inplace=True)
print(x3.shape)

输出结果

torch.Size([1, 200])
torch.Size([1, 200])
torch.Size([1, 10])

三、封装网络结构

class MLP(nn.Module):
    def __init__(self):
        super(MLP, self).__init__()
        self.model = nn.Sequential(
            nn.Linear(784, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 200),
            nn.LeakyReLU(inplace=True),
            nn.Linear(200, 10),
            nn.LeakyReLU(inplace=True),

        )

        def forward(self, x):
            x = self.model(x)
            return x

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值