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とリスト間の相互変換

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