[英]Trained and Loaded Keras Sequential Model is giving different result
我已经训练了一个模型并将其保存在特定的目录中,而训练它可以提供约81%的测试准确性。 我使用了以下命令:
model = Sequential()
model.add(Embedding(max_features, 128, input_length=max_len))
model.add(SpatialDropout1D(0.3))
model.add(GaussianNoise(0.2))
model.add(LSTM(128 , dropout_W=0.3, dropout_U=0.3, return_sequences=False))
model.add(LSTM(56, dropout_W = 0.4, dropout_U=0.4))
model.add(Dense(1, W_regularizer=l2(0.2)))
model.add(Activation('sigmoid'))
model.summary()
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.00)
model.compile(loss='binary_crossentropy', optimizer=adam,metrics = ['accuracy'] )
model_history = model.fit(x, y=y, batch_size=128, epochs=2, verbose=1,validation_split = 0.2)
model_json = model.to_json()
with open("C:/Users/twelve_user/Downloads/model3.json", "w") as json_file:
json_file.write(model_json)
model.save_weights("C:/Users/twelve_user/Downloads/weights_model3.h5")
print("Saved model to disk")
predictions = model.predict(testx)
但是每当我尝试在不同的python脚本中加载相同的模型时,准确性就会下降,即76%。 有时我会像未经训练的模型一样获得随机精度。 下面给出了我用于加载的命令:
json_file = open('C:/Users/twelve_user/Downloads/model3.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
model = model_from_json(loaded_model_json)
model.load_weights("C:/Users/twelve_user/Downloads/weights_mode3.h5")
print("Loaded model from disk")
这怎么可能? 训练后的模型和加载的模型的结果都应该相同。 由于我是Keras的新手,所以无法了解我错了。
感谢您的帮助! 任何帮助,将不胜感激。
这是因为权重是用随机值初始化的,请在此处找到代码段和详细信息
这很可能是因为您仅保存了模型结构和模型权重。 您不保存优化器或培训配置的状态。 如果要完全相同的模型,请使用keras函数model.save
。
另请查看此常见问题解答以获取更多信息。
范例程式码
predictions_before = model.predict(testx)
model.save('model3.h5')
del model
model = load_model('model3.h5')
predictions_after = model.predict(testx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.