What does the .numpy() function do?

Viewed 8845

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())
3 Answers

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.

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.

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

Related