numpy->torch
torch_data = torch.from_numpy(np_data)
torch->numpy
np_data = torch_data.numpy()
实例:
import torch
import numpy as np
np_data = np.arange(6).reshape((2, 3))
torch_data = torch.from_numpy(np_data)
np_data_2 = torch_data.numpy()
print("np_data:\n", np_data)
print("torch_data:\n", torch_data)
print("np_data_2:\n", np_data_2)
运行结果:
np_data:
[[0 1 2]
[3 4 5]]
torch_data:
tensor([[0, 1, 2],
[3, 4, 5]], dtype=torch.int32)
np_data_2:
[[0 1 2]
[3 4 5]]