简体   繁体   English

咸菜Keras ANN

[英]pickle Keras ANN

I am trying to use this code to fit an ANN using Keras and then pickle it: 我正在尝试使用此代码来使用Keras来适合ANN,然后对其进行腌制:

early_stopping = EarlyStopping(monitor='val_loss', patience=4, mode='auto')
model = Sequential()
model.add(Dense(units=40, kernel_initializer='random_uniform', input_dim=x_train.shape[1], activation='relu'))
model.add(Dense(units=1, kernel_initializer='random_uniform', activation='sigmoid', W_regularizer=reg))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(x=x_train, y=y_train, epochs=1, validation_data=(x_val, y_val), callbacks=[early_stopping])

pickle_file_and_path = 'C:/Bla/DLModel20180816.sav'
pickle.dump(model, open(pickle_file_and_path, 'wb'))

Unfortunately, I get: 不幸的是,我得到:

  pickle.dump(model, open(pickle_file_and_path, 'wb'))
TypeError: can't pickle _thread.RLock objects

Any ideas? 有任何想法吗?

The canonical way of storing Keras models is to use the built-in model.save() method which will save the model into a HDF5 file. 存储Keras模型的规范方法是使用内置的model.save()方法,该方法会将模型保存到HDF5文件中。

Adapting your code: 修改您的代码:

model = Sequential()
model.add(Dense(units=40, kernel_initializer='random_uniform', input_dim=x_train.shape[1], activation='relu'))
model.add(Dense(units=1, kernel_initializer='random_uniform', activation='sigmoid', W_regularizer=reg))
model.compile(loss='binary_crossentropy', optimizer='adam')
model.fit(x=x_train, y=y_train, epochs=1, validation_data=(x_val, y_val), callbacks=[early_stopping])

# Save the model
model.save('./model.h5')

Afterwards, you can load it as follows: 之后,您可以按以下方式加载它:

from keras.models import load_model
model = load_model('./model.h5')

And start retraining or use the model for inference. 并开始重新训练或将模型用于推理。 Note that you can also store the only the weights with the save_weights() method. 请注意,您也可以使用save_weights()方法仅存储权重。 For the full documentation and more examples see the Keras website . 有关完整的文档和更多示例,请参见Keras 网站

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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