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

Ove*_*gon 6 python keras tensorflow tensorflow2.0

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)
Run Code Online (Sandbox Code Playgroud)
<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
Run Code Online (Sandbox Code Playgroud)
AttributeError: 'Tensor' object has no attribute 'numpy' 
Run Code Online (Sandbox Code Playgroud)


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

Ser*_*dev 6

我想你想要K.eval

>>> v = K.ones(1)
>>> K.eval(v)
array([1.], dtype=float32)
>>> K.eval(K.sqrt(v))
array([1.], dtype=float32)
Run Code Online (Sandbox Code Playgroud)

请注意,K.get_value保留用于变量(例如v此处),同时K.eval适用于任何张量。