PyTorch 介绍 | BUILD THE NEURAL NETWORK
神经网络由对数据进行操作的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的更多相关文章
- Neural Network Programming - Deep Learning with PyTorch with deeplizard.
PyTorch Prerequisites - Syllabus for Neural Network Programming Series PyTorch先决条件 - 神经网络编程系列教学大纲 每个 ...
- 课程一(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 ...
- 课程一(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 ...
- 机器学习: Python with Recurrent Neural Network
之前我们介绍了Recurrent neural network (RNN) 的原理: http://blog.csdn.net/matrix_space/article/details/5337404 ...
- Convolutional neural network (CNN) - Pytorch版
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # ...
- Recurrent neural network (RNN) - Pytorch版
import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms # ...
- Recurrent Neural Network系列2--利用Python,Theano实现RNN
作者:zhbzz2007 出处:http://www.cnblogs.com/zhbzz2007 欢迎转载,也请保留这段声明.谢谢! 本文翻译自 RECURRENT NEURAL NETWORKS T ...
- Convolutional Neural Network in TensorFlow
翻译自Build a Convolutional Neural Network using Estimators TensorFlow的layer模块提供了一个轻松构建神经网络的高端API,它提供了创 ...
- 计算机视觉学习记录 - Implementing a Neural Network from Scratch - An Introduction
0 - 学习目标 我们将实现一个简单的3层神经网络,我们不会仔细推到所需要的数学公式,但我们会给出我们这样做的直观解释.注意,此次代码并不能达到非常好的效果,可以自己进一步调整或者完成课后练习来进行改 ...
随机推荐
- 主流的 API 架构
1. RPC:调用另一个系统的函数 2. SOAP:使数据作为服务可用 3. REST:使数据作为资源可用 4. GraphQL:仅请求所需要的数据 1. RPC:调用另一个系统的函数 远程过程调用是 ...
- kubernetes运行应用1之Deployment
run 或create deployment 部署一个应用 kubernetes 部署 nginx ,使用 kubectl get deployment 时出现 No resources found ...
- python 面向对象:类属性
一.概念和使用 类属性就是给类对象定义的属性 类属性用于记录与这个类相关的特征 类属性不会用于记录具体对象的特征 使用赋值语句在 class 关键字下方可以定义类属性 二.代码演示 示例需求: 定 ...
- 拓展 Array 方法
为 Array 对象扩展了一个迭代器之后,就可以利用这个法代器进一步拓展 Array 的方法,使其能够完成更多的实用功能. Array.prototype.each = function( f ) { ...
- Spark-local本地环境搭建
注:图片如果损坏,点击文章链接:https://www.toutiao.com/i6815385772254822919/ 承接上一个文档<Spark源码编译> 解压spark编译好的压缩 ...
- HDU 2044 一只小蜜蜂... (斐波那契数列)
原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=2044 题目分析:其实仔细读题就会发现其中的规律, 其中:这是一个典型的斐波那契数列. 代码如下: #i ...
- C#进程调用FFmpeg操作音视频
项目背景 因为公司需要对音视频做一些操作,比如说对系统用户的发音和背景视频进行合成,以及对多个音视频之间进行合成,还有就是在指定的源背景音频中按照对应的规则在视频的多少秒钟内插入一段客户发音等一些复杂 ...
- 解析HetuEngine实现On Yarn原理
摘要:本文介绍HetuEngine实现On Yarn的原理,通过阅读本文,读者可以了解HetuEngine如何在资源使用方面融入Hadoop生态体系. 本文分享自华为云社区<MRS HetuEn ...
- dubbo接口方法重载且入参未显式指定序列化id导致ClassCastException分析
问题描述&模拟 线上登录接口,通过监控查看,有类型转换异常,具体报错如下图 此报错信息是dubbo consumer端显示,且登录大部分是正常,有少量部分会报类型转换异常,同事通过更换方法名+ ...
- Android Sensor.TYPE_STEP_COUNTER 计步器传感器 步数统计
注意:使用 计步器传感器 Sensor.TYPE_STEP_COUNTER 获取步数前需要手机支持该传感器 1.学习资料 1.1 SENSOR.TYPE_STEP_COUNTER 地址:开发者文档 翻 ...