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
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
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
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
import tensorflow as tf
value = tf.constant([ 1 , 15 , 10 ], dtype = tf.float64)
print ( "Value: " , value)
proto = tf.make_tensor_proto(value)
res = tf.make_ndarray(proto)
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
import tensorflow as tf
value = tf.constant([[ 1 , 2 ], [ 3 , 4 ]], dtype = tf.float64)
print ( "Value: " , value)
proto = tf.make_tensor_proto(value)
res = tf.make_ndarray(proto)
print ( "Result: " , res)
|
Output:
Value: tf.Tensor(
[[1. 2.]
[3. 4.]], shape=(2, 2), dtype=float64)
Result: [[1. 2.]
[3. 4.]]
Last Updated :
22 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...