Exemplo n.º 1
0
 def train_model(self):
     model = self._build_model()
     history = model.fit(self.train_batches,
                         epochs=10,
                         validation_data=self.test_batches,
                         validation_steps=20)
     plot(history)
     return model
Exemplo n.º 2
0
 def train(self, batch_size=512, epochs=20):
     model = self.build_model()
     # early_stop配合checkpoint使用,可以得到val_loss最小的模型
     early_stop = EarlyStopping(patience=3, verbose=1)
     checkpoint = ModelCheckpoint(os.path.join(self.model_path, 'weights.{epoch:03d}-{val_loss:.3f}.h5'),
                                  verbose=1,
                                  save_best_only=True)
     history = model.fit(self.x_train,
                         self.y_train,
                         batch_size=batch_size,
                         epochs=epochs,
                         verbose=1,
                         callbacks=[checkpoint, early_stop],
                         validation_data=(self.x_test, self.y_test))
     plot(history)
     return model
Exemplo n.º 3
0
    def train(self, weights_only=True, call_back=False):
        model = self._build_model()

        if call_back:
            early_stopping = EarlyStopping(monitor='val_loss', patience=30)
            stamp = 'lstm_%d' % self.n_hidden
            checkpoint_dir = os.path.join(
                self.model_path, 'checkpoints/' + str(int(time.time())) + '/')
            if not os.path.exists(checkpoint_dir):
                os.makedirs(checkpoint_dir)

            bst_model_path = checkpoint_dir + stamp + '.h5'
            if weights_only:
                model_checkpoint = ModelCheckpoint(bst_model_path,
                                                   save_best_only=True,
                                                   save_weights_only=True)
            else:
                model_checkpoint = ModelCheckpoint(bst_model_path,
                                                   save_best_only=True)
            tensor_board = TensorBoard(log_dir=checkpoint_dir +
                                       "logs/{}".format(time.time()))
            callbacks = [early_stopping, model_checkpoint, tensor_board]
        else:
            callbacks = None
        model_trained = model.fit(
            [self.x_train['left'], self.x_train['right']],
            self.y_train,
            batch_size=self.batch_size,
            epochs=self.epochs,
            validation_data=([self.x_val['left'],
                              self.x_val['right']], self.y_val),
            verbose=1,
            callbacks=callbacks)
        if weights_only and not call_back:
            model.save_weights(os.path.join(self.model_path,
                                            'weights_only.h5'))
        elif not weights_only and not call_back:
            model.save(os.path.join(self.model_path, 'model.h5'))
        self._save_config()
        plot(model_trained)
        return model