Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of a tensor? Python

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.

like image 838
taigi100 Avatar asked Jun 19 '18 11:06

taigi100


2 Answers

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'>
like image 72
soerface Avatar answered Oct 18 '22 04:10

soerface


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
like image 10
DesiKeki Avatar answered Oct 18 '22 03:10

DesiKeki