神经网络由对数据进行操作的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. 《HelloGitHub》第 69 期

    兴趣是最好的老师,HelloGitHub 让你对编程感兴趣! 简介 HelloGitHub 分享 GitHub 上有趣.入门级的开源项目. https://github.com/521xueweiha ...

  2. Differential Evolution: A Survey of the State-of-the-Art

    @ 目录 概 主要内容 DE/rand/1/bin DE/?/?/? DE/rand/1/exp DE/best/1 DE/best/2 DE/rand/2 超参数的选择 的选择 的选择 的选择 一些 ...

  3. CS5211替代CH7511B|设计DP转LVDS转接板|替代CH7511B

    CH7511B是一款DP转lvds屏转换芯片CH7511B是一款eDP转LVDS转换芯片.CH7511B将嵌入式DisplayPort信号转换为LVDS(低压差分信号).通过CH7511B的高级解码/ ...

  4. 使用JavaScript 中的Math对象和勾股定理公式,计算鼠标的位置与页面图片中心点的距离,根据距离对页面上的图片进行放大或缩小处理。距离远时图片放大,距离近时图片缩小

    查看本章节 查看作业目录 需求说明: 使用JavaScript 中的Math对象和勾股定理公式,计算鼠标的位置与页面图片中心点的距离,根据距离对页面上的图片进行放大或缩小处理.距离远时图片放大,距离近 ...

  5. Notepad++快速选中多行

    我们在编辑文章的时候, 通常需要选择多行连续的文本, 可以使用Shift+鼠标选择多行文本, 如果一次需要选择的文本太多, 比如选择10000到20000行之间的文本, 鼠标要拉好久,手一累一抖,又要 ...

  6. TypeScript中文教程基础部分上----翻译自TS官方

    为什么使用TS? js中每一个值在不同的操作运行中表现出一系列不同的行为,比如说下面这个例子: message.toLowerCase();message(); 逐行看下,第一行调用了message的 ...

  7. Docker_创建自定义镜像(5)

    生成docker镜像有两种方式 使用已有容器生成镜像 使用dockerfile生成镜像 一.使用已有容器生成镜像 1.下载centos镜像,并创建容器 2.进入容器部署python环境 centos镜 ...

  8. python 中的省略号

    在查看django源码时遇到下列内容:sweat: 这个省略号是什么意思? 来自为知笔记(Wiz)

  9. JMeter_性能压测报错address already in use:connect

    报错截图如下: 原因分析: 这个问题的原因是windows端口被耗尽了(默认1024-5000),而且操作系统要 2~4分钟才会重新释放这些端口,所以可以增加windows的可用端口来解决.windo ...

  10. Kubernetes最佳实践之腾讯云TKE 集群组建

    作者陈鹏,腾讯工程师,负责腾讯云 TKE 的售中.售后的技术支持,根据客户需求输出合理技术方案与最佳实践,为客户业务保驾护航.使用 TKE 来组建 Kubernetes 集群时,会面对各种配置选项,本 ...