Keras 1.0:获得中间层输出

时间:2016-04-20 13:45:16

标签: theano keras

我目前正在尝试将Keras 1.0中的中间层输出可视化(我可以使用Keras 0.3),但它不再起作用了。

x = model.input
y = model.layers[3].output
f = theano.function([x], y)

但是我收到以下错误:

MissingInputError: ("An input of the graph, used to compute DimShuffle{x,x,x,x}(keras_learning_phase), was not provided and not given a value.Use the Theano flag exception_verbosity='high',for more information on this error.", keras_learning_phase)

在Keras 1.0之前,使用我的图表模型,我可以这样做:

x = graph.inputs['input'].input
y = graph.nodes[layer].get_output(train=False)
f = theano.function([x], y, allow_input_downcast=True)

所以我怀疑它来自“train = False”参数,我不知道如何设置新版本。

感谢您的帮助

2 个答案:

答案 0 :(得分:6)

尝试: 在import语句中首先给出

from keras import backend as K
from theano import function

然后

f = K.function([model.layers[0].input, K.learning_phase()],
                              [model.layers[3].output])
# output in test mode = 0
layer_output = get_3rd_layer_output([X_test, 0])[0]

# output in train mode = 1
layer_output = get_3rd_layer_output([X_train, 1])[0]

答案 1 :(得分:3)

这是由FrançoisChollet在github上回答的:

  

您的模型在训练和测试模式中显然有不同的行为,因此需要知道它应该使用的模式。

     

使用

     

iterate = K.function([input_img, K.learning_phase()], [loss, grads])

     

并根据您是否希望模型处于训练模式或测试模式,将1或0作为学习阶段的值传递。

https://github.com/fchollet/keras/issues/2417