使用model.predict输出作为另一个模型

时间:2018-06-13 02:35:33

标签: python-3.x tensorflow neural-network keras deep-learning

我尝试使用model.predict的输出作为另一个模型的输入。 这实际上是出于调试目的,以及为什么我没有使用get_layer.output或使用统一这两个模型的全局模型。

我遇到了这个错误:

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("input_1:0", shape=(?, 10, 10, 2048), dtype=float32) is not an element of this graph.

这是我目前的代码:

我使用以下功能作为瓶颈发电机

def test_model_predictions(params):

        batch_size = params['batch_size'] #params just contains model parameters
        base_model = create_model() #this just creates an instance of Inception model with final layers cutoff
        train,_ = create_generators(params) #creats a generator for image files

        while True:
                for x, y in train:
                        predict1 = base_model.predict(x)

                        yield (predict1, y)




def training_bottleneck():


    bottleneck_train = test_model_predictions(params) #generator 



    def bottleneck_model_1():
        bottleneck_input = Input(shape = (10, 10, 2048))
        x = GlobalAveragePooling2D()(bottleneck_input)
        x = Dense(1024, activation='relu')(x)
        predictions = Dense(params['classes'], activation='softmax')(x)
        model = Model(inputs=bottleneck_input, outputs=predictions)
        return model




    model2 =  bottleneck_model_1()
    model2.compile(optimizer= optimizers.SGD(lr=0.0001, momentum=0.99),
                  loss='categorical_crossentropy', metrics = ['accuracy'])

    print('Starting model training')
    history = model2.fit_generator(bottleneck_train,
    steps_per_epoch = 1000,
    epochs = 85,
    shuffle= False,
    verbose = 2,  )
    return history

有关如何使这项工作的任何线索?

谢谢。

编辑:似乎有些混淆我为什么这样做,所以我会添加更多信息。

我特意使用predict,因为我注意到将model.predict值(瓶颈值)保存到hdf5文件时出现差异,然后将这些值加载到另一个模型(原始模型的后半部分) ),

只是加载整个模型而只是冻结上半部分(不能训练上半部分)。尽管使用相同的超参数,我注意到的差异, 并且基本上是相同的模型是整个模型正确训练和收敛,而加载瓶颈值的模型并没有真正改善。 因此,我试图看到我融合model.predict以节省瓶颈值是导致两个模型之间存在差异的原因。

1 个答案:

答案 0 :(得分:1)

所以基本上你想用一个模型的预测作为第二个模型的输入? 在你的代码中你混淆了Tensors和" normal" python数据结构,由于你必须使用Tensors构建孔计算图,因此无法工作。

我想你想使用"预测"第一个模型,并添加一些其他功能,以使用第二个模型进行预测?在这种情况下,你可以这样做:

from keras.layers import Input, Dense, concatenate
input_1= Input(shape=(32,))
input_2= Input(shape=(64,))
out_1= Dense(48, input_shape=(32,))(input_1) # your model 1
x = concatenate([out_1, input_2]) # stack both feature vectors
x = Dense(1, activation='sigmoid')(x)    # your model 2
model = Model(inputs=[input_1, input_2], outputs=[x]) # if you want the outputs of model 1 you can add the output out1


history = model.fit([x_train, x_meta_train], y_train, ...)
相关问题