Pytorch(5)-BUILD THE NEURAL NETWORK建立神经网络
文章目录
建立神经网络
神经网络由对数据执行操作的层/模块组成。该torch.nn命名空间提供了所有你需要建立自己的神经网络的blocks。PyTorch中的每个模块都将nn.Module子类化。神经网络本身就是一个由其他模块(层)组成的模块。这种嵌套结构允许轻松地构建和管理复杂的体系结构。
在以下各节中,我们将构建一个神经网络来对FashionMNIST数据集中的图像进行分类。
import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
Get Device for Training
我们希望能够在硬件加速器(如GPU)上训练模型(如果有)。让我们检查一下 torch.cuda是否可用,否则我们将继续使用CPU。
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))
output:
Using cuda device
定义类别
我们通过子类化定义神经网络nn.Module,并在中初始化神经网络层__init__。每个nn.Module子类都对forward方法中的输入数据执行操作。
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
nn.ReLU(),
nn.Linear(512, 512),
nn.ReLU(),
nn.Linear(512, 10),
nn.ReLU()
)
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
我们创建的实例NeuralNetwork,并将其移至device,并打印其结构。
model = NeuralNetwork().to(device)
print(model)
NeuralNetwork(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear_relu_stack): Sequential(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): ReLU()
(2): Linear(in_features=512, out_features=512, bias=True)
(3): ReLU()
(4): Linear(in_features=512, out_features=10, bias=True)
(5): ReLU()
)
)
要使用该模型,我们将输入数据传递给它。这将执行模型forward以及一些后台操作。不要直接 call model.forward()方法
在输入上调用模型将返回一个10维张量,其中包含每个类的原始预测值。我们通过将其传递给nn.Softmax模块实例来获得预测概率。
X = torch.rand(1, 28, 28, device=device)
logits = model(X)
pred_probab = nn.Softmax(dim=1)(logits)
y_pred = pred_probab.argmax(1)
print(f"Predicted class: {y_pred}")
Predicted class: tensor([0], device='cuda:0')
模型层
让我们细分FashionMNIST模型中的各个层。为了说明这一点,我们将抽取3个大小为28x28的图像的小批量样本,并观察当它通过网络传递时发生了什么。
input_image = torch.rand(3,28,28)
print(input_image.size())
torch.Size([3, 28, 28])
nn.Flatten
我们初始化nn.Flatten 层,将每个2D 28x28图像转换为784个像素值的连续数组(维持了最小批处理尺寸(在dim = 0时))。
flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
torch.Size([3, 784])
nn.Linear
线性层 是使用其存储的权重和偏置所述输入施加线性变换的模块。
layer1 = nn.Linear(in_features=28*28, out_features=20)
hidden1 = layer1(flat_image)
print(hidden1.size())
torch.Size([3, 20])
nn.ReLU
非线性激活会在模型的输入和输出之间创建复杂的映射。它们在线性变换之后被应用以引入非线性,从而帮助神经网络学习各种各样的现象。
在此模型中,我们在线性层之间使用nn.ReLU,但还有其他激活可以在模型中引入非线性。
print(f"Before ReLU: {hidden1}\n\n")
hidden1 = nn.ReLU()(hidden1)
print(f"After ReLU: {hidden1}")
nn.Sequential
nn.Sequential是模块的有序容器。数据按照定义的顺序通过所有模块。您可以使用顺序容器将类似的快速网络组合在一起seq_modules。
seq_modules = nn.Sequential(
flatten,
layer1,
nn.ReLU(),
nn.Linear(20, 10)
)
input_image = torch.rand(3,28,28)
logits = seq_modules(input_image)
nn.Softmax
神经网络的最后一个线性层返回logit -[-infty,infty]中的原始值-将其传递到 nn.Softmax模块。将对数缩放为[0,1]值,该值表示每个类别的模型的预测概率。dim参数表示必须将值加起来为1的维度。
softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
Model Parameters
神经网络内部的许多层均已参数化,即具有相关的权重和偏差,这些权重和偏差在训练期间进行了优化。子类化nn.Module自动跟踪模型对象内部定义的所有字段,并使用模型parameters()或named_parameters()方法访问所有参数。
在此示例中,我们遍历每个参数,并打印其大小和值的预览。
named_parameters()字典返回name, param
name:Layer param.Size param.Values
print("Model structure: ", model, "\n\n")
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values : {param[:2]} \n")
Model structure: NeuralNetwork(
(flatten): Flatten(start_dim=1, end_dim=-1)
(linear_relu_stack): Sequential(
(0): Linear(in_features=784, out_features=512, bias=True)
(1): ReLU()
(2): Linear(in_features=512, out_features=512, bias=True)
(3): ReLU()
(4): Linear(in_features=512, out_features=10, bias=True)
(5): ReLU()
)
)
Layer: linear_relu_stack.0.weight | Size: torch.Size([512, 784]) | Values : tensor([[ 0.0162, 0.0121, -0.0109, ..., -0.0290, -0.0324, -0.0006],
[-0.0345, 0.0246, -0.0126, ..., 0.0274, 0.0213, -0.0283]],
device='cuda:0', grad_fn=<SliceBackward>)
Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([-0.0352, -0.0020], device='cuda:0', grad_fn=<SliceBackward>)
Layer: linear_relu_stack.2.weight | Size: torch.Size([512, 512]) | Values : tensor([[-0.0011, 0.0311, -0.0367, ..., -0.0133, -0.0049, -0.0121],
[ 0.0409, -0.0321, 0.0395, ..., 0.0087, 0.0121, 0.0420]],
device='cuda:0', grad_fn=<SliceBackward>)
Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([ 0.0051, -0.0063], device='cuda:0', grad_fn=<SliceBackward>)
Layer: linear_relu_stack.4.weight | Size: torch.Size([10, 512]) | Values : tensor([[-0.0298, 0.0097, 0.0397, ..., 0.0076, 0.0193, -0.0279],
[ 0.0129, -0.0059, -0.0007, ..., -0.0307, 0.0081, -0.0435]],
device='cuda:0', grad_fn=<SliceBackward>)
Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([-0.0245, 0.0133], device='cuda:0', grad_fn=<SliceBackward>)