tensorflow张量和numpy数组相互转换

知识补充:

官方文档(GItHub):TensorFlow 2.0: Functions, not Sessions.

tensorflow2.x的转换模块@tf.function

关于图执行(Graph )和立即执行(Eager)

numpy数组转换成张量:(tf.convert_to_tensor)

import numpy as np 
import tensorflow as tf

a = np.ones((1,2))
print(a, type(a))
a = tf.convert_to_tensor(a, dtype='float32')
print(a, type(a))

输出为:
[[1. 1.]] 
tf.Tensor([[1. 1.]], shape=(1, 2), dtype=float32)  

张量转换为数组: (Session.run 或者 eval)

import numpy as np 
import tensorflow as tf

tf.compat.v1.disable_eager_execution()

b = tf.constant([1,2,3])
b = tf.compat.v1.Session().run(b)
print(b, type(b))

b = tf.constant([1,2,3])
with tf.compat.v1.Session().as_default():
        b = b.eval()
print(b, type(b))

输出:
[1 2 3] 
[1 2 3] 

(tensorflow2.0以上版本需要tf.compat.v1作为接口)

eager_execution 是tensorflow的立即执行模式(不同于图执行模式),在2.x的tensorflow中默认打开,需要调用disable_eager_execution()去关闭(在1.x的版本中则是默认关闭)

如果不关闭该模式,则需要.numpy()来转换成数组,继续用eval()则会报错:

eval is not supported when eager execution is enabled

import numpy as np 
import tensorflow as tf

b = tf.constant([1,2,3])
with tf.compat.v1.Session().as_default():
        # b = b.eval()
        b= b.numpy()
print(b, type(b))

补充:实测可以直接调用numpy的asarray来转换

补充:

关于图执行(Graph )和立即执行(Eager)

tensorflow2.x的转换模块@tf.function

你可能感兴趣的:(python,tensorflow)