本文主要讲解张量的定义,以及如何使用 PyTorch 完成张量的加、减、乘、除、切片和重塑等操作,以及如何将变量定义到GPU中。
张量生成一、张量的创建
1.torch.empty2.torch.rand3.torch.zerosones4.x.dtype5.torch.tensor6.requires_grad 二、张量的四则运算
1.张量的加法2.张量的减法3.张量的乘法4.张量的除法 三、张量的切片四、张量的重塑五、NumPy 与 Tensor
1.Tensor2NumPy2.NumPy2Tensor 六、GPU 上创建张量
1.在GPU上直接创建张量2.将变量放到GPU上进行运算
import torch一、张量的创建
1.torch.empty
利用torch.empty()初始化指定的张量大小,如果不指定值的话,内容为随机值。传入的参数为想创建的张量大小。
x.size()可以查看某个张量的大小
x=torch.empty(1) #scalar,大小为1*1的张量 print(x.size()) x=torch.empty(3) #vector,1D,大小为1*3的张量 print(x.size()) x=torch.empty(2,3) #matrix,2D,大小为2*3的张量 print(x.size()) x=torch.empty(2,2,3) #tensor,3D,大小为2*2*3的张量 print(x.size())
输出结果如下:
torch.Size([1]) torch.Size([3]) torch.Size([2, 3]) torch.Size([2, 2, 3])
2.torch.rand
随机初始化值在0-1之间的张量(服从均匀分布),可以使用torch.rand(size)。
torch.rand(5,3)#初始化5*3大小的0-1之间的张量
输出结果如下:
tensor([[0.7578, 0.4057, 0.2106],
[0.1077, 0.9233, 0.4721],
[0.4090, 0.6145, 0.4688],
[0.0066, 0.2052, 0.0865],
[0.0403, 0.0515, 0.3843]])
3.torch.zerosones
初始化全为 1 或者全为 0 的张量,可以使用 torch.zeros(size) 和torch.ones(size):
x=torch.zeros(5,3) y=torch.ones(5,3) print(x) print(y)
输出结果如下:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
4.x.dtype
x.dtype可以查看x中值的具体类型,也可以在初始化的时候传入指定的数据类型。
x=torch.zeros(5,3,dtype=torch.float16) print(x) print(x.dtype)
输出结果如下:
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]], dtype=torch.float16)
torch.float16
5.torch.tensor
创建指定值的张量,我们可以使用 torch.tensor(list),list 可以为 NumPy 中的一个列表。
x=torch.tensor([5.5,3.0]) print(x) print(x.size()) print(x.dtype)
输出结果如下:
tensor([5.5000, 3.0000]) torch.Size([2]) torch.float32
6.requires_grad
如果想要定义的张量能够自动计算梯度,那么我们就需要将参数 requires_grad 置为 True。
torch.tensor([5.5,3.0],requires_grad=True)
输出结果如下:
tensor([5.5000, 3.0000], requires_grad=True)
二、张量的四则运算 1.张量的加法
y=torch.rand(2,2) x=torch.rand(2,2) z=x+y print(x) print(y) print(z)
输出结果如下:
tensor([[0.2612, 0.2316],
[0.3099, 0.8368]])
tensor([[0.5535, 0.4303],
[0.2704, 0.3087]])
tensor([[0.8147, 0.6619],
[0.5804, 1.1455]])
2.张量的减法
使用 - 或者 .sub 都可以表示张量减法。
z=x-y print(z) z=torch.sub(x,y) print(z)
输出结果如下:
tensor([[-0.2922, -0.1986],
[ 0.0395, 0.5280]])
tensor([[-0.2922, -0.1986],
[ 0.0395, 0.5280]])
3.张量的乘法
张量乘法(利用 * 或者 torch.mul表示):
z=x*y print(z) z=torch.mul(x,y) print(z)
输出结果如下:
tensor([[0.1446, 0.0997],
[0.0838, 0.2584]])
tensor([[0.1446, 0.0997],
[0.0838, 0.2584]])
4.张量的除法
张量除法(使用 / 或者 torch.div 表示):
z=x/y print(z) z=torch.div(x,y) print(z)
三、张量的切片
和 NumPy 的切片类似,如下:
x=torch.rand(5,3) print(x) print(x[1,1])# 第一个值表示第一维(即行号),第二个值表示第二维(即列号) print(x[:,0])# 所有的行中的第 1 列 print(x[1,:])# 第 2 行中所有的列
输出结果如下:
tensor([[0.5549, 0.4097, 0.4717],
[0.9115, 0.7156, 0.3842],
[0.8097, 0.1971, 0.0908],
[0.6428, 0.7458, 0.0578],
[0.1143, 0.2395, 0.0955]])
tensor(0.7156)
tensor([0.5549, 0.9115, 0.8097, 0.6428, 0.1143])
tensor([0.9115, 0.7156, 0.3842])
四、张量的重塑
重塑的意思就是将原张量的形状进行变换,即元素总个数不变的情况下改变行数和列数,使用 torch.view(size) 类似于 numpy.reshape。
x=torch.rand(4,4) y=x.view(16)#指定改变后的大小 z=x.view(2,8) print(x.size(), y.size(), z.size())
输出结果如下:
torch.Size([4, 4]) torch.Size([16]) torch.Size([2, 8])
当
x
x
x 的大小为 12×23×32 ,而我们想把
x
x
x 转为
2
×
m
2×m
2×m 的大小时,我们就必须手动算出 12×23×32 的值,然后除以 2,进而得到
m
m
m 的值。
为了避免这种情况,我们可以将
m
m
m所在位置赋为 -1。计算机看到 -1 时,会自动使用 12×23×32÷2 的值来替换 -1:
x = torch.randn(12, 23, 32) y = x.view(2, -1) # 将需要计算的那个维度直接用 -1 表示 12*23*32/2 的值 x.size(), y.size() #注意:一次切片中只能有一个位置值 -1 。
输出结果如下:
(torch.Size([12, 23, 32]), torch.Size([2, 4416]))
五、NumPy 与 Tensor 1.Tensor2NumPy
可以使用 tensor.numpy()将 Tensor 类型的变量转为 NumPy类型:
a=torch.ones(5) print(a) b=a.numpy() print(b) print(type(b))
输出结果如下:
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
2.NumPy2Tensor
可以使用 torch.from_numpy() 将 NumPy 类型的变量转为 Tensor:
import numpy as np a=np.ones(5) b=torch.from_numpy(a) print(a) print(b)
输出结果如下:
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
六、GPU 上创建张量
默认情况下,所有的张量都是在 CPU 上创建的,但是你也可以使用 GPU 创建它,或者将 CPU 创建的向量移动到 GPU 中。
我们可以通过 torch.cuda.is_available() 命令,查看本地环境时候支持 GPU (True 表示支持 False 表示不支持):
torch.cuda.is_available()
输出结果如下:
True
1.在GPU上直接创建张量
device = torch.device("cuda")
y = torch.ones_like(x, device=device) # 在 GPU 上直接创建张量
z = torch.zeros_like(x, device=device)
print(x)
print(y)
print(z)
输出结果如下:
tensor([[ 0.4948, -1.2999, 0.5415, 1.1467],
[-2.5609, 1.6418, -0.0849, 0.9079],
[-1.1307, -1.0002, -1.7547, -0.2796],
[-1.3649, -0.1008, -2.2295, 1.1563]], device='cuda:0')
tensor([[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.],
[1., 1., 1., 1.]], device='cuda:0')
tensor([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]], device='cuda:0')
2.将变量放到GPU上进行运算
x = torch.randn(4, 4)
device = torch.device("cuda")
x = x.to(device) # 将张量移动到 GPU
print(x)
输出结果如下:
tensor([[ 0.4948, -1.2999, 0.5415, 1.1467],
[-2.5609, 1.6418, -0.0849, 0.9079],
[-1.1307, -1.0002, -1.7547, -0.2796],
[-1.3649, -0.1008, -2.2295, 1.1563]], device='cuda:0')



