Tensorflow: Tensor to numpy array conversion without running any session

故事扮演 提交于 2021-02-07 12:49:40

问题


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:


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>


来源:https://stackoverflow.com/questions/52215711/tensorflow-tensor-to-numpy-array-conversion-without-running-any-session

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!