简体   繁体   English

训练有素的Keras序列模型给出了不同的结果

[英]Trained and Loaded Keras Sequential Model is giving different result

I have trained a model and saved in a particular directory, while training it is giving about 81% testing accuracy. 我已经训练了一个模型并将其保存在特定的目录中,而训练它可以提供约81%的测试准确性。 I have used following commands: 我使用了以下命令:

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)

But whenever I'm trying to load the same model in different python script, the accuracy falling down ie 76%. 但是每当我尝试在不同的python脚本中加载相同的模型时,准确性就会下降,即76%。 and sometimes I'm getting random accuracy like an untrained model. 有时我会像未经训练的模型一样获得随机精度。 commands are given below which i have used for loading: 下面给出了我用于加载的命令:

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")  

How is this possible? 这怎么可能? Both trained and loaded model's result should be the same. 训练后的模型和加载的模型的结果都应该相同。 As i am quite new to Keras, not able to understand where i am wrong. 由于我是Keras的新手,所以无法了解我错了。
Thank you for the help! 感谢您的帮助! Any help would be appreciated. 任何帮助,将不胜感激。

这是因为权重是用随机值初始化的,请在此处找到代码段和详细信息

It is most likely because you only save the model structure and the model weights. 这很可能是因为您仅保存了模型结构和模型权重。 You do not save the state of your optimizer or training configuration. 您不保存优化器或培训配置的状态。 If you want exactly the same model use the keras function model.save . 如果要完全相同的模型,请使用keras函数model.save

Also check this faq for more information. 另请查看常见问题解答以获取更多信息。

Example code 范例程式码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM