TensorFlow 中查看 的具体数值的两种方法

时间:2025-03-30 07:33:48

由于TensorFlow 由静态图构成,所以不能直接查看tensor的数值,而使用动态图的TensorFlow 则可以直接查看

TensorFlow 1有两中查看方式:

第一种方法:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

sess = tf.Session()
sess.run(tf.global_variables_initializer())
tensor = tf.Variable([[1,2]])
sess.run(tensor)

第二种方法:

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

sess = tf.Session()
sess.run(tf.global_variables_initializer())
tensor = tf.Variable([[1,2]])
tensor.eval(session=sess)
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

sess = tf.Session()
sess.run(tf.global_variables_initializer())
tensor_a = tf.Variable([[1,2]])
tensor_b = tf.Variable([[1,2]])

with sess.as_default(): # () as:
   tensor_a.eval()  # runs one step
   tensor_b.eval()  # runs one step
   sess.run([tensor_a, tensor_b])  # evaluates both tensors in a single step