コード例 #1
0
    def train_model(self, x_train, y_train, x_val, y_val):
        self.model.compile(loss='binary_crossentropy',
                           optimizer='adam',
                           metrics=['accuracy'])
        self.model.summary()

        # File used to save model checkpoints
        model_filename = 'chargram-cnn.{0:03d}.hdf5'

        if self.last_finished_epoch > 0:
            self.model = load_model(
                model_filename.format(self.last_finished_epoch - 1))
        elif self.initial_weights_file is not None:
            self.model = load_model(self.initial_weights_file)

        print('Fitting model')
        self.model.fit(x_train,
                       y_train,
                       batch_size=self.batch_size,
                       epochs=self.epochs,
                       validation_data=(x_val, y_val),
                       callbacks=[
                           keras_utils.ModelSaveCallback(model_filename),
                           keras_utils.TqdmProgressCallback()
                       ],
                       verbose=1,
                       initial_epoch=self.last_finished_epoch or 0)
# from keras.models import load_model
# s = reset_tf_session()
# last_finished_epoch = 7
# model = load_model(model_filename.format(last_finished_epoch))

# fit model
model.fit(
    x_train2,
    y_train2,  # prepared data
    batch_size=BATCH_SIZE,
    epochs=EPOCHS,
    callbacks=[
        keras.callbacks.LearningRateScheduler(lr_scheduler),
        LrHistory(),
        keras_utils.TqdmProgressCallback(),
        keras_utils.ModelSaveCallback(model_filename)
    ],
    validation_data=(x_test2, y_test2),
    shuffle=True,
    verbose=0,
    initial_epoch=last_finished_epoch or 0)

# save weights to file
model.save_weights("weights.h5")

# load weights from file (can call without model.fit)
model.load_weights("weights.h5")
"""# Evaluate model"""

# make test predictions
y_pred_test = model.predict_proba(x_test2)