How to get the value of a tensor? Python

白昼怎懂夜的黑 提交于 2021-02-07 20:30:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!