阅读说明: 保留原笔记的编号与章节顺序;代码只供查看,没有在本站运行。历史输出不代表当前版本的复现结果。截图/外链图以独立整理的公式、表格、示意或文字替换;纠错与必要补充均作说明。
%matplotlib inline0. What is PyTorch?
It’s a Python-based scientific computing package targeted at two sets of audiences:
- A replacement for NumPy to use the power of GPUs
- A deep learning research platform that provides maximum flexibility and speed
1. Getting Started
Tensors are similar to NumPy’s ndarrays, with the addition being that Tensors can also be used on a GPU to accelerate computing.
from torch.autograd import Variable 已被废弃
直接:
x = torch.randn(N, D_in)# from __future__ import print_function
import torch
import numpy as npConstruct a 5x3 matrix, uninitialized:
x = torch.empty(5, 3)
print(x)tensor([[2.1619e-33, 6.4600e-43, 2.1619e-33],
[6.4600e-43, 2.1620e-33, 6.4600e-43],
[2.1620e-33, 6.4600e-43, 2.1618e-33],
[6.4600e-43, 2.1618e-33, 6.4600e-43],
[2.1616e-33, 6.4600e-43, 2.1616e-33]])
整理注: torch.empty为未初始化内存;打印的值没有数学含义,不可作为随机初始化。这里仅保留原输出,不在站点分配或读取未初始化内存。
Construct a randomly initialized matrix:
x = torch.rand(5, 3)
print(x)tensor([[0.3949, 0.2483, 0.7308],
[0.5197, 0.0942, 0.2607],
[0.0216, 0.9783, 0.0192],
[0.8772, 0.2504, 0.5289],
[0.5290, 0.3911, 0.1284]])
Construct a matrix filled zeros and of dtype long:
x = torch.zeros(5, 3, dtype=torch.long)
print(x)tensor([[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]])
Construct a tensor directly from data:
x = torch.tensor([5.5, 3])
print(x)tensor([5.5000, 3.0000])
or create a tensor based on an existing tensor. These methods will reuse properties of the input tensor, e.g. dtype, unless new values are provided by user
x = x.new_ones(5, 3, dtype=torch.double) # new_* methods take in sizes
print(x)tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
x = torch.randn_like(x, dtype=torch.float) # override dtype!
print(x) # result has the same sizetensor([[ 1.5208, -0.0597, -0.0905],
[-1.4642, -0.1585, 1.1798],
[-0.7855, 0.1995, 0.5058],
[ 1.1318, -0.8209, 0.6122],
[ 2.1100, -0.0974, 0.1178]])
Get its size:
print(x.size())torch.Size([5, 3])
x = torch.Tensor([1., 2., 3.])
print(x)
print(x.shape)
print(torch.ones(2, 1))
print(torch.zeros_like(x))tensor([1., 2., 3.])
torch.Size([3])
tensor([[1.],
[1.]])
tensor([0., 0., 0.])
y = np.array([0, 1, 2, 3])
print(y)
x = torch.from_numpy(y)
print(x)[0 1 2 3]
tensor([0, 1, 2, 3], dtype=torch.int32)
2. Data types in Pytorch and Casting
| dtype | 含义 | 常用别名 |
|---|---|---|
| float32 | 32位浮点 | torch.float |
| float64 | 64位浮点 | torch.double |
| uint8 | 8位无符号整数 | torch.uint8 |
| int8 | 8位有符号整数 | torch.int8 |
| int32 | 32位有符号整数 | torch.int |
| int64 | 64位有符号整数 | torch.long |
| bool | 布尔值 | torch.bool |
类型转换可能丢精度;旧式FloatTensor等类型构造器与device管理应区分。
A tensor can be cast to any data type, with possible loss of precision:
print(x.dtype)torch.int32
x = x.type(torch.FloatTensor)
print(x.dtype)torch.float32
print(x.float())
print(x.float().dtype)tensor([0., 1., 2., 3.])
torch.float32
print(x.type(torch.DoubleTensor))tensor([0., 1., 2., 3.], dtype=torch.float64)
print(x.type(torch.LongTensor))tensor([0, 1, 2, 3])
3. Tensor Arithmetic
Addition: syntax 1
x = torch.randn(5, 3, dtype=torch.float)
y = torch.rand(5, 3)
print(x + y)tensor([[-0.7963, 0.5517, -1.0351],
[ 0.5931, 0.3763, -0.5903],
[-0.2743, 0.6772, 0.4807],
[ 2.4802, 1.9205, 0.1098],
[ 1.3044, 2.1340, 0.6395]])
Addition: syntax 2
print(torch.add(x, y))tensor([[-0.7963, 0.5517, -1.0351],
[ 0.5931, 0.3763, -0.5903],
[-0.2743, 0.6772, 0.4807],
[ 2.4802, 1.9205, 0.1098],
[ 1.3044, 2.1340, 0.6395]])
Addition: providing an output tensor as argument
result = torch.empty(5, 3)
torch.add(x, y, out=result)
print(result)tensor([[-0.7963, 0.5517, -1.0351],
[ 0.5931, 0.3763, -0.5903],
[-0.2743, 0.6772, 0.4807],
[ 2.4802, 1.9205, 0.1098],
[ 1.3044, 2.1340, 0.6395]])
Addition: in-place
# adds x to y
y.add_(x)
print(y)tensor([[-0.7963, 0.5517, -1.0351],
[ 0.5931, 0.3763, -0.5903],
[-0.2743, 0.6772, 0.4807],
[ 2.4802, 1.9205, 0.1098],
[ 1.3044, 2.1340, 0.6395]])
Note
Any operation that mutates a tensor in-place is post-fixed with an _.
For example: x.copy_(y), x.t_(), will change x.
x = torch.randn(5, 3, dtype=torch.float)
y = torch.rand(5, 3)
print(x - y)tensor([[-0.3067, -1.9665, -0.9493],
[-0.5383, -1.5818, -1.5131],
[ 0.7852, -1.2541, -0.1374],
[ 0.0908, -2.7448, -0.9767],
[-0.5671, 0.2215, -1.6113]])
print(x.sub(y))tensor([[-0.3067, -1.9665, -0.9493],
[-0.5383, -1.5818, -1.5131],
[ 0.7852, -1.2541, -0.1374],
[ 0.0908, -2.7448, -0.9767],
[-0.5671, 0.2215, -1.6113]])
4. Matrix Multiplication vs. Element-wise Multiplication
x = torch.tensor([[1, 2, 3]])
y = torch.tensor([[2, 2, 2]])x.shapetorch.Size([1, 3])
x.t().shape # transposetorch.Size([3, 1])
y.shapetorch.Size([1, 3])
torch.mul(x, y)tensor([[2, 4, 6]])
x.t().mm(y)tensor([[2, 2, 2],
[4, 4, 4],
[6, 6, 6]])
x.mm(y.t())tensor([[12]])
torch.mm(x, y.t())tensor([[12]])
torch.matmul(x, y.t())tensor([[12]])
5. Other helpful transcendental functions
PyTorch support cos(), sin(), exp() just like Numpy.
np.pi3.141592653589793
torch.cos(torch.tensor(np.pi))tensor(-1.)
torch.sin(torch.tensor(np.pi/2))tensor(1.)
torch.exp(torch.tensor(1.))tensor(2.7183)
6. Logical Operations
x = torch.tensor([True, False, False])
y = torch.tensor([True, False, False])
x.shapetorch.Size([3])
y.dtypetorch.bool
x & ytensor([ True, False, False])
x | ytensor([ True, False, False])
x = torch.tensor([0, 1, 2])
y = torch.tensor([2, 3, 4])
(x > 1) & (y > 1)tensor([False, False, True])
7. More logical operations
torch.where(condition, input, other)looks at each index i of 3 input tensors. It will return input if condition true, else will return other:
x = torch.tensor([0, 1, 2])
y = torch.tensor([6, 5, 4])
torch.where((x > 0) & (x < 2), x, y)tensor([6, 1, 4])
Logical operations can be combined with tensor.nonzero() to retrueve relevant array indices. .nonzero() will return the indices of all non_zero elements of the input. It can be used much like np.argwhere(), in the following manner:
x = torch.tensor([0, 1, 3, 3])
x == 3tensor([False, False, True, True])
(x == 3).nonzero()tensor([[2],
[3]])
8. Sorting Operations
x = torch.tensor([3, 0, 1, 2])
torch.argsort(x)tensor([1, 2, 3, 0])
9. Combing Tensors
Tensors can be combined along any dimension, as long as the dimensions align properly. Concatenating(torch.cat()) or stacking(torch.stack()) tensors are considered different operations in PyTorch.
torch.stack() will combine a sequence of tensors along a new dimension, whereas torch.cat() will concatenates tensors along a default dimension dim=0.
x = torch.tensor([1, 2, 3])
y = torch.tensor([2, 2, 2])torch.stack([x, y])tensor([[1, 2, 3],
[2, 2, 2]])
torch.cat([x, y])tensor([1, 2, 3, 2, 2, 2])
x = torch.tensor([[1, 2], [3, 4]])
y = torch.tensor([[2, 2], [2, 2]])torch.stack([x, y])tensor([[[1, 2],
[3, 4]],
[[2, 2],
[2, 2]]])
torch.cat([x, y])tensor([[1, 2],
[3, 4],
[2, 2],
[2, 2]])
10. NumPy-like Indexing
x = torch.arange(4*3)
print(x)tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
x = x.reshape(3, 2, 2)
print(x)tensor([[[ 0, 1],
[ 2, 3]],
[[ 4, 5],
[ 6, 7]],
[[ 8, 9],
[10, 11]]])
x[0, :, :]tensor([[0, 1],
[2, 3]])
x[1, 1:, :]tensor([[6, 7]])
x[2, 0, 1]tensor(9)
Resizing: If you want to resize/reshape tensor, you can use torch.view:
x = torch.randn(4, 4)
y = x.view(16)
z = x.view(-1, 8) # the size -1 is inferred from other dimensions
print(x.size(), y.size(), z.size())torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
reshape() vs view()
- 相同之处
都可以用来重新调整 tensor 的形状。 - 不同之处
- view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。
如果对 tensor 调用过 transpose, permute 等操作的话会使该 tensor 在内存中变得不再连续,此时就不能再调用 view 函数。因此,需要先使用 contiguous 来返回一个 contiguous copy。 - reshape 则不需要依赖目标 tensor 是否在内存中是连续的。
- view 函数只能用于 contiguous 后的 tensor 上,也就是只能用于内存中连续存储的 tensor。
整理注: view是否可行取决于目标形状与stride兼容性,并非所有非连续张量都不可view;reshape可能返回视图,也可能复制。
If you have a one element tensor, use .item() to get the value as a
Python number
x = torch.randn(1)
print(x)
print(x.item())tensor([0.1756])
0.1756105273962021
11. NumPy Bridge
Converting a Torch Tensor to a NumPy array and vice versa is a breeze.
The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.
整理注: 共享内存依赖设备、dtype与转换方式;示例是兼容CPU张量。GPU转CPU等复制不保证共享。
- Converting Torch Tensor to NumPy Array
a = torch.ones(5)
print(a)tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)[1. 1. 1. 1. 1.]
See how the numpy array changed in value.
a.add_(1)
print(a)
print(b)tensor([2., 2., 2., 2., 2.])
[2. 2. 2. 2. 2.]
- Converting NumPy Array to Torch Tensor
See how changing the np array changed the Torch Tensor automatically
a = np.ones(5)
b = torch.from_numpy(a)
np.add(a, 1, out=a)
print(a)
print(b)[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
12. CUDA Tensors
Tensors can be moved onto any device using the .to method.
x = torch.tensor([[1,2,3]])
y = torch.tensor([[2,2,2]])# let us run this cell only if CUDA is available
# We will use ``torch.device`` objects to move tensors in and out of GPU
if torch.cuda.is_available():
device = torch.device("cuda") # a CUDA device object
y = torch.ones_like(x, device=device) # directly create a tensor on GPU
x = x.to(device) # or just use strings ``.to("cuda")``
z = x + y
print(z)
print(z.to("cpu", torch.double)) # ``.to`` can also change dtype together!tensor([[2, 3, 4]], device='cuda:0')
tensor([[2., 3., 4.]], dtype=torch.float64)
教程出处
本篇部分示例对应PyTorch入门教程,整理时保留章节与代码,修正说明已标注。原许可见PyTorch tutorials BSD-3-Clause。