作者:阳光映像YGYX | 来源:互联网 | 2022-12-02 12:50
我的模型是一个简单的完全连接的网络,如下所示:
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)
因此,保存模型后,我想将输入提供给第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)
但这不起作用,即我收到诸如不兼容输入之类的错误,输入应为元组等。错误消息为:
raise TypeError('`inputs` should be a list or tuple.')
TypeError: `inputs` should be a list or tuple.
有什么办法可以让我在网络中间传递自己的输入并获取输出,而不是在开始时输入并从末尾获取输出?任何帮助将不胜感激。
1> today..:
首先,您必须在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
循环来构建新模型。但是,对于更复杂的模型,这样做可能并不容易,您可能需要编写更多代码来构建新模型。