首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获得中间层的输出?

如何获得中间层的输出?
EN

Stack Overflow用户
提问于 2019-05-23 20:13:03
回答 1查看 2K关注 0票数 1

我在试着理解Google的colab代码。我应该如何使用这个代码:

代码语言:javascript
复制
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]

要查看每一层之后的值?或者有什么不同的方法来查看值(而不是形状)?

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-24 04:17:49

对于要在Keras模型的层上执行的任何操作,首先需要访问模型所包含的keras.layers对象的列表。

代码语言:javascript
复制
model_layers = model.layers

这个列表中的每个层对象都有自己的inputoutput张量(如果使用TensorFlow后端)

代码语言:javascript
复制
input_tensor = model.layers[ layer_index ].input
output_tensor = model.layers[ layer_index ].output

如果您直接使用output_tensor方法运行tf.Session.run(),您将得到一个错误,说明在访问层的输出之前,必须将输入提供给模型。

代码语言:javascript
复制
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为模型的输入提供占位符张量。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56282323

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档