咸菜Keras ANN

时间:2018-08-16 13:46:35

标签: python python-3.x keras pickle

我正在尝试使用以下代码使用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'))

不幸的是,我得到了

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

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

存储Keras模型的规范方法是使用内置的model.save()方法,该方法会将模型保存到HDF5文件中。

修改您的代码:

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

然后,您可以按以下方式加载它:

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

然后开始重新训练或将模型用于推理。请注意,您也可以使用save_weights()方法仅存储权重。有关完整文档和更多示例,请参见Keras website