7

I tried searching for the documentation online but I can't find anything that gives me an answer. What does .numpy() function do? The example code given is:

y_true = []
for X_batch, y_batch in mnist_test:
    y_true.append(y_batch.numpy()[0].tolist())
0

3 Answers 3

16

Both in Pytorch and Tensorflow, the .numpy() method is pretty much straightforward. It converts a tensor object into an numpy.ndarray object. This implicitly means that the converted tensor will be now processed on the CPU.

1
  • 1
    > This implicitly means that the converted tensor will be now processed on the CPU. Here's a relevant docstring supporting this statement Dec 15, 2021 at 0:49
2

Ever getting a problem understanding some PyTorch function you may ask help().

import torch
t = torch.tensor([1,2,3])
help(t.numpy)

Out:

Help on built-in function numpy:

numpy(...) method of torch.Tensor instance
    numpy() -> numpy.ndarray
    
    Returns :attr:`self` tensor as a NumPy :class:`ndarray`. This tensor and the
    returned :class:`ndarray` share the same underlying storage. Changes to
    :attr:`self` tensor will be reflected in the :class:`ndarray` and vice versa.

This numpy() function is the converter form torch.Tensor to numpy array.

0

If we look at this code below, we see a simple example where the .numpy() convert Tensors to numpy arrays automatically.

import numpy as np

ndarray = np.ones([3, 3])

print("TensorFlow operations convert numpy arrays to Tensors automatically")
tensor = tf.multiply(ndarray, 42)
print(tensor)


print("And NumPy operations convert Tensors to numpy arrays automatically")
print(np.add(tensor, 1))

print("The .numpy() method explicitly converts a Tensor to a numpy array")
print(tensor.numpy())

In the 2nd last line of code, we see that the tensorflow officials declared it as the converter of Tensor to a numpy array. You may check it out here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.