Keras在网络中间层输入并获取最终输出

我的模型是一个简单的全连接网络,像这样:

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循环来构建新的模型。然而,对于更复杂的模型,这样做可能并不容易,你可能需要编写更多的代码来构建新模型。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注