Pytorch study notes-summary of data type conversion

1. Interconversion between Tensor and Numpy

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

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

2. Mutual conversion between Tensor and list

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

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

3. Common data type conversion between Tensor and 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() converts the tensor into a tensor of the specified type

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

Guess you like

Origin blog.csdn.net/m0_45388819/article/details/109429653