我的模型是一个简单的全连接网络,像这样:
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, layer3d=Dense(512,activation='relu')(d)d=Dense(1024,activation='relu')(d)d=Dense(128,activation='linear')(d)
因此,在保存模型后,我想在第三层输入数据。我目前的做法是这样的:
model=load_model('blah.h5') #above described networkprint(temp_input.shape) #(16,256), which is equal to what I want to giveindex=3intermediate_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.
有没有办法可以在网络中间输入自己的数据并获取输出,而不是在开始时输入数据并从末端获取输出?任何帮助将不胜感激。
回答:
首先你必须了解,在Keras中,当你将一层应用于一个输入时,该层内会创建一个新节点,该节点连接输入和输出张量。每层可能有多个节点,连接不同的输入张量到相应的输出张量。为了构建模型,这些节点会被遍历,并创建一个新的模型图,该图包含从输入张量到达输出张量所需的所有节点(即你在创建模型时指定的:model = Model(inputs=[...], outputs=[...])
)。
现在,你希望向模型的中间层输入数据并获取模型的输出。由于这是一个新的数据流路径,我们需要为这条新计算图中的每层创建新节点。我们可以这样做:
idx = 3 # index of desired layerinput_shape = model.layers[idx].get_input_shape_at(0) # get the input shape of desired layerlayer_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 pathx = layer_inputfor layer in model.layers[idx:]: x = layer(x)# create the modelnew_model = Model(layer_input, x)
幸运的是,你的模型只有一条分支,我们可以简单地使用for
循环来构建新的模型。然而,对于更复杂的模型,这样做可能并不容易,你可能需要编写更多的代码来构建新模型。