Example #1
0
    def train_model(self, X, y, batch_size=1, epochs=10):
        """Train a Convolutional Neural Network to recognize handwritten characters.

        Args:
            X (numpy.ndarray)8: Training data (EMNIST ByClass dataset)
            y (numpy.ndarray): Labels of the training data.
            batch_size (int): How many images the CNN should use at a time.
            epochs (int): How many times the data should be used to train the model.
        """
        self.build_model()
        callbacks.Callback()
        checkpoint = callbacks.ModelCheckpoint(filepath=getcwd() +
                                               'weights.{epoch:02d}.hdf5',
                                               monitor='val_loss',
                                               verbose=0,
                                               save_best_only=False,
                                               save_weights_only=False,
                                               mode='auto',
                                               period=1)
        #self.model.load_weights(filepath=getcwd()+'weights.04.hdf5', by_name=False)
        callbacks.TensorBoard(log_dir=getcwd() + 'weights.{epoch:02d}')
        self.model.fit(X,
                       y,
                       batch_size=batch_size,
                       epochs=epochs,
                       callbacks=[checkpoint])
def train_model(model, epochs, x_test, y_test, x_train, y_train, weights_path,
                log_path, learning_rate):
    """
	Training a model on training data, while evaluating it on the validation set

	Args:
	model: Keras model to train
	epochs: number of epochs the model should be trained for
	x_train: training data
	x_test:  validation data
	y_train: training labels
	y_test:  validation labels 
	weights_path: the filepath of weights of the model, if existant
	log_path: filepath of were to log data about training into
	learning_rate: learning rate used to train the model

	Returns:
	- 
	"""
    adam = optimizers.Adam(lr=learning_rate)
    sdg = optimizers.SGD(lr=learning_rate,
                         momentum=0.0,
                         decay=0.0,
                         nesterov=False)

    model.compile(loss='categorical_crossentropy',
                  optimizer=adam,
                  metrics=['accuracy'])

    if os.path.isfile(weights_path):
        model.load_weights(weights_path, by_name=False)

    cb = callbacks.Callback()
    cb.set_model(model)
    tensorboard = TensorBoard(log_dir=log_path)
    tensorboard.set_model(model)
    checkpoint = ModelCheckpoint(weights_path,
                                 monitor='val_acc',
                                 verbose=1,
                                 save_best_only=False,
                                 mode='max')
    #early_stop = EarlyStopping(monitor='val_loss', patience=5, verbose=0)

    callbacks_list = [checkpoint, cb, tensorboard]

    model.fit(x_train,
              y_train,
              batch_size=256,
              epochs=epochs,
              shuffle=True,
              verbose=2,
              callbacks=callbacks_list,
              validation_data=(x_test, y_test))

    model.save_weights(weights_path)

    score = model.evaluate(x_test, y_test, batch_size=128)
    print(score)
Example #3
0
 def train(self, data, labels, batch_size=128, epochs=2):
     #Il modello viene allenato
     self.getModel()
     callbacks.Callback()
     checkpoint = callbacks.ModelCheckpoint(filepath=getcwd() +
                                            'weights.{epoch:02d}.hdf5',
                                            monitor='val_loss',
                                            verbose=0,
                                            save_best_only=False,
                                            save_weights_only=False,
                                            mode='auto',
                                            period=1)
     # self.model.load_weights(filepath=getcwd()+'weights.10.hdf5', by_name=False)
     self.model.fit(data,
                    labels,
                    batch_size=batch_size,
                    epochs=epochs,
                    callbacks=[checkpoint])
     print(checkpoint)
Example #4
0
# print(Counter(X_train))
print("---" * 80)
c = 1
for an in Counter(ans):
    if c <= 6:
        print(an)
    c += 1
c = 1
for an in Counter(SP):
    if c <= 1:
        print("SP:", an)
    c += 1
# print(len(SP))
# print(len(ans))
# print(len(X_train))
callbacks.Callback()
callbacks.History()
callbacks.TensorBoard(log_dir='./logs',
                      histogram_freq=0,
                      batch_size=32,
                      write_graph=True,
                      write_grads=False,
                      write_images=False,
                      embeddings_freq=0,
                      embeddings_layer_names=None,
                      embeddings_metadata=None,
                      embeddings_data=None,
                      update_freq='epoch')
callbacks.ReduceLROnPlateau(monitor='val_loss',
                            factor=0.1,
                            patience=10,