因为numpy是一个python numerical computing library, PyTorch 可以 interact with it nicely.
The two main methods you will want to use for NumPy to PyTorch (and back again) are:
torch.from_numpy(ndarray)
- NumPy array -> PyTorch tensortorch.Tensor.numpy()
- PyTorch tensor -> NumPy array
import numpy as np
array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(array)
print(tensor)
# 输出结果
[1. 2. 3. 4. 5. 6. 7.]
tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
这里稍微介绍一下:
By default, NumPy arrays are created with the datatype float64
and if you convert it to a PyTorch tensor, it’ll keep the same datatype.
However, many PyTorch calculations default to using float32
.
So if you want to convert your numpy array (float64) -> PyTorch tensor (float64) -> PyTorch tensor (float32), you can use tensor = torch.from_numpy(array).type(torch.float32)
下面是代码来展示,让tensor和numpy做两者之间的互相转换
import numpy as np
# Array to Tensor
array = np.arange(1.0, 8.0)
tensor = torch.from_numpy(array)
print(f"array: {array}")
print(f"tensor 1: {tensor}")
array = array + 1
print(f"array: {array}")
tensor = tensor + 1
print(f"tensor 2: {tensor}")
# Tensor to Numpy array
tensor = torch.ones(7)
print(f"tensor 3: {tensor}")
numpy_tensor = tensor.numpy()
print(f"numpy_tensor: {numpy_tensor} | numpy_tensor datatype: {numpy_tensor.dtype}")
# Change the tensor, keep the array the same
tensor = tensor + 1
print(f"tensor: {tensor}")
print(f"numpy_tensor: {numpy_tensor}")
# 结果如下
array: [1. 2. 3. 4. 5. 6. 7.]
tensor 1: tensor([1., 2., 3., 4., 5., 6., 7.], dtype=torch.float64)
array: [2. 3. 4. 5. 6. 7. 8.]
tensor 2: tensor([2., 3., 4., 5., 6., 7., 8.], dtype=torch.float64)
tensor 3: tensor([1., 1., 1., 1., 1., 1., 1.])
numpy_tensor: [1. 1. 1. 1. 1. 1. 1.] | numpy_tensor datatype: float32
看到这了,点个赞支持一下咯~