PyTorch 介绍 | 构建神经网络

PyTorch 介绍 | 构建神经网络
神经网络由对数据进行操作的layers/modules组成。torch.nn 命名空间提供了所有你需要的构建块,用于构建你自己的神经网络。PyTorch的每一个module都继承自nn.Module。神经网络本身也是包含其它module(layer)的module。这种嵌套结构允许轻松构建和管理复杂的架构。

下面,我们将构建一个神经网络分类FashionMNIST数据集的图片

import os
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
为训练获取设备
如果可以的话,我们想要能够在一个类似于GPU的硬件加速器上训练模型。检查torch.cuda,否则继续使用CPU。

device = ‘cuda’ if torch.cuda.is_available() else ‘cpu’
print(f"Using {device} device")
输出:

Using cuda device
定义类
通过继承 nn.Module 定义我们的神经网络。利用 init 初始化神经网络的layers。每个 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),
)

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)
)
)
为使用模型,我们传入input data。这将沿着一些background operations执行模型的 forward。不要直接调用 model.forward()

将input输入模型返回维度大小为10的tensor,包含对每个类的原始预测值。我们通过将其传入 nn.Softmax module的实例获取预测概率值。

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([1], device=‘cuda:0’)
Model Layers
让我们来分解一下FashionMNIST模型的layers。为了说明,我们构建了一个具有3个28x28图片样本的minibatch,观察将其输入网络后发生了什么。

input_image = torch.rand(3, 28, 28)
print(input_image.size())
输出:

torch.size([3, 28, 28])
nn.Flatten
初始化 nn.Flatten 层,将每一个2D 28x28图片转换为一个连续的具有784像素值的数组(保留minibatch维度(dim=0))。

flatten = nn.Flatten()
flat_image = flatten(input_image)
print(flat_image.size())
输出:

torch.Size([3, 784])
nn.Linear
linear layer也是一个module,它是对input使用保存的权重和偏置进行线性变换。

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}")
输出:

点击查看代码
Before ReLU: tensor([[-0.2541, -0.1397, 0.2342, 0.1364, -0.0437, 0.3759, 0.2808, -0.0619,
0.2780, 0.2830, -0.4725, 0.4298, 0.2717, -0.1618, -0.0604, 0.3242,
-0.5874, -0.5922, -0.2481, -0.4181],
[-0.1339, -0.1163, 0.1688, 0.1112, 0.1179, 0.3560, 0.0990, -0.1398,
0.2619, -0.1023, -0.7150, -0.1186, 0.3338, -0.0817, 0.1983, -0.2084,
-0.3889, -0.2361, -0.0752, -0.2144],
[-0.1284, 0.0683, 0.0707, 0.0997, -0.2274, 0.4379, 0.1461, 0.0949,
0.2710, -0.0563, -0.6621, -0.3552, 0.4966, 0.2304, 0.0020, -0.0470,
-0.6260, -0.2077, -0.0790, -0.4635]], grad_fn=)

After ReLU: tensor([[0.0000, 0.0000, 0.2342, 0.1364, 0.0000, 0.3759, 0.2808, 0.0000, 0.2780,
0.2830, 0.0000, 0.4298, 0.2717, 0.0000, 0.0000, 0.3242, 0.0000, 0.0000,
0.0000, 0.0000],
[0.0000, 0.0000, 0.1688, 0.1112, 0.1179, 0.3560, 0.0990, 0.0000, 0.2619,
0.0000, 0.0000, 0.0000, 0.3338, 0.0000, 0.1983, 0.0000, 0.0000, 0.0000,
0.0000, 0.0000],
[0.0000, 0.0683, 0.0707, 0.0997, 0.0000, 0.4379, 0.1461, 0.0949, 0.2710,
0.0000, 0.0000, 0.0000, 0.4966, 0.2304, 0.0020, 0.0000, 0.0000, 0.0000,
0.0000, 0.0000]], grad_fn=)
nn.Sequential
nn.Sequential是modules的排序容器。输入数据根据所定义的,按照相同的顺序依次通过所有module。你可以使用顺序容器快速组建一个网络,如 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
神经网络的最后一个线性层返回logits - 原始数值,范围是[-infty, infty] - 传入nn.Softmax module。logits被缩放到[0, 1],表示了模型对每个类别的预测概率值。dim 参数指定了元素的和为1的维度。

softmax = nn.Softmax(dim=1)
pred_probab = softmax(logits)
模型参数
许多神经网络中的层都是参数化的,即具有训练过程中可被优化的相关权重和偏置。继承nn.Module自动跟踪模型对象定义的所有区域,并使得所有参数都可通过模型的 parameters() 或 named_parameters()方法访问。

print("Model structure: ", model, ‘\n\n’)

for name, param in model.named_parameters():
print(f:“Layer: {} | 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)
)
)

Layer: linear_relu_stack.0.weight | Size: torch.Size([512, 784]) | Values : tensor([[-0.0169, 0.0327, -0.0128, …, -0.0273, 0.0193, -0.0197],
[ 0.0309, 0.0003, -0.0232, …, 0.0284, -0.0163, 0.0171]],
device=‘cuda:0’, grad_fn=)

Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([-0.0060, -0.0333], device=‘cuda:0’, grad_fn=)

Layer: linear_relu_stack.2.weight | Size: torch.Size([512, 512]) | Values : tensor([[-0.0294, 0.0120, -0.0287, …, -0.0280, -0.0299, 0.0083],
[ 0.0260, -0.0075, 0.0430, …, -0.0196, -0.0200, 0.0145]],
device=‘cuda:0’, grad_fn=)

Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([-0.0003, -0.0043], device=‘cuda:0’, grad_fn=)

Layer: linear_relu_stack.4.weight | Size: torch.Size([10, 512]) | Values : tensor([[-0.0287, -0.0199, -0.0147, …, 0.0074, 0.0403, 0.0068],
[ 0.0375, -0.0005, 0.0372, …, -0.0426, -0.0094, -0.0081]],
device=‘cuda:0’, grad_fn=)

Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([-0.0347, 0.0438], device=‘cuda:0’, grad_fn=)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值