taigi100
taigi100

Reputation: 2839

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.

Upvotes: 13

Views: 22555

Answers (3)

DesiKeki
DesiKeki

Reputation: 696

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

Upvotes: 12

soerface
soerface

Reputation: 6813

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

Upvotes: 6

sai
sai

Reputation: 349

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)

Upvotes: 1

Related Questions