PyTorch 官方教程 Getting Started 第一部分 Deep Learning with PyTorch: A 60 Minute Blitz 笔记
文章目录
1. What is PyTorch?
PyTorch 是基于 Python 的科学计算包,目的有两个:
- 神经网络上的NumPy.
- 敏捷高效的深度学习框架.
PyTorch是Torch在Python上的移植,Torch是基于Lua语言的的深度学习框架。因此,PyTorch继承了Torch灵活的动态图特性,与Python语言简洁的语法特性。基于这两个特性,PyTorch可以轻松地与NumPy交互。NumPy将array放入CPU加速计算,PyTorch将Tensor放入GPU加速计算
PyTorch 和 TensorFlow 类似,使用 Tensor 组织数据。Tensor(张量) 和 NumPy 的 ndarray(多维数组) 相似 。
torch package 包含基于高维张量的数据结构和计算它们的操作方式,默认使用 CPU 计算。它们也有 CUDA 版本,可以使用 GPU 计算。
from __future__ import print_function
import torch
创建未初始化的 5x3 矩阵:
x = torch.empty(5, 3)
print(x)
Out:
tensor([[4.1371e-07, 4.5822e-41, 6.7807e-06],
[4.5822e-41, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00],
[0.0000e+00, 0.0000e+00, 0.0000e+00]])
创建随机初始化的矩阵:
x = torch.rand(5, 3)
print(x)
Out:
tensor([[0.3814, 0.6408, 0.5860],
[0.4887, 0.5330, 0.8477],
[0.5300, 0.5962, 0.5901],
[0.3305, 0.5589, 0.7821],
[0.4265, 0.6637, 0.2600]])
创建0矩阵初始化的矩阵,数据类型为长整型:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)
Out:
tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
创建矩阵,从 Python 数据结构获得数据:
x = torch.tensor([5.5, 3])
print(x)
Out:
tensor([5.5000, 3.0000])
上面所创建x
是一个torch.Tensor
。它就是高维张量,其每一个元素的数据类型都相同。
Torch 定义了8位CPU张量类型和8位GPU张量类型。点击这里。
print(type(x))
Out
<class 'torch.Tensor'>
每个torch.Tensor
都有它的torch.dtype
、torch.device
和torch.layout
,这些都是它的属性(Tensor Attributes)
2. Autograd: Automatic Differentiation
Autograd: Automatic Differentiation
与TensorFlow的静态图方式不同,PyTorch使用动态图的方式计算梯度反向传播。
PyTorch的动态图特性依赖其自动微分机制(Autograd mechanics)。动微分机制(Autograd mechanics)具体由torch.autograd
包实现。
将torch.Tensor
的.requires_grad
属性设置为True
,将开始跟踪在这个tensor上的所有operations。当完成对这个tensor的所有operatio后,调用.backward()
,自动计算它的所有梯度,它的梯度值积累保存在.grad
属性里。
调用.detach()
停止追踪计算历史。
将代码块包裹在with torch.no_grad():
内,可以强制停止追踪计算历史,即使代码块内的tensor的requires_grad=True
。
torch.autograd.Function
类对自动微分机制(Autograd mechanics)非常重要。
Tensor
和Function
是相互连接的,共同建立一个无环的计算图。每个tensor都有一个.grad_fn
属性,关联到创建这个Tensor
的Function
上。如果这个Tensor
不是由Function
创建的,而是由用户创建的,则它的grad_fn = None
。
数学上,如果有一个向量值函数
,
对每个
的梯度组成一个雅克比矩阵(Jacobian matrix):
一般地,torch.autograd
是计算雅克比矩阵-向量内积的引擎。也就是说,给定任意向量
,计算内积
。当
是标量函数
的梯度时,也就是,
,那么,根据链式法则,雅克比矩阵-向量内积就是
对
的梯度:
3. Neural Networks
建立神经网络系统需要使用torch.nn
包。
nn
依赖于autograd
去定义一个网络模型并计算微分。nn.Module
包含各类网络层,和forward(input)
方法计算网络的output
。
4. Training a Classifier
torchvision
包特别为视觉任务开发。它具有数据加载模块可以便捷使用许多公共数据集,例如:Imagenet,CIFAR10,MNIST等,并将数据转换为images,viz,torchvision.datasets
和torch.utils.data.DataLoader
。
使用GPU训练
目前为止,都是在使用CPU运行神经网络,因为默认使用的是CPU。要想在GPU上运行神经网络,需要将网络模型转换为GPU版本,就像将tensor从CPU转为GPU一样。
首先,定义device为cuda设备(如果GPU可用)。
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Assuming that we are on a CUDA machine, this should print a CUDA device:
print(device)
Out
cuda:0
这些方法将递归地将所有模块的变量和缓存转换为 CUDA tensor。
net.to(device)
输入网络的数据和标签页要转换到GPU下。
inputs, labels = inputs.to(device), labels.to(device)
5. Optional: Data Parallelism
在多GPU上并行计算神经网络需要使用DataParallel
:
model = nn.DataParallel(model)
device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")