首先,您必须在Keras中学习到,在输入上应用层时,在该层内创建了一个新节点,该节点连接输入和输出张量。每一层可具有将不同的输入张量连接到其相应的输出张量的多个节点。要构建模型,将遍历这些节点并创建一个新的模型图,其中包括从输入张量(即在创建模型时指定的)到达输出张量所需的所有节点model = Model(inputs=[...], outputs=[...])
。
现在,您想提供模型的中间层并获取模型的输出。由于这是一条新的数据流路径,因此我们需要为与该新计算图相对应的每一层创建新节点。我们可以这样做:
idx = 3 # index of desired layer
input_shape = model.layers[idx].get_input_shape_at(0) # get the input shape of desired layer
layer_input = Input(shape=input_shape) # a new input tensor to be able to Feed the desired layer
# create the new nodes for each layer in the path
x = layer_input
for layer in model.layers[idx:]:
x = layer(x)
# create the model
new_model = Model(layer_input, x)
幸运的是,您的模型由一个分支组成,我们可以简单地使用for
循环来构建新模型。但是,对于更复杂的模型,这样做可能并不容易,并且您可能需要编写更多代码来构建新模型。