如何获得张量的值?Python

tai*_*100 9 python tensorflow

在进行一些计算时,我最终计算了一个average_acc. 当我尝试打印它时,它输出:tf.Tensor(0.982349, shape=(), dtype=float32). 如何获取0.98..它的值并将其用作普通浮点数?

我想要做的是在数组中获取一堆并绘制一些图形,但为此,据我所知,我需要简单的浮点数。

小智 12

最简单、最好的方法是使用tf.keras.backend.get_valueAPI。

print(average_acc)
>>tf.Tensor(0.982349, shape=(), dtype=float32)
print(tf.keras.backend.get_value(average_acc))
>>0.982349
Run Code Online (Sandbox Code Playgroud)


soe*_*ace 5

在我看来,您好像还没有计算过张量。您可以调用tensor.eval()以评估结果,或使用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'>
Run Code Online (Sandbox Code Playgroud)