Saturday, December 28, 2024
Google search engine
HomeLanguagesTensorFlow – How to create a numpy ndarray from a tensor

TensorFlow – How to create a numpy ndarray from a tensor

TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep-learning, neural networks.

Create a Numpy array from a torch.tensor

A Pytorch Tensor is basically the same as a NumPy array. This means it does not know anything about deep learning or computational graphs or gradients and is just a generic n-dimensional array to be used for arbitrary numeric computation.

Example 1: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_a = tensor.numpy()


Output:

array([1, 2, 3, 4, 5])

Example 2: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.detach.numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_b = tensor.detach().numpy()


Output:

array([1, 2, 3, 4, 5])

Example 3: 

To create a Numpy array from Tensor, Tensor is converted to a tensor.detach().cpu().numpy() first.

Python3




# pip install torch
import torch
tensor = torch.tensor([1, 2, 3, 4, 5])
 
np_c = tensor.detach().cpu().numpy()


Output:

array([1, 2, 3, 4, 5])

Create a numpy ndarray from a Tensorflow.tensor

A torch in TensorFlow, as the name indicates, is a framework to define and run computations involving tensors. A tensor is a generalization of vectors and matrices to potentially higher dimensions.

Example 1:

To create a Numpy array from Tensor, Tensor is converted to a proto tensor first.

Python3




# importing the library
import tensorflow as tf
 
# Initializing Input
value = tf.constant([1, 15, 10], dtype = tf.float64)
 
# Printing the Input
print("Value: ", value)
 
# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)
 
# Generating numpy array
res = tf.make_ndarray(proto)
 
# Printing the resulting numpy array
print("Result: ", res)


Output:

Value:  tf.Tensor([ 1. 15. 10.], shape=(3, ), dtype=float64)
Result:  [ 1. 15. 10.]

Example 2: 

This method uses a Tensor with shape (2, 2) so the shape of the resulting array will be (2, 2).

Python3




# importing the library
import tensorflow as tf
 
# Initializing Input
value = tf.constant([[1, 2], [3, 4]], dtype = tf.float64)
 
# Printing the Input
print("Value: ", value)
 
# Converting Tensor to TensorProto
proto = tf.make_tensor_proto(value)
 
# Generating numpy array
res = tf.make_ndarray(proto)
 
# Printing the resulting numpy array
print("Result: ", res)


Output:

Value:  tf.Tensor(
[[1. 2.]
 [3. 4.]], shape=(2, 2), dtype=float64)
Result:  [[1. 2.]
 [3. 4.]]

RELATED ARTICLES

Most Popular

Recent Comments