如何获得中间层的输出(特征提取)? [英] How can I obtain the output of an intermediate layer (feature extraction)?
问题描述
我想提取光学图像的特征并将其保存到numpy array中.我见过类似的问题,也可以在这里看到:
I want to extract features of a optical image and save them into numpy array . I've seen similar questions , also can be seen here : https://keras.io/getting_started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer-feature-extraction , but don't know how to go about it .
推荐答案
Keras文档确实指定了如何执行此操作.如果定义了模型 model_full
,则可以创建另一个模型,它只是其中的一部分-从输入层到您感兴趣的模型.
Keras documentation does exaclty specify how to do that. If you have defined your model model_full
you can create another one, that is just a part of it - from the input layer, to the one you're interested in.
model_part = Model(
inputs=model_full.input,
outputs=model_full.get_layer("intermed_layer").output)
那么您应该能够使用以下方法从中间层获取输出:
Then you should be able to obtain output from intermediate layer using:
intermed_output = model_part(data)
为此,您只需要定义一个 model_full
,我想您已经定义了.
In order to do that, you just need a model_full
defined, which I assume you already have.
您还可以使用内置的Keras函数,我想您也已经在文档中看到了.乍看起来可能有点复杂,但它只是创建一个具有绑定值的函数,即
You can also use built-in Keras function, which I guess you already saw in documentation as well. It may look kind of complicated at first, but it's just creating a function with bound values i.e.
from keras import backend as K
get_3rd_layer_output = K.function(
[model.layers[0].input], # param 1 will be treated as layer[0].output
[model.layers[3].output]) # and this function will return output from 3rd layer
# here X is param 1 (input) and the function returns output from layers[3]
output = get_3rd_layer_output([X])[0]
很显然,必须再次定义 model
.不确定除此之外是否还有其他要求.
Clearly, again model
has to be defined. Not sure if there are any other requirements apart from that.
这篇关于如何获得中间层的输出(特征提取)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!