创建size为[2,3]的浮点数张量:
x = torch.FloatTensor(2,3)
输出为tensor([[-5.6497e-27, 8.5619e-43, -5.6497e-27],
[ 8.5619e-43, -2.0937e-26, 8.5619e-43]])
创建数据为2,3的浮点数张量
x = torch.FloatTensor([2,3])
输出为tensor([2., 3.])
转换为整型张量
x = x.type_as(torch.IntTensor())
输出为tensor([2, 3], dtype=torch.int32)
GPU和CPU上的Tensor转换
>>> x = torch.FloatTensor([[1,2,3],[4,5,6]])
>>> print(x)
tensor([[1., 2., 3.],
[4., 5., 6.]])
将x移动到GPU上
>>> x_gpu = x.cuda()
>>> print(x_gpu)
tensor([[1., 2., 3.],
[4., 5., 6.]], device='cuda:0')
将x移动到CPU上
>>> x_cpu = x_gpu.cpu()
>>> print(x_cpu)
tensor([[1., 2., 3.],
[4., 5., 6.]])
tensor的形状
>>> x = torch.FloatTensor(10,12,3,3)
>>> print(x.size()[:])
torch.Size([10, 12, 3, 3])
torch.index_select(input, dim, index, out=None) → Tensor
函数作用:Returns a new tensor which indexes the input tensor along dimension dim using the entries in index which is a LongTensor.
The returned tensor has the same number of dimensions as the original tensor (input).
The dimth dimension has the same size as the length of index; other dimensions have the same size as in the original tensor.
The returned tensor does not use the same storage as the original tensor.
用法:
>>> x = torch.randn(3,4)
>>> x
tensor([[ 0.3221, -1.1750, -0.3818, 1.4253],
[ 0.9451, 0.8435, -2.3493, 0.0100],
[-1.7050, -1.1493, 0.5394, 0.7163]])
>>> indices = torch.tensor([0,2])
>>> torch.index_select(x,0,indices)
tensor([[ 0.3221, -1.1750, -0.3818, 1.4253],
[-1.7050, -1.1493, 0.5394, 0.7163]])
>>> torch.index_select(x, 1, indices)
tensor([[ 0.3221, -0.3818],
[ 0.9451, -2.3493],
[-1.7050, 0.5394]])
torch.masked_select(input, mask, out=None) → Tensor
函数作用:Returns a new 1-D tensor which indexes the input tensor according to the boolean mask mask w