转载自:https://www.jb51.net/article/177575.htm,做简要记录
1、tensor与numpy数组:
# tensor转numpy
tensor.numpy()
# numpy转tensor
torch.from_numpy()
2、tensor与list:
# tensor转list
tensor.tolist()
# list转tensor
torch.tensor()
3、tensor类型转换
tensor = torch.Tensor(3, 5)
# torch.long() 将tensor投射为long类型
newtensor = tensor.long()
# torch.half()将tensor投射为半精度浮点类型
newtensor = tensor.half()
# torch.int()将该tensor投射为int类型
newtensor = tensor.int()
# torch.double()将该tensor投射为double类型
newtensor = tensor.double()
# torch.float()将该tensor投射为float类型
newtensor = tensor.float()
# torch.char()将该tensor投射为char类型
newtensor = tensor.char()
# torch.byte()将该tensor投射为byte类型
newtensor = tensor.byte()
# torch.short()将该tensor投射为short类型
newtensor = tensor.short()
4、type_as() 将张量转换成指定类型张量,需要赋值,type_as不会改变调用它的tensor
>>> a=torch.Tensor(2,5)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30], [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])
>>> b=torch.IntTensor(1,2)
>>> a.type_as(b)
tensor([[ 0, -2147483648, 0, 0, -2147483648], [-2147483648, -2147483648, 0, -2147483648, -2147483648]], dtype=torch.int32)
>>> a
tensor([[1.9431e-19, 4.8613e+30, 1.4603e-19, 2.0704e-19, 4.7429e+30], [1.6530e+19, 1.8254e+31, 1.4607e-19, 6.8801e+16, 1.8370e+25]])