Tensorflow:无需运行任何会话即可将 Tensor 转换为 numpy 数组 [英] Tensorflow: Tensor to numpy array conversion without running any session
问题描述
我在 tensorflow 中创建了一个 OP,其中对于某些处理,我需要将我的数据从张量对象转换为 numpy 数组.我知道我们可以使用 tf.eval()
或 sess.run
来评估任何张量对象.我真正想知道的是,有没有办法在不运行任何会话的情况下将张量转换为数组,因此我们又避免使用 .eval()
或 .run()代码>.
非常感谢任何帮助!
def tensor_to_array(tensor1):'''将张量对象转换为numpy数组'''array1 = SESS.run(tensor1) **#====== 需要绕过这一行**返回 array1.astype("uint8")def array_to_tensor(array):'''将numpy数组转换为张量对象'''tensor_data = tf.convert_to_tensor(数组,dtype=tf.float32)返回张量数据
更新
#必须在eagar模式下def tensor_to_array(tensor1):返回 tensor1.numpy()
示例
<预><代码>>>>将张量流导入为 tf>>>tf.enable_eager_execution()>>>def tensor_to_array(tensor1):...返回 tensor1.numpy()...>>>x = tf.constant([1,2,3,4])>>>tensor_to_array(x)数组([1, 2, 3, 4], dtype=int32)我相信你可以在没有 tf.eval()
或 sess.run
的情况下使用 tf.enable_eager_execution()
示例
将 tensorflow 导入为 tf将 numpy 导入为 nptf.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)>
有关张量流急切模式的更多详细信息,请在此处查看:张量流急切
如果没有tf.enable_eager_execution()
:
将 tensorflow 导入为 tf将 numpy 导入为 npc = tf.constant([4,3,2,1])x = np.array([1,2,3,4])c+x<tf.Tensor 'add:0' shape=(4,) dtype=int32>
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
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>
这篇关于Tensorflow:无需运行任何会话即可将 Tensor 转换为 numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!