学习目标:
- 理解Pytorch 的 Tensor库,以及神经网络。
- 训练一个简单的图像分类网络。
假设已经了解numpy的基本用法,并确保已经安装好torch和torchvision。
什么是Pytorch
Pytorch是一个基于Python的科学计算包,用于以下两个目的:
- 代替NumPy,使用GPU的加速能力。
- 用于提供最大灵活性和速度的深度学习研究平台。
张量(Tensors)
张量与NumPy的数组类似,但是张量可以用在GPU上用来加速计算。
现在我们用Pytorch构造一个未经初始化的5×3的矩阵:
1
2
3
4 1x = torch.empty(5, 3)
2print(x)
3
4
结果:
1
2
3
4
5
6
7 1tensor([[0.0000e+00, 0.0000e+00, 0.0000e+00],
2 [0.0000e+00, 0.0000e+00, 0.0000e+00],
3 [0.0000e+00, 0.0000e+00, 0.0000e+00],
4 [0.0000e+00, 7.6231e-43, 0.0000e+00],
5 [0.0000e+00, 2.9966e+32, 0.0000e+00]])
6
7
构造一个随机初始化的矩阵:
1
2
3
4 1x = torch.rand(5, 3)
2print(x)
3
4
结果:
1
2
3
4
5
6
7 1tensor([[0.4140, 0.7152, 0.0888],
2 [0.6878, 0.9607, 0.2579],
3 [0.0088, 0.5816, 0.1782],
4 [0.3815, 0.6752, 0.9996],
5 [0.4057, 0.3032, 0.8977]])
6
7
用0初始化矩阵,并且数据类型为long:
1
2
3
4 1x = torch.zeros(5, 3, dtype=torch.long)
2print(x)
3
4
结果:
1
2
3
4
5
6
7 1tensor([[0, 0, 0],
2 [0, 0, 0],
3 [0, 0, 0],
4 [0, 0, 0],
5 [0, 0, 0]])
6
7
直接从数据中构造张量:
1
2
3
4 1x = torch.tensor([5.5, 3])
2print(x)
3
4
结果:
1
2
3 1tensor([5.5000, 3.0000])
2
3
从现有tensor构造另外一个tensor,这会重用输入tensor的一些属性,比如数据类型,除非用户指定另外的值。
1
2
3
4
5
6
7 1x = x.new_ones(5, 3, dtype=torch.double) # new_* 方法接收tensor大小参数
2print(x)
3
4x = torch.randn_like(x, dtype=torch.float) # 重载数据类型!
5print(x) # 结果有相同的大小
6
7
结果:
1
2
3
4
5
6
7
8
9
10
11
12 1tensor([[1., 1., 1.],
2 [1., 1., 1.],
3 [1., 1., 1.],
4 [1., 1., 1.],
5 [1., 1., 1.]], dtype=torch.float64)
6tensor([[ 0.6743, -0.3788, 0.7561],
7 [-0.7612, -1.6943, -1.2451],
8 [ 0.6169, -1.1207, -1.1664],
9 [ 0.4309, 1.3055, -0.0481],
10 [ 0.7891, -1.7696, 1.4875]])
11
12
获取tensor的大小:
1
2
3 1print(x.size())
2
3
结果:
1
2
3 1torch.Size([5, 3])
2
3
注意:torch.Size实际上是一个tuple,因此它支持所有的tuple操作。
操作(Operations)
操作有许多种语法,下面将展示操作的几种语法。
加法:语法一
1
2
3
4 1y = torch.rand(5, 3)
2print(x + y)
3
4
结果:
1
2
3
4
5
6
7 1tensor([[1.2953, 0.3779, 0.9404],
2 [0.8671, 0.5968, 0.7860],
3 [1.3698, 1.2983, 1.1537],
4 [0.3706, 0.6296, 0.7085],
5 [0.8819, 0.8260, 0.9962]])
6
7
加法:语法二
1
2
3 1print(torch.add(x, y))
2
3
结果:
1
2
3
4
5
6
7 1tensor([[1.2953, 0.3779, 0.9404],
2 [0.8671, 0.5968, 0.7860],
3 [1.3698, 1.2983, 1.1537],
4 [0.3706, 0.6296, 0.7085],
5 [0.8819, 0.8260, 0.9962]])
6
7
加法:将结果存入另外一个tensor
1
2
3
4
5 1result = torch.empty(5, 3)
2torch.add(x, y, out=result)
3print(result)
4
5
结果:
1
2
3
4
5
6
7 1tensor([[1.2953, 0.3779, 0.9404],
2 [0.8671, 0.5968, 0.7860],
3 [1.3698, 1.2983, 1.1537],
4 [0.3706, 0.6296, 0.7085],
5 [0.8819, 0.8260, 0.9962]])
6
7
加法:in-place(在被加数上加上加数,因此会改变被加数的值)
1
2
3
4
5 1# 把x加在y上
2y.add_(x)
3print(y)
4
5
结果:
1
2
3
4
5
6
7 1tensor([[1.2953, 0.3779, 0.9404],
2 [0.8671, 0.5968, 0.7860],
3 [1.3698, 1.2983, 1.1537],
4 [0.3706, 0.6296, 0.7085],
5 [0.8819, 0.8260, 0.9962]])
6
7
注意:任何带有下划线()的操作,都会改变tensor的值,比如x.copy(y), x.t_() 都会改变x的值。
在tensor上还可以尽情使用类似NumPy的索引方法:
1
2
3 1print(x[:, 1])
2
3
结果:
1
2
3 1tensor([0.1801, 0.1028, 0.7038, 0.3089, 0.1738])
2
3
使用torch.view来改变tensor大小:
1
2
3
4
5
6 1x = torch.randn(4, 4)
2y = x.view(16)
3z = x.view(-1, 8) # -1表示这个维度的数值通过其他维度推算而出
4print(x.size(), y.size(), z.size())
5
6
结果:
1
2
3 1torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
2
3
如果tensor中只有1个值,那么通过.item()可以取得:
1
2
3
4
5 1x = torch.randn(1)
2print(x)
3print(x.item())
4
5
结果:
1
2
3
4 1tensor([0.3665])
20.36647817492485046
3
4
对接NumPy
下面介绍Torch Tensor 和 NumPy之间如何相互转换。
Torch Tensor和NumPy会共享数据底层的内存存储位置,所以修改其中一个也会改变另外一个的值。
Torch Tensor转成NumPy数组:
1
2
3
4 1a = torch.ones(5)
2print(a)
3
4
结果:
1
2
3 1tensor([1., 1., 1., 1., 1.])
2
3
1
2
3
4 1b = a.numpy()
2print(b)
3
4
结果:
1
2
3 1[1. 1. 1. 1. 1.]
2
3
现在我们改变tensor中的值,看看NumPy数组中的值是什么:
1
2
3
4
5 1a.add_(1)
2print(a)
3print(b)
4
5
结果:
1
2
3
4 1tensor([2., 2., 2., 2., 2.])
2[2. 2. 2. 2. 2.]
3
4
从结果可以看出,在tensor上加上了1,由它转成的NumPy数组上的数值也随之修改了。
NumPy数组转Torch Tensor
和上面一样,由NumPy数组生成的Tensor,如果修改了数组的值,对应的Tensor也会随之修改:
1
2
3
4
5
6
7
8 1import numpy as np
2a = np.ones(5)
3b = torch.from_numpy(a)
4np.add(a, 1, out=a)
5print(a)
6print(b)
7
8
结果:
1
2
3
4 1[2. 2. 2. 2. 2.]
2tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
3
4
CPU上的Tensor,除类型为CharTensor之外,都能和NumPy互转。
CUDA Tensors
通过.to方法可以将tensor移到任何CUDA设备上:
1
2
3
4
5
6
7
8
9
10
11 1# 如果支持CUDA设备
2# 使用 ``torch.device`` 将tensor移入或移出GPU
3if torch.cuda.is_available():
4 device = torch.device("cuda") # CUDA设备对象
5 y = torch.ones_like(x, device=device) # 直接在GPU上创建
6 x = x.to(device) # 或者使用 ``.to("cuda")``将tensor放到GPU上
7 z = x + y
8 print(z)
9 print(z.to("cpu", torch.double)) # ``.to`` 也能同时修改数据类型!
10
11
结果:
1
2
3
4 1tensor([-0.7816], device='cuda:0')
2tensor([-0.7816], dtype=torch.float64)
3
4