【问题标题】:Inspect value of a tensor in Tensorflow 2.0在 Tensorflow 2.0 中检查张量的值
【发布时间】:2021-10-01 13:07:06
【问题描述】:

我很难使用 Tensorflow 2.6.0 将答案应用于 similar questions

我想在调试期间检查张量中的值。如果我做 Python 打印

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: ")

所有这些都会引发错误。在我看来,这是一个非常常见的问题,在 TF 2.6.0 中必须有一个优雅而稳健的简单答案。

【问题讨论】:

  • @hafiz031 已经给你答案了。使用他展示的numpy 方法(不是属性)。
  • 不幸的是,predicted_ids.numpy() 出现错误
  • predicted_logits 或您的安装必须关闭某些内容,因为我用[0.3, 0.2, 0.1, 0.4] 代替predicted_logits.numpy() 在TF 2.6.0 上运行良好

标签: python tensorflow machine-learning


【解决方案1】:

其实很简单:

例如:

tf.random.categorical(tf.math.log([[0.5, 0.5]]), 5).numpy()

输出:

array([[0, 1, 1, 0, 0]])

在你的情况下:

predicted_ids.numpy()

【讨论】:

  • AttributeError: 'Tensor' 对象没有属性 'numpy'
【解决方案2】:

我认为您不需要创建会话,因为 .eval() 函数与 TensorFlow v1 兼容。 适合我的代码是使用 tf.print() 函数。这是一个快速演示:

c = tf.constant([[1.0, 2.0], [3.0, 4.0]])
d = tf.constant([[1.0, 1.0], [0.0, 1.0]])
e = tf.matmul(c, d)
print(tf.print(e))

【讨论】:

  • 这打印出一些丑陋的东西name: "PrintV2" op: "PrintV2" input: "StringFormat" attr { key: "end" value { s: "\n" } } attr { key: "output_stream" value { s: "stderr" } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
相关资源
最近更新 更多