PyTorch and NumPy: Converting Without Surprises
PyTorch and NumPy convert into each other cheaply. Use torch.from_numpy(arr) to get a tensor and tensor.numpy() to get an array. Both share the same memory when the tensor is on the CPU, which makes the conversion free but means changes to one show up in the other. Knowing this, plus two common errors, avoids most conversion problems.
NumPy array to tensor
import numpy as np
import torch
arr = np.array([[1.0, 2.0], [3.0, 4.0]])
t1 = torch.from_numpy(arr) # shares memory
t2 = torch.tensor(arr) # copies data
t3 = torch.as_tensor(arr) # shares if possible, else copies
arr[0, 0] = 99.0
print(t1[0, 0]) # tensor(99., dtype=torch.float64) <- changed
print(t2[0, 0]) # tensor(1., dtype=torch.float64) <- unchanged
from_numpy does not copy, so editing the array edits the tensor. torch.tensor always copies. Notice the dtype: NumPy defaults to float64, so the tensor is double precision too. Most models expect float32, so convert with .float() before feeding the tensor to a layer.
x = torch.from_numpy(arr).float() # float32 copy of the data
print(x.dtype) # torch.float32
Note that .float() makes a new tensor when the dtype changes, so that result no longer shares memory.
Tensor to NumPy array
t = torch.ones(3)
a = t.numpy() # shares memory with t
t.add_(1) # in-place change
print(a) # [2. 2. 2.]
The array reflects the in-place update because both point to the same buffer. If you want an independent array, copy it: t.numpy().copy() or t.clone().numpy().
The two classic errors
1. Can't call numpy() on a tensor that requires grad
w = torch.ones(3, requires_grad=True)
# w.numpy() # RuntimeError: Can't call numpy() on Tensor that requires grad.
arr = w.detach().numpy() # detach from the autograd graph first
print(arr)
NumPy knows nothing about gradients, so you must detach() the tensor to get a version without graph history. Model outputs also require grad, so you will write output.detach() often.
2. Can't convert a CUDA tensor to numpy
device = "cuda" if torch.cuda.is_available() else "cpu"
y = torch.rand(3, device=device)
# y.numpy() # TypeError on a GPU tensor
arr = y.detach().cpu().numpy() # the safe general recipe
print(arr)
NumPy only works with CPU memory. The safe chain for any model output is .detach().cpu().numpy(). It is a no-op for tensors that are already detached or on the CPU, so you can use it everywhere.
Using both libraries in a pipeline
A common pattern is to preprocess with NumPy or pandas, train in PyTorch, then analyse predictions back in NumPy.
import numpy as np
import torch
from torch import nn
X = np.random.rand(100, 4).astype("float32") # make float32 up front
model = nn.Linear(4, 1)
with torch.no_grad():
out = model(torch.from_numpy(X))
preds = out.squeeze(1).numpy() # no grad, CPU: direct conversion
print(preds.shape, preds.dtype) # (100,) float32
Creating the array as float32 avoids a conversion later. Inside torch.no_grad() the output does not require grad, so .numpy() works directly.
Memory and performance notes
Because from_numpy and .numpy() share memory, they are the fastest ways to cross between the libraries, and they scale to very large arrays without extra cost. Copying conversions such as torch.tensor(arr) take time and memory proportional to the data size, which matters when you convert inside a training loop. Convert once, outside the loop, whenever you can, and keep the data as tensors while it is being used by the model.
Moving a tensor from a GPU to the CPU is a synchronisation point: PyTorch must wait for all queued GPU work to finish before it can copy the data. Calling .cpu() or .item() on every step to log a value can therefore slow training noticeably. Log every few steps instead, or accumulate values on the device and transfer them once at the end of an epoch.
Datasets from images and files
Image libraries such as Pillow and OpenCV return NumPy arrays with the layout height, width, channels, usually with integer values from 0 to 255. Before a model can use them you must permute the axes to channels first, convert to float, and scale the values, for example by dividing by 255. The torchvision function ToTensor does exactly this for you, which is why you will see it at the start of most image pipelines. Doing it by hand once helps you understand what the transform hides.
Mixing functions
Many NumPy functions accept tensors on the CPU because tensors implement the array interface, but the result is a NumPy array and not a tensor, and a tensor with gradients will raise an error. Stick to explicit conversions at clear boundaries so you always know which library owns the data.
Cheat sheet
- NumPy to tensor, shared memory:
torch.from_numpy(arr). - NumPy to tensor, copy:
torch.tensor(arr). - Tensor to NumPy, shared:
t.numpy()(CPU, no grad only). - Anything to NumPy, safe:
t.detach().cpu().numpy(). - Convert
float64tofloat32before training. - Scalars:
t.item()for single-element tensors,t.tolist()for Python lists.
With tensors covered, you are ready for the feature that makes PyTorch a deep learning framework: autograd.
Comments
No comments yet. Have a question or a tip? Be the first to share it.