torch与numpy有不少相似之处,可看作gpu版本的numpy
代码
import numpy as np
import torch
1、创建
arange
print(np.arange(6))
print(torch.arange(6))
结果
[0 1 2 3 4 5]
tensor([0, 1, 2, 3, 4, 5])
2、形状
改变形状
a = np.arange(6).reshape(2, 3)
print(a.shape)
b = torch.arange(6).reshape(2, 3)
print(b.shape)
结果
(2, 3)
torch.Size([2, 3])
3、矩阵乘法
代码
print(a.dot(a.T))
print(np.matmul(a, a.T))
print(torch.mm(b, b.T))
结果
[[ 5 14]
[14 50]]
[[ 5 14]
[14 50]]
tensor([[ 5, 14],
[14, 50]])
4、转化
张量=>数组,数组=>张量
print(torch.from_numpy(a))
print(b.numpy())
结果
tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
[[0 1 2]
[3 4 5]]
5、向量运算
向量加、减和数乘。
a = np.arange(6).reshape(2, 3)
print(a + 10)
b = torch.arange(6).reshape(2, 3)
print(b + 10)
结果
[[10 11 12]
[13 14 15]]
tensor([[10, 11, 12],
[13, 14, 15]])
6、升维
增加维度
print(a[None].shape)
print(a[:, None].shape)
print(a[:, :, None].shape)
for i in range(3):
print(b.unsqueeze(i).shape)
结果
(1, 2, 3)
(2, 1, 3)
(2, 3, 1)
torch.Size([1, 2, 3])
torch.Size([2, 1, 3])
torch.Size([2, 3, 1])
7、降维
代码
a = np.arange(6).reshape(2, 3)
b = torch.arange(6).reshape(2, 3)
print(a[None].shape)
print(a[None].squeeze().shape)
print(a[:, None].shape)
print(a[:, None].squeeze(1).shape)
print(a[:, :, None].shape)
print(a[:, :, None].squeeze(2).shape)
for i in range(3):
print(b.unsqueeze(i).shape)
print(b.unsqueeze(i).squeeze(i).shape)
结果
(1, 2, 3)
(2, 3)
(2, 1, 3)
(2, 3)
(2, 3, 1)
(2, 3)
torch.Size([1, 2, 3])
torch.Size([2, 3])
torch.Size([2, 1, 3])
torch.Size([2, 3])
torch.Size([2, 3, 1])
torch.Size([2, 3])
8、随机数种子
生成相同的随机数
np.random.seed(1)
print(np.random.rand(1))
np.random.seed(1)
print(np.random.rand(1))
torch.manual_seed(1)
print(torch.rand(1))
torch.manual_seed(1)
print(torch.rand(1))
结果
[0.417022]
[0.417022]
tensor([0.7576])
tensor([0.7576])
9、正态分布随机数
常用分布随机数
print(np.random.randn(1))
print(torch.randn(1))
print(np.random.normal(0,1,[2]))
print(torch.normal(0,1,[2]))
结果
[-1.65451545]
tensor([0.1584])
[-2.3634686 1.13534535]
tensor([-0.6617, -0.0426])
10、随机整数
代码
print(np.random.randint(5,size=[2,3]))
print(torch.randint(5,size=[2,3]))
结果
[[2 4 3]
[4 2 4]]
tensor([[3, 3, 0],
[2, 1, 2]])
11、函数
向量版本的数学函数
print(np.sin([1,2,3]))
print(torch.sin(torch.Tensor([1,2,3])))
结果
[0.84147098 0.90929743 0.14112001]
tensor([0.8415, 0.9093, 0.1411])
12、求和
不同方向求和
a = np.arange(6).reshape(2,3)
print(a.sum(0))
print(a.sum(1))
print(a.sum())
b = torch.arange(6).reshape(2,3)
print(b.sum(0))
print(b.sum(1))
print(b.sum())
结果
[3 5 7]
[ 3 12]
15
tensor([3, 5, 7])
tensor([ 3, 12])
tensor(15)
13、点乘
对应元素相乘
a = np.arange(6).reshape(2,3)
print(a*a)
print(np.multiply(a,a))
b = torch.arange(6).reshape(2,3)
print(b*b)
print(torch.mul(b,b))
结果
[0.417022]
[0.417022]
tensor([0.7576])
tensor([0.7576])