Chpater 2 PyTorch Fundamentals
本章节主要是Pytorch的使用介绍,本笔记也只会记录其中一些比较好的技巧的应用,其他基础应用可百度或查看官方文档进行查阅。
- 安装Pytorch 省略(百度有很多相关的文章)
- 张量(tensor)
- 基于Pytorch的神经网络
- 通过序列方式构建一神经网络
- 保存及加载Pytorch模型
张量 Tensor
张量可以说是在深度学习里一个最基础的数据类型,不管哪个框架下都会对其有所介绍,这里就不过多记录。
A tensor is a multi-deimensional matrix similar to Numpy's ndarrays.
- 标量(scalar)可以看作是一个零维的张量
- 向量(vector)可以看作是一个一维张量
- 二维矩阵(two-dimensional matrix)可以看作是一个二维张量
- 多维矩阵(multi-dimensional matrix)可以看作是一个多维张量
如一张彩色图片可以看作是一个三维张量,图片总共有HW3个像素点,这里的3代表了RGB三个通道数。一张灰色图片可看作是一个二维张量,即H*W像素点。
张量初始化
有很多种初始化张量的方法,这里简单给出几种方式:
# torch直接生成
import torch
x = torch.tensor([[1, 2]])
y = torch.tensor([[1], [2]])
# 查看tensor大小或数据类型
print(x.shape)
print(x.dtype)
Pytorch也提供了很多跟Numpy的数据生成函数,如zeros, ones和随机数等,具体可查阅相关官方文档。
Numpy与Pytorch数据互换
# from numpy
import numpy as np
import torch
x = np.array([[10,20,30],[2,3,4]])
y = torch.tensor(x)
print(type(x), type(y))
# <class 'numpy.ndarray'> <class 'torch.Tensor'>
张量操作
【后面补充】
张量自动梯度计算
从前面的例子可以看出对模型中权重的更新梯度计算是十分重要的,所以Pytorch框架提供了一个灵活的自动梯度计算,为后面的深度学习中后向传播计算梯度提供了一个便捷的通道。
-
通过一个简单样例,看一下pytorch是如何计算梯度
image.png
import torch
# requires_grad 定义该张量是否要进行梯度计算
x = torch.tensor([[2., -1.], [1., 1.]], requires_grad=True)
print(x)
"""
tensor([[ 2., -1.],
[ 1., 1.]], requires_grad=True)
"""
# 梯度为 2*x
out = x.pow(2).sum()
# 调用 backward()进行梯度计算
out.backward()
x.grad
"""
tensor([[ 4., -2.],
[ 2., 2.]])
Notice that the gradients obtained previously match with the intuitive gradient
values (which are two times that of the value of x).
"""
Pytorch的tensor与Numpy的ndarray的优势
直接上图,其实最主要是就是可以借助GPU实现并行计算,从而提升运算速度。
基于Pytorch构建神经网络
从前面的例子中,我们知道一般的神经网络在构建过程中主要由以下几个考虑:
- 有几个隐藏层
- 各隐藏层有几个单元(神经元)
- 激活函数
- 损失函数
- 学习率初始化是多少
- 批数据是多少(训练数据是多少,批量 大小batch size)
- 模型训练期望训练多少轮(epoch)
前面的网络构建中,我们并没有提到batch size这个超参数,接下来通过pytorch里的几个内置包实现batch size的训练。
Batch size refers to the number of data points considered to calculate the loss value or update weights.
- Dataset
- DataLoader
在实际应用中,训练模型时都会用到batch size这个超参数,因为实际中我们的训练数据是非常多的,同时模型的参数也是万千上万的,因此在计算梯度时会占用很大的计算资源(内存等),所以一般操作都是会将训练数据分批进行训练更新参数,从而达到在有限的资源下实现模型训练。
用nn.Sequential()构建刚才的网络模型
Pytorch模型存储与加载
One of the important aspects of working on neural network models is to save and load back a model after training.
保存模型参数
torch.save(model.to('cpu').state_dict(), 'mymodel.pth')
A good practice is to transfer the model to the CPU before calling torch.save as this will save tensors as CPU tensors and not as CUDA tensors. This will help in loading the model onto any machine, whether it contains CUDA capabilities or not.
加载模型参数
Loading a model would require us to initialize the model with random weights first and then load the weights from state_dict
# 模型参数加载
# 首先需要构建模型网络结构
tmp_model = nn.Sequential(
nn.Linear(2, 8),
nn.ReLU(),
nn.Linear(8, 1)
).to(device)
state_dict = torch.load('mymodel.pth')
tmp_model.load_state_dict(state_dict)
# <All keys matched successfully> 表示数据加载成功