def on_epoch_end(self, epoch, logs=None): if logs is not None: if logs['val_loss'] < self.max_val_loss: self.max_val_loss = logs['val_loss'] weight_file_name = 'model_weights_best' model_tools.save_network(self.model, weight_file_name) np.save('lossRecord', self.max_val_loss) print("best weights and min loss saved")
def train_model(learning_rate, batch_size, num_epochs, steps_per_epoch, validation_steps, workers, optimizer, weight_file_name): image_hw = 160 image_shape = (image_hw, image_hw, 3) inputs = layers.Input(image_shape) num_classes = 3 # Call fcn_model() output_layer = fcn_model(inputs, num_classes) # Define the Keras model and compile it for training model = models.Model(inputs=inputs, outputs=output_layer) if optimizer == 'Nadam': model.compile(optimizer=keras.optimizers.Adam(learning_rate), loss='categorical_crossentropy') elif optimizer == 'Adam': model.compile(optimizer=keras.optimizers.Nadam(lr=learning_rate, beta_1=0.9, beta_2=0.999, epsilon=1e-08, schedule_decay=0.004), loss='categorical_crossentropy') else: raise RuntimeError('Invalid optimizer type "{}"'.format(optimizer)) # Data iterators for loading the training and validation data train_iter = data_iterator.BatchIteratorSimple(batch_size=batch_size, data_folder=os.path.join( '..', 'data', 'train'), image_shape=image_shape, shift_aug=True) val_iter = data_iterator.BatchIteratorSimple(batch_size=batch_size, data_folder=os.path.join( '..', 'data', 'validation'), image_shape=image_shape) logger_cb = plotting_tools.LoggerPlotter(save_graphs=True) callbacks = [logger_cb] model.fit_generator( train_iter, steps_per_epoch=steps_per_epoch, # the number of batches per epoch, epochs=num_epochs, # the number of epochs to train for, validation_data=val_iter, # validation iterator validation_steps= validation_steps, # the number of batches to validate on callbacks=callbacks, workers=workers) # Save your trained model weights model_tools.save_network(model, weight_file_name)
#logger_cb = plotting_tools.LoggerPlotter() #callbacks = [logger_cb] callbacks = [] model.fit_generator( train_iter, steps_per_epoch=steps_per_epoch, # the number of batches per epoch, epochs=num_epochs, # the number of epochs to train for, validation_data=val_iter, # validation iterator validation_steps= validation_steps, # the number of batches to validate on callbacks=callbacks, workers=workers) weight_file_name = 'model_weights_' + run model_tools.save_network(model, weight_file_name) run_num = 'run_' + run val_with_targ, pred_with_targ = model_tools.write_predictions_grade_set( model, run_num, 'patrol_with_targ', 'evaluation') val_no_targ, pred_no_targ = model_tools.write_predictions_grade_set( model, run_num, 'patrol_non_targ', 'evaluation') val_following, pred_following = model_tools.write_predictions_grade_set( model, run_num, 'following_images', 'evaluation') print( "--------------------------------------------------------------------------------" )
val_with_targ, pred_with_targ) # Sum all the true positives, etc from the three datasets to get a weight for the score true_pos = true_pos1 + true_pos2 + true_pos3 false_pos = false_pos1 + false_pos2 + false_pos3 false_neg = false_neg1 + false_neg2 + false_neg3 weight = true_pos / (true_pos + false_neg + false_pos) #print(weight) # The IoU for the dataset that never includes the hero is excluded from grading final_IoU = (iou1 + iou3) / 2 print("IoU no hero - ", final_IoU) # And the final grade score is final_score = final_IoU * weight print("Final Grade - ", final_score) if final_score > fg: # Save model with best score weight_file_name = str(final_score) + '_' + datetime.now( ).strftime('model_%H_%M_%d_%m_%Y') + '.h5' model_tools.save_network(your_model=model, your_weight_filename=weight_file_name) fg = final_score arr = [fg, final_IoU, weight, weight_file_name] print('Best --- ', fg) print('Data --- ', arr)
def train_net(x): """Trains the network with the suggested hyper-parameters passed in x argument. Returns -final_score as a result to let ski-opt library find the desired minimum, corresponding to the maximum final_score""" learning_rate = x[0] # 0.001 batch_size = x[1] # 32 num_epochs = x[2] # 12 layers_num = x[3] #2 conv_layers_num = x[4] #1 external_features = x[5] #128 internal_features = x[6] #16 conv_features = x[7] #16 print() print("learning_rate", learning_rate) print("batch_size", batch_size) print("num_epochs", num_epochs) print("layers_num", layers_num) print("conv_layers_num", conv_layers_num) print("external_features", external_features) print("internal_features", internal_features) print("conv_features", conv_features) image_hw = 160 image_shape = (image_hw, image_hw, 3) inputs = layers.Input(image_shape) num_classes = 3 # Call fcn_model() output_layer = fcn_model(inputs, num_classes, layers_num, external_features, internal_features, conv_layers_num, conv_features) # Define the Keras model and compile it for training model = models.Model(inputs=inputs, outputs=output_layer) model.compile(optimizer=keras.optimizers.Adam(learning_rate), loss='categorical_crossentropy') # Data iterators for loading the training and validation data train_iter = data_iterator.BatchIteratorSimple(batch_size=batch_size, data_folder=os.path.join( '..', 'data', 'train_combined'), image_shape=image_shape, shift_aug=True) val_iter = data_iterator.BatchIteratorSimple(batch_size=batch_size, data_folder=os.path.join( '..', 'data', 'validation'), image_shape=image_shape) model.fit_generator( train_iter, steps_per_epoch=steps_per_epoch, # the number of batches per epoch, epochs=num_epochs, # the number of epochs to train for, validation_data=val_iter, # validation iterator validation_steps= validation_steps, # the number of batches to validate on workers=workers) run_num = 'run_1' val_with_targ, pred_with_targ = model_tools.write_predictions_grade_set( model, run_num, 'patrol_with_targ', 'sample_evaluation_data') val_no_targ, pred_no_targ = model_tools.write_predictions_grade_set( model, run_num, 'patrol_non_targ', 'sample_evaluation_data') val_following, pred_following = model_tools.write_predictions_grade_set( model, run_num, 'following_images', 'sample_evaluation_data') # Scores for while the quad is following behind the target. true_pos1, false_pos1, false_neg1, iou1 = scoring_utils.score_run_iou( val_following, pred_following) # Scores for images while the quad is on patrol and the target is not # visible true_pos2, false_pos2, false_neg2, iou2 = scoring_utils.score_run_iou( val_no_targ, pred_no_targ) # This score measures how well the neural network can detect the target # from far away true_pos3, false_pos3, false_neg3, iou3 = scoring_utils.score_run_iou( val_with_targ, pred_with_targ) # Sum all the true positives, etc from the three datasets to get a weight # for the score true_pos = true_pos1 + true_pos2 + true_pos3 false_pos = false_pos1 + false_pos2 + false_pos3 false_neg = false_neg1 + false_neg2 + false_neg3 weight = true_pos / (true_pos + false_neg + false_pos) # The IoU for the dataset that never includes the hero is excluded from # grading final_IoU = (iou1 + iou3) / 2 # And the final grade score is final_score = final_IoU * weight weight_file_name = 'model_weights_' + str(final_score) model_tools.save_network(model, weight_file_name) print("Saved", weight_file_name) print("final_score", final_score) print() return -final_score