Tensorflow: Tensor to numpy array conversion without running any session

Viewed 18616

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
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>
Related