How to Unify Data Types When Converting NumPy Arrays to PyTorch Tensors

Learn how to handle dtype mismatches when converting NumPy arrays to PyTorch tensors by casting to float32 before conversion.

x = np.random.rand(5)
print(x)
torch_x = torch.tensor(x)
print(torch_x)
[0.07875406 0.96178392 0.64953209 0.12122955 0.92958997]
tensor([0.0788, 0.9618, 0.6495, 0.1212, 0.9296], dtype=torch.float64)

When a NumPy array is directly converted to a PyTorch tensor, the original dtype is preserved.

torch_x = torch.tensor(x.astype(np.float32))
print(torch_x)
tensor([0.0788, 0.9618, 0.6495, 0.1212, 0.9296])

To explicitly control the dtype, convert the NumPy array to float32 before creating the PyTorch tensor.