神经网络由对数据进行操作的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. uniapp医院预约挂号微信小程序

    开头感言:最近看小程序很火,也想弄一个看看,用了一些时间从0开始写,也记录了一些笔记,自己用框架写的模板,不是很精美,后面会慢慢优化,功能也是后面慢慢加上去的, 其中功能这块,起初只是一些简单的功能, ...

  2. 阿克曼函数推导过程(m<=3)

    阿克曼函数(Ackermann)是非原始递归函数的例子.它需要两个自然数作为输入值,输出一个自然数.它的输出值增长速度非常快,仅是对于(4,3)的输出已大得不能准确计算. \[A(m, n)=\lef ...

  3. Spring中的@Bean注解

    @Bean 基础概念 @Bean:Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理.产生这个Bean对象的方法Spring只会调用一次,随后这个 ...

  4. 【C\C++笔记】指针输出字符串

    1错误代码 #include<stdio.h> int main(){ char a[]="hello"; char *p=a; for(int i=0;i<5; ...

  5. 漫谈grpc 3:从实践到原理,带你参透 gRPC

    ​ 原文链接:万字长文 | 从实践到原理,带你参透 gRPC 大家好,我是煎鱼. gRPC 在 Go 语言中大放异彩,越来越多的小伙伴在使用,最近也在公司安利了一波,希望这一篇文章能带你一览 gRPC ...

  6. element 表格行内进行编辑

    <template> <div class="process_manage"> <el-card class="box-card" ...

  7. 编写Java程序,创建一个父类交通工具类(Vehicles),以及两个子类,分别是轿车类(Car)和卡车类(Truck)。

    返回本章节 返回作业目录 需求说明: 创建一个父类交通工具类(Vehicles),以及两个子类,分别是轿车类(Car)和卡车类(Truck). 父类有属性品牌(brand)和颜色(color). 在父 ...

  8. Kerberos认证过程学习理解

    概念: Kerberos服务器:AS认证服务器,TGS服务授权服务器 Client 客户端,代表使用应用的用户 AppServer 服务端,应用提供各种服务的服务器 Client在Kerberos注册 ...

  9. XPTH定位总结

    xpath定位总结:nodename 选取此节点的所有子节点. / :从根节点选取.绝对定位 //:从匹配选择的当前节点选择文档中的节点,而不考虑它们的位置. 相对定位(推荐使用相对定位) . :选取 ...

  10. centos7 查看卸载软件

    rpm -e xxx查不到就用下面的 # 查询软件列表# rpm -qa | grep 软件名rpm -qa | grep maxscale # 卸载软件# sudo yum remove 软件名su ...