Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: Tensor to numpy array conversion without running any session

I have created an OP in tensorflow where for some processing I need my data to be converted from tensor object to numpy array. I know we can use tf.eval() or sess.run to evaluate any tensor object. What I really want to know is, Is there any way to convert tensor to array without any session running, so in turn we avoid use of .eval() or .run().

Any help is highly appreciated!

def tensor_to_array(tensor1):
    '''Convert tensor object to numpy array'''
    array1 = SESS.run(tensor1) **#====== need to bypass this line**
    return array1.astype("uint8")

def array_to_tensor(array):
    '''Convert numpy array to tensor object'''
    tensor_data = tf.convert_to_tensor(array, dtype=tf.float32)
    return tensor_data
like image 924
KapB Avatar asked Sep 07 '18 05:09

KapB


People also ask

Can you convert a tensor to Numpy array?

To convert back from tensor to numpy array you can simply run . eval() on the transformed tensor.

Which of the following will be used to convert Numpy array to TensorFlow tensor?

convert_to_tensor() method from the TensorFlow library is used to convert a NumPy array into a Tensor.

What is the difference between a tensor and a Numpy array?

The key difference between tensors and NumPy arrays is that tensors have accelerator support like GPU and TPU and are immutable.


1 Answers

Updated

# must under eagar mode
def tensor_to_array(tensor1):
    return tensor1.numpy()

example

>>> import tensorflow as tf
>>> tf.enable_eager_execution()
>>> def tensor_to_array(tensor1):
...     return tensor1.numpy()
...
>>> x = tf.constant([1,2,3,4])
>>> tensor_to_array(x)
array([1, 2, 3, 4], dtype=int32)

I believe you can do it without tf.eval() or sess.run by using tf.enable_eager_execution()

example

import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
x = np.array([1,2,3,4])
c = tf.constant([4,3,2,1])
c+x
<tf.Tensor: id=5, shape=(4,), dtype=int32, numpy=array([5, 5, 5, 5], dtype=int32)>

For more details about tensorflow eager mode, checkout here:Tensorflow eager

If without tf.enable_eager_execution():

import tensorflow as tf
import numpy as np
c = tf.constant([4,3,2,1])
x = np.array([1,2,3,4])
c+x
<tf.Tensor 'add:0' shape=(4,) dtype=int32>
like image 78
R.yan Avatar answered Nov 07 '22 20:11

R.yan