Keras将输入提供给中间层并获得最终输出

Asi*_*sim 4 python machine-learning neural-network keras keras-layer

我的模型是一个简单的完全连接的网络,如下所示:

inp=Input(shape=(10,))
d=Dense(64, activation='relu')(inp)
d=Dense(128,activation='relu')(d)
d=Dense(256,activation='relu')(d)     #want to give input here, layer3
d=Dense(512,activation='relu')(d)
d=Dense(1024,activation='relu')(d)
d=Dense(128,activation='linear')(d)
Run Code Online (Sandbox Code Playgroud)

因此,保存模型后,我想将输入提供给第3层。我现在正在做的是:

model=load_model('blah.h5')    #above described network
print(temp_input.shape)        #(16,256), which is equal to what I want to give

index=3
intermediate_layer_model = Model(inputs=temp_input,
                                 outputs=model.output)

End_output = intermediate_layer_model.predict(temp_input)
Run Code Online (Sandbox Code Playgroud)

但这不起作用,即我收到诸如不兼容输入之类的错误,输入应为元组等。错误消息为:

raise TypeError('`inputs` should be a list or tuple.') 
TypeError: `inputs` should be a list or tuple.
Run Code Online (Sandbox Code Playgroud)

有什么办法可以让我在网络中间传递自己的输入并获取输出,而不是在开始时输入并从末尾获取输出?任何帮助将不胜感激。

tod*_*day 6

首先,您必须在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)
Run Code Online (Sandbox Code Playgroud)

幸运的是,您的模型由一个分支组成,我们可以简单地使用for循环来构建新模型。但是,对于更复杂的模型,这样做可能并不容易,您可能需要编写更多代码来构建新模型。


ani*_*an7 5

这是实现相同结果的另一种方法。最初创建一个新的输入层,然后将其连接到较低的层(带权重)。

为此,首先重新初始化这些层(具有相同名称)并使用从父模型重新加载相应的权重

new_model.load_weights("parent_model.hdf5", by_name=True )

这将从父模型加载所需的权重。只需确保事先正确命名图层。

idx = 3  
input_shape = model.layers[idx].get_input_shape_at(0) layer

new_input = Input(shape=input_shape)

d=Dense(256,activation='relu', name='layer_3')(new_input)
d=Dense(512,activation='relu', name='layer_4'))(d)
d=Dense(1024,activation='relu', name='layer_5'))(d)
d=Dense(128,activation='linear', name='layer_6'))(d)

new_model = Model(new_input, d)
new_model.load_weights("parent_model.hdf5", by_name=True)
Run Code Online (Sandbox Code Playgroud)

此方法适用于具有多个输入或分支的复杂模型。您只需为所需层复制相同的代码,连接新输入并最终加载相应的权重。