Pytorch学习笔记——数据类型转换总结

1.Tensor与Numpy之间的相互转化

tensor转numpy
a = torch.ones([2,5])
b = a.numpy()

numpy转tensor
a = np.ones([2,5])
b = torch.from_numpy(a)

2.Tensor与list之间的相互转化

tensor转list
a = torch.ones([1,5])
b = a.tolist()

list转tensor
a = list(range(1,6))
b = torch.tensor(a)

3.Tensor与Tensor之间常见数据类型转化

tensor所有的数据类型:
torch.FloatTensor:32位浮点型
torch.DoubleTensor:64位浮点型
torch.ShortTensor:16位整型
torch.IntTensor:32位整型
torch.LongTensor:64位整型

a = torch.tensor(3.1415)
int_t = a.int()
short_t = a.short()
long_t = a.long()

double_t = a.double()

char_t = a.char()
byte_t = a.byte()

4.type_as()将张量转换成指定类型的张量

a = torch.Tensor(2,5)
b = torch.IntTensor(1,2)
a.type_as(b)

猜你喜欢

转载自blog.csdn.net/m0_45388819/article/details/109429653