我有以下张量对象,这超出了a=model.layers[3].output
这段代码
a = <tf.Tensor 'dense_20/Softmax:0' shape=(None, 3) dtype=float32>
如何从上面的张量对象中获取值。我已经尝试print(a.numpy())
并收到以下错误:
AttributeError: 'Tensor' object has no attribute 'numpy'
我也试过eval(a)
方法,并得到同样的上述错误。
使用 a.eval() 时,出现以下错误:
ValueError: Cannot evaluate tensor using `eval()`: No default session is registered. Use `with sess.as_default()` or pass an explicit session to `eval(session=sess)`
我也试过以下:
with tf.compat.v1.Session() as sess:
a=model.layers[3].output
print(sess.run(a))
sess.close()
并收到以下错误:
RuntimeError: The Session graph is empty. Add operations to the graph before calling run().
我从这里尝试了很多东西,但没有得到答案。
我正在研究 google colab,tensorflow=2.2.0,keras=2.3.1
为了评估Keras
模型中任意层的输出,您需要确保其所有输入都可用。这是一个示例代码,它使用虚拟模型来显示相同的内容。代码应该在TF1.x
和中都可以使用TF2.x
。注意这里使用 Keras 函数来摆脱处理 tensorflow 会话的样板代码。
import tensorflow as tf
print('TensorFlow: ', tf.__version__, end='\n\n')
input_layer = tf.keras.Input(shape=[100])
x = tf.keras.layers.Dense(16, activation='relu')(input_layer)
x = tf.keras.layers.Dense(64, activation='relu')(x)
x = tf.keras.layers.Dense(32, activation='relu')(x)
x = tf.keras.layers.Dense(10, activation='relu')(x)
output_layer = tf.keras.layers.Dense(5, activation='softmax')(x)
model = tf.keras.Model(inputs=[input_layer], outputs=[output_layer])
a = model.layers[3].output
print(a)
fn = tf.keras.backend.function(input_layer, a) # create a Keras Function
random_input = tf.random.normal([1, 100]) # random noise
a_eval = fn(random_input)
print('\nLayer Output:\n', a_eval)
输出:
TensorFlow: 2.3.0-dev20200611
Tensor("dense_73/Identity:0", shape=(None, 32), dtype=float32)
Layer Output:
[[0. 0. 0.46475422 0.0961322 0. 0.
0.23016977 0. 0. 0.05861767 0.03298267 0.11953808
0. 0. 0.97043467 0. 0. 0.6384926
0. 0. 0. 0.2346505 0.1822727 0.0145395
0.08411474 0. 0. 0.37601566 0. 0.
0.29435986 0.44069782]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句