神经网络由对数据进行操作的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=<AddmmBackward0>) 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=<ReluBackward0>)

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=<SliceBackward0>) Layer: linear_relu_stack.0.bias | Size: torch.Size([512]) | Values : tensor([-0.0060, -0.0333], device='cuda:0', grad_fn=<SliceBackward0>) 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=<SliceBackward0>) Layer: linear_relu_stack.2.bias | Size: torch.Size([512]) | Values : tensor([-0.0003, -0.0043], device='cuda:0', grad_fn=<SliceBackward0>) 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=<SliceBackward0>) Layer: linear_relu_stack.4.bias | Size: torch.Size([10]) | Values : tensor([-0.0347, 0.0438], device='cuda:0', grad_fn=<SliceBackward0>)

延伸阅读

PyTorch 介绍 | BUILD THE NEURAL NETWORK的更多相关文章

  1. Neural Network Programming - Deep Learning with PyTorch with deeplizard.

    PyTorch Prerequisites - Syllabus for Neural Network Programming Series PyTorch先决条件 - 神经网络编程系列教学大纲 每个 ...

  2. 课程一(Neural Networks and Deep Learning),第四周(Deep Neural Networks) —— 3.Programming Assignments: Deep Neural Network - Application

    Deep Neural Network - Application Congratulations! Welcome to the fourth programming exercise of the ...

  3. 课程一(Neural Networks and Deep Learning),第四周(Deep Neural Networks)——2.Programming Assignments: Building your Deep Neural Network: Step by Step

    Building your Deep Neural Network: Step by Step Welcome to your third programming exercise of the de ...

  4. 机器学习: Python with Recurrent Neural Network

    之前我们介绍了Recurrent neural network (RNN) 的原理: http://blog.csdn.net/matrix_space/article/details/5337404 ...

  5. Convolutional neural network (CNN) - Pytorch版

    import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # ...

  6. Recurrent neural network (RNN) - Pytorch版

    import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # ...

  7. Recurrent Neural Network系列2--利用Python,Theano实现RNN

    作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...

  8. Convolutional Neural Network in TensorFlow

    翻译自Build a Convolutional Neural Network using Estimators TensorFlow的layer模块提供了一个轻松构建神经网络的高端API,它提供了创 ...

  9. 计算机视觉学习记录 - Implementing a Neural Network from Scratch - An Introduction

    0 - 学习目标 我们将实现一个简单的3层神经网络,我们不会仔细推到所需要的数学公式,但我们会给出我们这样做的直观解释.注意,此次代码并不能达到非常好的效果,可以自己进一步调整或者完成课后练习来进行改 ...

随机推荐

  1. C# RabbitMQ的使用

    本文目的如题. 安装 先说一下RabbitMQ的安装,建议使用Docker镜像安装,Docker安装的好处是不管Windows系统还是Linux,安装步骤少,安装方法相同,不容易出错.使用下面的命令就 ...

  2. 【嵌入式】arduino IDE串口监视器可以正常使用但其他软件发送串口指令没有反应的问题

    解决办法: 1.检查 波特率baudrate 是否一致 2.检查 数据位长度databits 是否一致 3.检查 停止位长度stopbits 是否一致 4.检查 奇偶校验位 是否一致 5.(特殊)是否 ...

  3. NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis

    目录 概 主要内容 positional encoding 额外的细节 代码 Mildenhall B., Srinivasan P. P., Tancik M., Barron J. T., Ram ...

  4. DEFENSE-GAN: PROTECTING CLASSIFIERS AGAINST ADVERSARIAL ATTACKS USING GENERATIVE MODELS

    目录 概 主要内容 Samangouei P, Kabkab M, Chellappa R, et al. Defense-GAN: Protecting Classifiers Against Ad ...

  5. ACE_Get_Opt函数笔记

    #include "ace/OS_NS_string.h" #include "ace/Configuration.h" #include "ace/ ...

  6. [数据结构]常见数据结构的typedef类型定义总结

    目录 数据结构类型定义: 1.线性表 线性表(顺序存储类型描述): 线性表(动态存储类型描述) 2.线性表的链式表示 双链表的结点类型描述: 静态链表结点类型的描述: 3.栈的数据结构 顺序栈的数据结 ...

  7. 面试中问你MySql,这一篇就够了

    说一说主键索引与唯一索引 主键是一种约束,唯一索引是一种索引,两者在本质上是不同的. 主键索引默认是聚簇索引.唯一索引一般是非聚簇索引. 主键索引不能为空,唯一索引在InnoDB中可以出现多个null ...

  8. TortoiseGit使用技巧

    汇总TortoiseGit使用技巧,包括提交代码,创建patch等等. 1.提交代码到本地仓库 在Git工程目录下右键, 点击 Git Commit -> "master". ...

  9. hadoop 之 hadoop2.7.7升级到hadoop2.8.5

    服务器规划 准备阶段 停服务 stop-yarn.sh stop-dfs.sh 备份 备份NameNode目录 ---------- 101,102操作 ----------------- hdfs- ...

  10. Autofac实现有条件的DI

    Autofac.Annotation框架是我用.netcore写的一个DI框架,基于Autofac参考 Spring注解方式所有容器的注册和装配,切面,拦截器等都是依赖标签来完成. 开源地址:http ...