Python 如何获得中间层的输出?
我在努力理解。我应该如何使用此代码:Python 如何获得中间层的输出?,python,tensorflow,keras,Python,Tensorflow,Keras,我在努力理解。我应该如何使用此代码: from keras import backend as K prediction_model = lstm_model(seq_len=1, batch_size=BATCH_SIZE, stateful=True) prediction_model.load_weights('/tmp/bard.h5') get_test_layer_output = K.function([prediction_model.layers[0].input],
from keras import backend as K
prediction_model = lstm_model(seq_len=1, batch_size=BATCH_SIZE, stateful=True)
prediction_model.load_weights('/tmp/bard.h5')
get_test_layer_output = K.function([prediction_model.layers[0].input],
[prediction_model.layers[1].output])
layer_output = get_test_layer_output([x])[0]
要查看每个层后的值?或者是否有不同的方法来查看值(而不是形状)
对于要在Keras模型的层上执行的任何操作,首先,我们需要访问模型持有的
Keras.layers
对象列表
model_layers = model.layers
此列表中的每个图层对象都有自己的输入
和输出
张量(如果您使用的是TensorFlow后端)
如果您直接使用tf.Session.run()
方法运行输出张量,您将得到一个错误,说明在访问层的输出之前必须将输入馈送到模型
在运行模型之前,需要使用
tf.global\u variables\u initializer().run()
初始化变量。model.input
为模型的输入提供占位符张量。对于要在Keras模型的层上执行的任何操作,首先,我们需要访问模型持有的Keras.layers
对象列表
model_layers = model.layers
此列表中的每个图层对象都有自己的输入
和输出
张量(如果您使用的是TensorFlow后端)
如果您直接使用tf.Session.run()
方法运行输出张量,您将得到一个错误,说明在访问层的输出之前必须将输入馈送到模型
在运行模型之前,需要使用tf.global\u variables\u initializer().run()
初始化变量。model.input
为模型的输入提供占位符张量
input_tensor = model.layers[ layer_index ].input
output_tensor = model.layers[ layer_index ].output
import tensorflow as tf
import numpy as np
layer_index = 3 # The index of the layer whose output needs to be fetched
model = tf.keras.models.load_model( 'model.h5' )
out_ten = model.layers[ layer_index ].output
with tf.Session() as sess:
tf.global_variables_initializer().run()
output = sess.run( out_ten , { model.input : np.ones((2,186))} )
print( output )