赞
踩
在PyTorch中, torch.Tensor 是存储和变换数据的主要⼯工具,并且Tensor 和NumPy的多维数组⾮非常类似, Tensor 提供GPU计算和自动求梯度等功能。
"tensor"这个单词⼀一般可译作“张量量”,张量量可以看作是⼀一个多维数组。标量量可以看作是0维张量量,向
量量可以看作1维张量量,矩阵可以看作是⼆二维张量量。
在创建Tensor时,首先导入torch库
x = torch.empty(a, b)
x = torch.rand(a, b)
x = torch.zeros(a, b)
x = torch.tensor([a, b])
x = x.new_ones(a, b)
x = torch.randn_like(x)
x.size()
x.shape
x = torch.rand(5,3)
y = torch.rand(5,3)
z = x + y
z = torch.add(x, y)
y.add_(x)
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).使用函数
# 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]])
# 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])
# 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]])
# 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值均于加法示例中一致。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。