keras使用技术技巧

来源:互联网 发布:js 7.62mm狙击步枪 编辑:程序博客网 时间:2024/04/30 04:30

从keras的github issue中学习了几个技巧,记录如下:

(一)return best model

Is the only -- currently existing -- solution, to save the weights to a hdf5 file using ModelCheckpoint and then loading the file again and applying it to a model, which is then returned?

so something similar to this:

best_weights_filepath = './best_weights.hdf5'earlyStopping=kcallbacks.EarlyStopping(monitor='val_loss', patience=10, verbose=1, mode='auto')saveBestModel = kcallbacks.ModelCheckpoint(best_weights_filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')# train modelhistory = model.fit(x_tr, y_tr, batch_size=batch_size, nb_epoch=n_epochs,              verbose=1, validation_data=(x_va, y_va), callbacks=[earlyStopping, saveBestModel])#reload best weightsmodel.load_weights(best_weights_filepath)

(二)recording loss history

class LossHistory(keras.callbacks.Callback):    def on_train_begin(self, logs={}):        self.losses = []    def on_batch_end(self, batch, logs={}):        self.losses.append(logs.get('loss'))model = Sequential()model.add(Dense(10, input_dim=784, init='uniform'))model.add(Activation('softmax'))model.compile(loss='categorical_crossentropy', optimizer='rmsprop')history = LossHistory()model.fit(X_train, Y_train, batch_size=128, nb_epoch=20, verbose=0, callbacks=[history])print history.losses# outputs'''[0.66047596406559383, 0.3547245744908703, ..., 0.25953155204159617, 0.25901699725311789]'''


1 0