python - 如何将 tensorflow 变量打印到小数点后两位?

标签 python tensorflow

weights = tf.Variable(tf.truncated_normal([2,3]))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print('Weights:')
    print(sess.run(weights))

    print("{0:2f}".format(sess.run(weights)))

第一个打印语句按预期工作。

Weights:
[[ 0.30919516  0.29567152  0.11157229] 
 [ 0.26642913 -0.21269836 -0.58886886]]

使用 str.format() 的第二个打印语句给出以下错误。

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-20-b0e4f93d01f8> in <module>()
  4     print('Weights:')
  5     print(sess.run(weights))
----> 6     print("{0:2f}".format(sess.run(weights)))

> TypeError: non-empty format string passed to object.__format__

除了下面的答案之外,我还发现 np.set_printoptions( precision=2) 也有效。

np.set_printoptions(precision=2)
weights = tf.Variable(tf.truncated_normal([2,3]))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print('Weights:')
    print(sess.run(weights)) 

Weights:
[[ 0.01 -0.42 -1.57]
 [-0.44  1.62  0.27]]

最佳答案

您尝试打印整个数组,并且 format 需要可以表示为 float 的单个值。尝试这样:

print(np.around(sess.run(weights), 2)
#[[ 0.31  0.30  0.11] 
# [ 0.27 -0.21 -0.59]]

此外,正确的格式是0:.2f

关于python - 如何将 tensorflow 变量打印到小数点后两位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48710409/

相关文章:

sorting - 如何在 tensorflow 中对一批二维张量进行排序?

python - Tensorflow:在 LSTM 中显示或保存遗忘门值

Python 3 - 键错误 0

python - 减少 CNN 模型中的验证损失

c++ - TensorFlow Lite 模型测试类的 : right code, 概率

numpy - 为什么特征值分解的 TensorFlow 和 PyTorch 梯度彼此不同,解析解也不同?

python - 使用 JSON 功能读取 CSV

Python 正则表达式 : How to implement a regex expression that checks for matching set of brackets?

python - 树莓派LED亮度计算

python - 将不同的编码转换为ascii