Interoperate with NumPy
Use a CPU tensor as input to NumPy-based analysis or visualization code.
PyTorch · Module
Converts a tensor to a NumPy ndarray. By default, conversion requires a CPU tensor with no gradients or unresolved conjugate bit and a NumPy-compatible dtype and layout; force=True permits preparation steps and possible copying.
Tensor.numpy() exposes a tensor as a NumPy array when the default constraints are satisfied. With force=True, it detaches the tensor, moves it to CPU, resolves conjugate and negative views, and then performs the conversion; this may require a copy.
Tensor.numpy(*, force=False) → numpy.ndarray| Name | Type | Description |
|---|---|---|
force | bool | When true, the returned ndarray may be a copy instead of always sharing memory; defaults to false. |
numpy.ndarray
force=True can produce an array that does not share storage, especially for non-CPU or flagged tensors.import torch
x = torch.tensor([1.0, 2.0, 3.0])
a = x.numpy()
a[0] = 9.0
print(x) # tensor([9., 2., 3.])Creates a CPU tensor, converts it to an ndarray, and demonstrates that both objects observe the same storage.
Use a CPU tensor as input to NumPy-based analysis or visualization code.
Inspect or edit CPU tensor data through an ndarray without allocating another buffer.
Convert tensors that require gradients or reside on an accelerator after explicitly detaching and moving them.
Tensor.numpy() return, and when does the default conversion work?It returns the tensor as a NumPy ndarray. By default, conversion is allowed only for a CPU tensor that does not require gradients, has no conjugate bit, and uses a NumPy-supported dtype and layout.
Follow-up: What does force=True change? It applies detach, CPU transfer, conjugate resolution, and negative-bit resolution before conversion, so the result may be a copy.
When conversion succeeds under the default rules, the ndarray and tensor share storage. Therefore, modifying one is visible through the other.
Follow-up: Can storage sharing be assumed with force=True? No. The documentation says the result may be a copy when the tensor is not on CPU or has conjugate or negative bits.
force argument affect conversion?force=True is shorthand for t.detach().cpu().resolve_conj().resolve_neg().numpy(). It is useful when the tensor does not meet the default conversion requirements, but sharing is not guaranteed.
Follow-up: Why might a caller prefer the default? It preserves the stricter zero-copy conditions and exposes unsupported situations instead of silently permitting a copy.
torch.from_numpytorch.as_tensortorch.Tensor.detachtorch.Tensor.cputorch.Tensor.resolve_conjtorch.Tensor.resolve_neg