我在使用Tensorflow 2.6.0时,尝试应用类似问题的答案时遇到了困难。
我在调试过程中希望查看张量中的值。如果我使用Python的print函数
predicted_ids=tf.random.categorical(predicted_logits, num_samples=1)predicted_ids=tf.squeeze(predicted_ids, axis=-1)print(predicted_ids)
我得到的输出是
Tensor("Squeeze:0", shape=(1,), dtype=int64)
然后我尝试了以下方法:
(1)
print(tf.Print(predicted_ids, [predicted_ids], message="This is predicted_ids: "))
(2)
with tf.Session() as sess: print(predicted_ids.eval())
(3)
sess = tf.InteractiveSession()a = tf.Print(predicted_ids, [predicted_ids], message="This is predicted_ids: ")
所有这些方法都会抛出错误。我认为这是一个非常常见的问题,在TensorFlow 2.6.0中一定有一个优雅、健壮且简单的答案。
回答:
这实际上非常简单:
例如:
tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5).numpy()
输出:
array([[1, 1, 1, 0, 1]])
在你的情况下:
predicted_ids.numpy()