[英]How to get the value of a tensor? Python
在做一些計算時,我最終計算了一個average_acc
。 當我嘗試打印它時,它輸出: tf.Tensor(0.982349, shape=(), dtype=float32)
。 如何獲得它的0.98..
值並將其用作普通浮點數?
我想要做的是在數組中獲取一堆並繪制一些圖形,但為此,據我所知,我需要簡單的浮點數。
在我看來,您好像還沒有計算過張量。 您可以調用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'>
最簡單和最好的方法是使用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
在會話中運行它,然后打印它。 除非你在會話中運行它,否則它在 Tensorflow 中仍然是一個對象,不會被初始化。 下面是一個例子:
with tf.Session() as sess:
acc = sess.run(average_acc)
print(acc)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.