MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

PyTorch Lab – 3 – Pytorch Conversions Between PyTorch And NumPy

This lab shows how to convert data between PyTorch tensors and NumPy arrays using tensor.numpy(), torch.from_numpy(), torch.as_tensor() and torch.tensor(). The main point is memory: the first three can share one buffer, so a change on one side shows up on the other, while torch.tensor() always makes a copy. The sections below the notebook explain those rules, then cover GPU tensors, autograd tensors, dtype problems and the errors you are most likely to see.


Which conversions share memory

The notebook above shows four ways to convert data. They look alike but behave differently. Some return a view of the same memory, so a change on one side shows up on the other. Others make an independent copy. Choosing the wrong one causes bugs that are hard to trace, such as a training batch changing after you have already logged it.

CallDirectionShares memory?Notes
t.numpy()Tensor to NumPyYes (CPU only)Fails on CUDA tensors and on tensors with requires_grad=True
torch.from_numpy(a)NumPy to TensorAlwaysKeeps the NumPy dtype. Fails on arrays with negative strides
torch.as_tensor(a)NumPy or list to TensorOnly if no dtype or device change is neededCopies when you pass a different dtype or device
torch.tensor(a)Anything to TensorNeverAlways copies and returns a new leaf tensor
np.asarray(t)Tensor to NumPyYes (CPU, no grad)Behaves like t.numpy()

Note: Memory stays shared only through in-place operations such as a[0] = 1, t.add_(1) or a += 1. A line like t = t + 1 creates a new tensor, and after that the two objects are no longer linked.

Prerequisites

  • A Python 3 version supported by your PyTorch release. The notebook metadata shows Python 3.7, which current PyTorch releases no longer support.
  • PyTorch and NumPy installed in the same environment, for example with pip install torch numpy.
  • Jupyter is optional. Every example below also runs as a plain .py script.
python -m venv .venv
source .venv/bin/activate
pip install torch numpy
python -c "import torch, numpy; print(torch.__version__, numpy.__version__)"Code language: JavaScript (javascript)

Runnable script that proves the memory rules

The notebook uses torch.rand, so its output changes on every run. The script below uses fixed values so you can compare your output with the comments. np.shares_memory() lets you check sharing directly instead of inferring it from changed values.

import numpy as np
import torch

# 1. Tensor -> NumPy: shares memory on CPU
t = torch.zeros(2, 3)
a = t.numpy()
a[0, 0] = 100.0
print(t[0, 0].item())        # 100.0
t.add_(1)                    # in-place change on the tensor side
print(a[0])                  # [101.   1.   1.]

# 2. NumPy -> Tensor with from_numpy: shares memory, keeps dtype
arr = np.array([1.0, 2.0, 3.0])
t2 = torch.from_numpy(arr)
arr[0] = -1.0
print(t2)                    # tensor([-1.,  2.,  3.], dtype=torch.float64)

# 3. as_tensor: shares only when no conversion is required
x = np.array([4, 8])
same = torch.as_tensor(x)
converted = torch.as_tensor(x, dtype=torch.float32)
x[1] = 5
print(same)                  # tensor([4, 5])
print(converted)             # tensor([4., 8.])  (copy, not updated)

# 4. torch.tensor: always copies
y = np.array([2, 2])
copy = torch.tensor(y)
y[1] = 4
print(copy)                  # tensor([2, 2])

# 5. Check sharing explicitly
print(np.shares_memory(arr, t2.numpy()))   # True
print(np.shares_memory(y, copy.numpy()))   # FalseCode language: PHP (php)

Sections 1 and 2 match the first half of the notebook. Section 3 adds the case the notebook leaves out: passing a different dtype to torch.as_tensor() forces a copy, so the tensor stops following the array. Section 4 matches the notebook's last cells.

Note: On Windows with NumPy versions before 2.0, the default integer type is 32-bit. There, same prints as tensor([4, 5], dtype=torch.int32). On Linux and macOS it is int64, which PyTorch does not show in the output.

Converting GPU and autograd tensors to NumPy

NumPy arrays live only in CPU memory and know nothing about autograd. That is why tensor.numpy() refuses two common kinds of tensor. In real training code you will usually have to detach the tensor and move it to the CPU first.

import torch

device = "cuda" if torch.cuda.is_available() else "cpu"
w = torch.rand(3, requires_grad=True, device=device)

# w.numpy() raises an error: the tensor requires grad (and may be on the GPU)

w_np = w.detach().cpu().numpy()   # standard pattern
print(w_np.dtype, w_np.shape)     # float32 (3,)

# Recent PyTorch releases also accept a shortcut that detaches and copies as needed
w_np2 = w.numpy(force=True)Code language: PHP (php)
  • detach() returns a tensor that shares data with w but has no gradient history. It does not copy anything.
  • cpu() copies the data to host memory if the tensor is on a GPU. If it is already on the CPU, it returns the same tensor.
  • Once the data has gone through a GPU, the NumPy array no longer shares memory with the original tensor. Writing to the array has no effect on the model.
  • Going the other way, torch.from_numpy(arr).to("cuda") or torch.as_tensor(arr, device="cuda") always copies, because the array is in CPU memory.

Watch the dtype: float64 versus float32

NumPy creates float arrays as float64 by default, and torch.from_numpy() keeps that dtype. That is why the notebook shows dtype=torch.float64. PyTorch layers use float32 by default, so feeding them a float64 tensor fails with a dtype mismatch error such as mat1 and mat2 must have the same dtype.

import numpy as np
import torch

features = np.random.rand(8, 4)               # float64
model = torch.nn.Linear(4, 1)                 # float32 weights

# Option 1: convert in NumPy, then share memory
x = torch.from_numpy(features.astype(np.float32))

# Option 2: convert in PyTorch (this makes a copy)
x = torch.from_numpy(features).float()

# Option 3: one call that converts and copies only if needed
x = torch.as_tensor(features, dtype=torch.float32)

print(model(x).shape)                         # torch.Size([8, 1])Code language: PHP (php)

Integer arrays have the same issue. Labels for nn.CrossEntropyLoss must be int64 (torch.long). Image data loaded as uint8 usually needs .float() and scaling before it goes into a network.

Common errors and how to fix them

Error message (abridged)CauseFix
can't convert cuda:0 device type tensor to numpyCalling .numpy() on a GPU tensort.cpu().numpy()
Can't call numpy() on Tensor that requires gradTensor is part of the autograd grapht.detach().numpy() or t.detach().cpu().numpy()
At least one stride in the given numpy array is negativeArray came from arr[::-1], np.flip() or a similar viewtorch.from_numpy(arr.copy()) or np.ascontiguousarray(arr)
The given NumPy array is not writable (warning)Array is read-only, for example a view returned by some image librariesPass arr.copy(), or use torch.tensor(arr) to copy
can't convert np.ndarray of type numpy.object_Ragged list or mixed types in the arrayPad sequences to one length or build the array with an explicit numeric dtype
mat1 and mat2 must have the same dtypefloat64 input sent to float32 layersConvert with .float() or astype(np.float32)

Corrections to the notebook

  • The markdown above the torch.from_numpy sharing demo refers to tensor and numpy_from_tensor and says that modifying the original array changes them. The cell actually modifies tensor_from_numpy and shows the change in numpy_arr. Read it as: tensor_from_numpy and numpy_arr share memory, so a change to either one is visible in the other.
  • The heading on the torch.as_tensor cell only covers input that is already a tensor. For a NumPy array, as_tensor also shares memory when the dtype and device match. If you request a different dtype or device, it copies.
  • The claim that NumPy arrays and tensors share memory applies to CPU tensors only. GPU tensors must be copied to the CPU first.
  • "Interoperablity" in the first heading should read "Interoperability".
  • The notebook kernel targets Python 3.7, which current PyTorch releases no longer support. Use a newer Python 3 version.

Best practices

  • Use torch.from_numpy() when you want zero-copy speed and you control the array's lifetime, for example inside a Dataset.__getitem__ that builds a new array on every call.
  • Use torch.tensor() or .clone() when the source array may be changed later, such as a buffer that gets reused or a preprocessing cache.
  • To copy an existing tensor, use t.clone().detach() instead of torch.tensor(t). PyTorch prints a warning recommending this.
  • Set the dtype on purpose at the boundary between NumPy and PyTorch, usually float32 for features and int64 for class labels.
  • In evaluation code, convert outputs with outputs.detach().cpu().numpy() inside torch.no_grad(), so you do not keep autograd graphs alive.
  • When behaviour surprises you, check with np.shares_memory() instead of guessing.

Frequently asked questions

Does tensor.numpy() copy the data?

No. For a CPU tensor, tensor.numpy() returns an array that uses the same memory, so in-place changes on either side show up on the other. Use tensor.numpy().copy() or tensor.clone().numpy() if you need an independent array.

What is the difference between torch.from_numpy and torch.tensor?

torch.from_numpy() always shares memory with the source array and keeps its dtype. torch.tensor() always copies the data, so later changes to the array do not affect the tensor.

When does torch.as_tensor share memory with a NumPy array?

It shares memory when the array's dtype is supported by PyTorch and you do not ask for a different dtype or device. If you pass dtype=torch.float32 for a float64 array, or device='cuda', it creates a copy.

How do I convert a CUDA tensor to a NumPy array?

Move the tensor to the CPU first, and detach it if it requires gradients: t.detach().cpu().numpy(). Recent PyTorch releases also support t.numpy(force=True), which does the same in one call.

Why is my tensor float64 after converting from NumPy?

NumPy float arrays default to float64, and torch.from_numpy() keeps the source dtype. Convert with .float(), arr.astype(np.float32) or torch.as_tensor(arr, dtype=torch.float32) before passing the data to a model.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Jupyter notebook โ€“ Lab Session โ€“ 8 โ€“ Calculating Descriptive Statistics with math, statistics, numpy, pandas

This lab calculates descriptive statistics in a Jupyter notebook with Python's built-in math and statistics modules, NumPy, SciPy and pandas. It covers central tendency (mean, weighted, harmonic…

Read More

Jupyter notebook โ€“ Lab Session โ€“ 2 โ€“ Analyzing Data with Pandas, NumPy & Visualizing Data with matplotlib

This lab loads a historical earthquake dataset into a Jupyter notebook with pandas, joins the separate Date and Time columns into one datetime column, and makes it…

Read More

PyTorch Lab – 9 – Pytorch CUDA Semantics

This lab covers how PyTorch builds a computation graph on the fly as tensor operations run, and how that graph behaves when tensors and models are on…

Read More

PyTorch Lab – 8 – Pytorch Install And Setup Tensorflow Hidden Layer

This lab sets up HiddenLayer, a small Python library that draws neural network graphs and plots training metrics, along with the Graphviz bindings it uses to render…

Read More

PyTorch Lab – 7 – Pytorch CUDA Semantics

This page covers a PyTorch lab notebook that fits a linear regression model with autograd and manual gradient descent. The title mentions CUDA, but the notebook above…

Read More

PyTorch Lab – 6 – Pytorch Autograd With Variables

This lab uses PyTorch autograd to calculate gradients through a single multiplication, result = var * w1, using the older torch.autograd.Variable wrapper. Below you'll find what each…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x