在预测期间从 Keras/Tensorflow 获得中间输出

D.G*_*chi 4 descriptor extraction neural-network keras tensorflow

假设我加载了 inception,我需要在分类之前提取最终描述符。所以给出这样一个简单的代码:

cnn = InceptionV3(weights='imagenet',
              include_top='False',
              pooling='avg')
cnn.predict(x, batch_size=32, verbose=0)
Run Code Online (Sandbox Code Playgroud)

如何在预测期间提取最后一层?

Dan*_*ler 10

找出获得结果所需的层的名称或索引,并考虑该层的输出创建一个新模型。

仅输出该层的模型:

earlyPredictor = Model(cnn.inputs, cnn.layers[theIndexYouWant].outputs)

#alternatively
earlyPredictor = Model(cnn.inputs, cnn.get_layer(theNameYouWant).outputs)    
Run Code Online (Sandbox Code Playgroud)

一个同时输出最终输出和所需层的模型:

fullPredictor = Model(cnn.inputs, [cnn.output, cnn.layers[index].output])  
Run Code Online (Sandbox Code Playgroud)

使用“输出”和“输出”之间的区别仅在层或模型具有多个输出时才会出现。如果 cnn 输出和特定层输出是多个,则第二个示例需要额外注意连接结果列表。