python - 如何获得中间层的输出?
问题描述
我正在尝试了解Google 的 colab 代码。我应该如何使用此代码:
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]
查看每一层之后的值?还是有任何不同的方法来查看值(不是形状)?
Layer (type) Output Shape Param #
=================================================================
seed (InputLayer) (128, 100) 0
_________________________________________________________________
embedding (Embedding) (128, 100, 512) 131072
_________________________________________________________________
lstm (LSTM) (128, 100, 512) 2099200
_________________________________________________________________
lstm_1 (LSTM) (128, 100, 512) 2099200
_________________________________________________________________
time_distributed (TimeDistri (128, 100, 256) 131328
=================================================================
Total params: 4,460,800
Trainable params: 4,460,800
Non-trainable params: 0
解决方案
对于要在 Keras 模型的层上执行的任何操作,首先,我们需要访问keras.layers
模型所拥有的对象列表。
model_layers = model.layers
此列表中的每个 Layer 对象都有自己的张量input
和output
张量(如果您使用的是 TensorFlow 后端)
input_tensor = model.layers[ layer_index ].input
output_tensor = model.layers[ layer_index ].output
如果您直接使用该tf.Session.run()
方法运行 output_tensor,您将收到一个错误,指出必须在访问层的输出之前将输入馈送到模型。
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 )
您需要tf.global_variables_initializer().run()
在运行模型之前使用初始化变量。为模型的model.input
输入提供占位符张量。
推荐阅读
- machine-learning - 无论如何要省略 VGG16 目标类?
- python - 如何在二进制张量中找到相邻的真值组?
- excel - VBA API REST - 返回状态 500
- c++ - 将字符串作为输入并将其拆分为单词的函数。标点符号应该被忽略
- javascript - 您将如何创建一个自动昵称系统,每个新成员的昵称数量都会增加?
- angular - 需要帮助:Angular 路由器和导航项目不起作用
- java - 自 Wildfly 15 以来,Arquillian 托管测试不再有效
- javascript - 如何使用 react-big-calendar 获取时间段的时间?
- javascript - 使用来自 AJAX 调用的动态 HTML 重新渲染 Vue 组件
- vba - 如何让 Shapes.HasTitle 找到演示文稿中的所有标题(VBA、.ppt)?