Pytorch數據類型轉換
載入模塊生成數據
import torch
import numpy as np
a_numpy = np.array([1,2,3])
Numpy轉換為Tensor
a_tensor = torch.from_numpy(a_numpy)
print(a_tensor)
Tensor轉換為Numpy
a_numpy = a_tensor.numpy()
print(a_numpy)
Int, float 轉換為tensor
c = torch.tensor(2)
print(c)
tensor 轉換為int
c = c.item()
print(c)
Numpy轉換為Variable
a_variable = Variable(torch.from_numpy(a_numpy))
print(a_variable)
Variable轉換為Numpy
a_numpy = a_variable.data.numpy()
print(a_numpy)