问题
While doing some calculations I end up calculating an average_acc
. When I try to print it, it outputs: tf.Tensor(0.982349, shape=(), dtype=float32)
. How do I get the 0.98..
value of it and use it as a normal float?
What I'm trying to do is get a bunch of those in an array and plot some graphs, but for that, I need simple floats as far as I can tell.
回答1:
It looks to me as if you have not evaluated the tensor. You can call tensor.eval()
to evaluate the result, or use session.run(tensor)
.
import tensorflow as tf
a = tf.constant(3.5)
b = tf.constant(4.5)
c = a * b
with tf.Session() as sess:
result = c.eval()
# Or use sess.run:
# result = sess.run(c)
print(result)
# out: 15.75
print(type(result))
# out: <class 'numpy.float32'>
回答2:
Run it in session and then print it. Unless you run it in a session, it remains as an object in Tensorflow, it won't be initialized. Here is an example:
with tf.Session() as sess:
acc = sess.run(average_acc)
print(acc)
回答3:
The easiest and best way to do it is using tf.keras.backend.get_value
API.
print(average_acc)
>>tf.Tensor(0.982349, shape=(), dtype=float32)
print(tf.keras.backend.get_value(average_acc))
>>0.982349
来源:https://stackoverflow.com/questions/50927890/how-to-get-the-value-of-a-tensor-python