我没有找到这个问题的决定性答案,所以我把它张贴在这里。我创建了一个带有自定义层的 Keras 模型,并在分类任务上对其进行了训练,该模型以大约 65% 的准确率获得了完全令人满意的性能。然而,在保存并重新加载后,性能完全下降到大约 25%,这类似于完全随机的预测。我一直在尝试不同的技巧(修复 numpy 和 tf 后端的种子,使用替代库函数 keras.models.save_model,酸洗),但没有一个能达到令人满意的程度。
我使用的代码如下。我正在使用额外的自定义“GraphConv”层(参见 Kipf & Well,2017):
data_shape = (np.shape(Xp)[1], 2)
num_classes = 4
in_x = Input(shape=data_shape)
x = GraphConv(filters=25, adjacency_matrix=A[0], input_features=2)(in_x)
x = Activation('relu')(x)
x = MaxPooling1D(pool_size=4, padding='same')(x)
x = GraphConv(filters=16, adjacency_matrix=A[2], input_features=25)(x)
x = Activation('relu')(x)
x = MaxPooling1D(pool_size=4, padding='same')(x)
x = Flatten()(x)
x = Dense(10)(x)
x = Activation('relu')(x)
x = Dense(50)(x)
x = Activation('relu')(x)
out_x = Dense(num_classes, activation='softmax')(x)
model = Model(inputs=in_x, outputs=out_x)
model.compile(loss=keras.losses.categorical_crossentropy, optimizer='adam', metrics=['accuracy'])
model.summary()
h = model.fit(X_train, Y_train, epochs=10, batch_size=250, verbose=1, validation_split=0.2)
在训练并达到约 65% 的准确率后,我用
保存模型model.save("test_model")
基于保存的模型,我创建了一个新的
test = keras.models.load_model("test_model", custom_objects={'GraphConv': GraphConv})
现在评估和比较我为 vanilla 模型获得的性能:
model.evaluate(X_train, Y_train)
4000/4000 [==============================] - 1s 151us/step
[0.8065748610496521, 0.6245]
对于新的测试模型:
test.evaluate(X_train, Y_train)
4000/4000 [==============================] - 1s 204us/step
[7.069425365447998, 0.25375]
我一直在思考是不是自定义层的一些参数没有正确保存,或者两个模型的权重不一样。但是经过一些测试和比较model.get_weights()和test.get_weights()以及model.layers和test.layers中的参数,我只能确认它们对于两个模型是相同的。
所以在这一点上,我完全不知道如何解决这个问题。
非常感谢我收到的任何建议!