张量是pytorch的基本数据类型,因此有必要重新快速的学习下怎么使用操作张量。
1:使用tensor直接创建
结果输出是:
tensor([[11, 22, 33, 66],
[77, 44, 88, 99]])
tensor([11, 22, 33, 66, 77, 44, 88, 99])
2:从numpy中导入
输出结果是:
[2. 5.5]
tensor([2.0000, 5.5000], dtype=torch.float64)
[[2. 5.5]
[1. 3. ]]
tensor([[2.0000, 5.5000],
[1.0000, 3.0000]], dtype=torch.float64)
3:从一些分布函数中得到
结果输出是:
tensor([[-0.1965, -1.2576, 0.9081],
[ 0.2345, 1.3528, 1.5679],
[-1.2760, -0.9808, 0.5914]])
tensor([[0.6441, 0.5676, 0.7393],
[0.0952, 0.9967, 0.8745],
[0.1752, 0.0379, 0.0169]])
tensor([[0.7620, 0.1802, 0.1150],
[0.5347, 0.6680, 0.5420],
[0.3381, 0.3097, 0.4028]])
tensor([[2, 8, 3],
[9, 1, 9],
[7, 4, 4]])
4:同一个数值
结果是:
tensor([[7, 7, 7],
[7, 7, 7]])
5:在一定范围带有步长的值
结果是:
tensor([0, 2, 4, 6, 8])
tensor([ 0.0000, 2.5000, 5.0000, 7.5000, 10.0000])
6:全0,全1,对角阵
结果是:
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]])
tensor([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
tensor([[1., 0., 0.],
[0., 1., 0.],
[0., 0., 1.]])
7:对张量进行下标选择,其中… 表示所有
结果是:
torch.Size([5, 3, 28, 28])
torch.Size([5, 3, 14, 14])
torch.Size([5, 3, 8, 28])
torch.Size([5, 3, 28, 14])
torch.Size([3, 3, 28, 14])
8:改变张量的维度信息
结果是:
torch.Size([5, 3, 4, 4])
torch.Size([240])
torch.Size([5, 48])
torch.Size([5, 3, 16])
torch.Size([5, 12, 4])
9:张量乘法和加法
结果是:
tensor([[1., 2., 3.],
[6., 5., 4.]])
tensor([[4., 1., 3.],
[9., 7., 2.]])
tensor([[ 5., 3., 6.],
[15., 12., 6.]])
tensor([[ 5., 3., 6.],
[15., 12., 6.]])
tensor([[15., 29.],
[41., 97.]])
类似可以得到类似的Div和Sub函数的操作。
10:聚合运算
Max/min:沿行/列取最大/最小值,dim=0表示列,dim=1表示行。返回值和索引。
Sum:沿行/列取求和,dim=0表示列,dim=1表示行
结果是
torch.Size([2, 3])
tensor([1., 2., 3.])
tensor([0, 0, 0])
tensor([3., 6.])
tensor([2, 0])
tensor([7., 7., 7.])
tensor([ 6., 15.])
11:张量的操作函数
1):cat。功能:将张量按维度dim进行拼接
• tensors: 张量序列 • dim : 要拼接的维度
结果是:
torch.Size([4, 3, 3, 2])
torch.Size([2, 6, 3, 2])
torch.Size([2, 3, 6, 2])
torch.Size([2, 3, 3, 4])
2):chunk。 功能:将张量按维度dim进行平均切分
返回值:张量列表
注意事项:若不能整除,最后一份张量小于 其他张量
• input: 要切分的张量
• chunks : 要切分的份数,向上取整
• dim : 要切分的维度
结果是:
第1个张量 shape is torch.Size([2, 3])
第2个张量 shape is torch.Size([2, 3])
第3个张量 shape is torch.Size([2, 1])
3):split。功能:将张量按维度dim进行切分,和chunk类似
返回值:张量列表
• tensor: 要切分的张量
• split_size_or_sections : 为int时,表示 每一份的长度;为list时,按list元素切分
• dim : 要切分的维度
结果是:
第1个张量:shape is torch.Size([2, 2])
第2个张量:shape is torch.Size([2, 2])
第3个张量:shape is torch.Size([2, 1])