首页 > 解决方案 > 在 Keras 中,CNN 层结果与 model.predict 的结果不同

问题描述

history = model.fit(x_spectro_train, y_train_onehot, batch_size=batch_size, epochs=training_epochs, validation_data =(x_spectro_test, y_test_onehot), shuffle=True, callbacks=callbacks_list,class_weight=class_weights, verbose=1)


model=load_model(model_name)
predict_prob_train = model.predict(x_spectro_train,batch_size=batch_size) 


inp = model.input                                           # input placeholder
outputs = [layer.output for layer in model.layers]          # all layer outputs
functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions
layer_outs = [func([x_spectro_train, 0.]) for func in functors] #test mode (0.0), train mode(1.0)

我想保存 CNN 层输出。我想用 CNN 层输出训练 svm 模型(不是概率)

所以我使用了Keras 的代码,如何获取每一层的输出?我看到了结果。

但是我的 CNN 层的结果与 model.predict 的结果不同。我监控了 val 的准确性,保存了最佳模型并加载它。这是我的模型的结构。(下图)

在此处输入图像描述

我预计 layer_outs[13](最后一层)的结果与 predict_prob_train 相同。然而,结果却不同。(如下图)

在此处输入图像描述

为什么结果不一样?

标签: pythontensorflowneural-networkkerasconv-neural-network

解决方案


You have 7 layers after Conv layer (2 of which are Dense). They also learn stuff and they are 'making the decision' of the model output.

Think about it like this: Conv outputs something, that is the input to Dense1 -> Dense2. All those layers are learning simultaneously. So the goal of Dense1 layer is to learn what Conv layer is 'trying to tell it', how to interpret the results of Conv layer. If you input the image to this Dense1 layer and then to Dense2 layer, you won't get the same result (nor correct one). All of those layers are working together to get the correct prediction.

You cannot isolate 1 layer and expect the correct result.


推荐阅读