PyTotch之Tensor数据类型介绍
Tonsor数据类型基础介绍
在PyTorch中, torch.Tensor 是存储和变换数据的主要⼯工具,并且Tensor 和NumPy的多维数组⾮非常类似, Tensor 提供GPU计算和自动求梯度等功能。
"tensor"这个单词⼀一般可译作“张量量”,张量量可以看作是⼀一个多维数组。标量量可以看作是0维张量量,向
量量可以看作1维张量量,矩阵可以看作是⼆二维张量量。
创建Tensor
在创建Tensor时,首先导入torch库
- 创建一个a x b的未初始化的Tensor
x = torch.empty(a, b)
- 创建一个a x b的随机初始化的Tensor
x = torch.rand(a, b)
- 创建一个a x b的全0型Tensor
x = torch.zeros(a, b)
- 根据数据([a, b])创建
x = torch.tensor([a, b])
- 创建一个a x b的全1的Tensor
x = x.new_ones(a, b)
- 创建根据指定类型的随机初始化的Tensor
x = torch.randn_like(x)
输出Tensor的shape
x.size()
x.shape
Tensor的算术操作
1. 加法运算
- 加法一:
x = torch.rand(5,3)
y = torch.rand(5,3)
z = x + y
- 加法二:
z = torch.add(x, y)
- 加法三:
y.add_(x)
2.索引
A).类似NumPy的索引操作。
注意:索引出来的结果与原数据共享内存,也即修改一个,另一个会跟着修改
import torch
x = torch.empty(3, 5)
y = torch.rand(3, 5)
z = x[0, :]
z1 += 1 # 源Tensor也被更改了
输出:
print(x)
tensor([[1.9005e-19, 4.6246e+19, 1.7163e+25, 1.1866e+27, 4.8263e+19],
[6.4072e+02, 2.8573e+32, 1.5793e-19, 2.1727e+35, 1.8971e+31],
[1.0803e-32, 1.3563e-19, 1.3563e-19, 2.7256e+20, 1.8524e+28]])
print(y)
tensor([[0.6262, 0.4501, 0.3295, 0.5330, 0.7711],
[0.9652, 0.9371, 0.3598, 0.4364, 0.5721],
[0.9199, 0.3670, 0.6096, 0.5397, 0.9333]])
print(z)
tensor([1.0000e+00, 4.6246e+19, 1.7163e+25, 1.1866e+27, 4.8263e+19])
print(z1)
tensor([1.0000e+00, 4.6246e+19, 1.7163e+25, 1.1866e+27, 4.8263e+19])
B).使用函数
- index_select(input, dim, index)
在指定维度dim上选取,比如选取某行、某列
# input:
z = torch.index_select(x, 1, torch.tensor([0, 2]))
# output
print(z)
tensor([[8.4490e-39, 1.0194e-38],
[9.6429e-39, 9.6429e-39],
[9.0919e-39, 9.2755e-39]])
- masked_select(input, mask)
# input
mask = x.ge(0.5)
z = torch.masked_select(x, mask)
# output
print(mask)
tensor([[False, True, True, True, False],
[ True, True, False, False, True],
[False, True, True, True, True]])
print(z)
tensor([1.7444e+28, 7.3909e+22, 1.8727e+31, 4.6168e+24, 4.2964e+24, 7.1345e+31,
1.7444e+28, 7.3909e+22, 1.8727e+31, 1.3179e+25])
- nonzero(input)
非0的下标
# input
z = torch.nonzero(x)
# output
print(z)
tensor([[0, 0],
[0, 1],
[0, 2],
[0, 3],
[0, 4],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 0],
[2, 1],
[2, 2],
[2, 3],
[2, 4]])
- gather(input, dim ,index)
根据index,在dim维度上选取数据,输出的size与index一样
# input
z = torch.gather(x,1,torch.LongTensor([[0,0],[1,0]]))
# output
print(z)
tensor([[2.3869e-12, 2.3869e-12],
[2.3869e-12, 5.7033e-43]])
Tips:x值均于加法示例中一致。