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