我在tensorflow中创建了一个OP,在其中进行一些处理时需要将我的数据从张量对象转换为numpy数组。我知道我们可以使用tf.eval()或sess.run评估任何张量对象。我真正想知道的是,有没有办法在无需运行任何会话的情况下将张量转换为数组,因此我们又避免使用.eval()or .run()。
任何帮助深表感谢!
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
Run Code Online (Sandbox Code Playgroud)
更新
# must under eagar mode
def tensor_to_array(tensor1):
return tensor1.numpy()
Run Code Online (Sandbox Code Playgroud)
例子
>>> 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)
Run Code Online (Sandbox Code Playgroud)
我相信您可以不使用tf.eval()或sess.run使用tf.enable_eager_execution()
例子
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)>
Run Code Online (Sandbox Code Playgroud)
有关 tensorflow 急切模式的更多详细信息,请在此处查看:Tensorflow 急切模式
如果没有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>
Run Code Online (Sandbox Code Playgroud)