TF1拥有sess.run()
并.eval()
获得张量的值-Keras拥有K.get_value()
; 现在,两者都不一样(以前是两个)。
K.eager(K.get_value)(tensor)
似乎可以通过退出来在Keras图内运行,而K.get_value(tensor)
在图外运行-都带有TF2的默认值(在以前是关闭的)。但是,如果tensor
是Keras后端操作,则此操作将失败:
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.keras
。有没有办法在TensorFlow 2.0中获取Keras 2.3张量值同时保持后端中立性?
我想你要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
。
谢谢; 但是,只能与
import keras.backend as K
- 一起使用,tensorflow.keras.backend
而对于和则失败tensorflow.python.keras.backend
。由于其他功能可能取决于后两者,因此这并不是一个完整的答案。但是,这可能是一个错误-您可以确认吗?我已经用您列出的导入检查了代码片段,所有这三个代码都产生了相同的结果。您能否使用在每种情况下获得的输出来更新您的问题?
一切都很好-事实
tf.python
并非意味着无论如何都不会使用(请参阅此处),或者并非总是如此。