温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - How to get value of a Keras tensor in TensorFlow 2?
keras python tensorflow tensorflow2.0

python - 如何在TensorFlow 2中获得Keras张量的值?

发布于 2020-04-10 10:51:48

TF1拥有sess.run().eval()获得张量的值-Keras拥有K.get_value(); 现在,两者都不一样(以前是两个)。

K.eager(K.get_value)(tensor)似乎可以通过退出来在Keras图内运行,而K.get_value(tensor)在图外运行-都带有TF2的默认值(在以前关闭的)。但是,如果tensorKeras后端操作,则此操作将失败

import keras.backend as K
def tensor_info(x):
    print(x)
    print("Type: %s" % type(x))
    try:        
        x_value = K.get_value(x)
    except:
        try:    x_value = K.eager(K.get_value)(x)
        except: x_value = x.numpy()
    print("Value: %s" % x_value)  # three methods

ones = K.ones(1)
ones_sqrt = K.sqrt(ones)

tensor_info(ones); print()
tensor_info(ones_sqrt)
<tf.Variable 'Variable:0' shape=(1,) dtype=float32, numpy=array([1.], dtype=float32)>
Type: <class 'tensorflow.python.ops.resource_variable_ops.ResourceVariable'>
Value: [1.]

Tensor("Sqrt:0", shape=(1,), dtype=float32)
Type: <class 'tensorflow.python.framework.ops.Tensor'>
# third print fails w/ below
AttributeError: 'Tensor' object has no attribute 'numpy' 


在TF <2.0中这不是问题。Github一直保持沉默。我知道将代码重写为一种变通方法,但是它将消除Keras的后端中立性,并且类似于tf.keras有没有办法在TensorFlow 2.0中获取Keras 2.3张量值同时保持后端中立性?

查看更多

提问者
OverLordGoldDragon
被浏览
95
Sergei Lebedev 2019-10-06 21:28

我想你要K.eval

>>> v = K.ones(1)
>>> K.eval(v)
array([1.], dtype=float32)
>>> K.eval(K.sqrt(v))
array([1.], dtype=float32)

请注意,与任何张量一起K.get_value使用时,保留用于变量(例如,v此处)K.eval