TanM
TanM

Reputation: 109

How to print a Tensor Flow variable to 2 decimal places?

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

The first print statement works as expected.

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

The second print statement with str.format() gives the below error.

---------------------------------------------------------------------------
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__

In addition to the below answer, I also found np.set_printoptions(precision=2) also works.

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]]

Upvotes: 3

Views: 3233

Answers (1)

zipa
zipa

Reputation: 27879

You trying to print the whole array and format expects single value that could be represented as float. Try like this:

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

Also, the correct format would be 0:.2f

Upvotes: 1

Related Questions