Exemple #1
0
 def __init__(self, current_price, pretrained=False):
     # agent config
     self.state_size = 5  # normalized previous days
     self.cash_in_hand = 6000
     self.total_share = 20
     self.action_size = 3  # [sit, buy, sell]
     self.inventory = []
     self.memory = deque(maxlen=10000)
     self.first_iter = True
     self.initial_price = current_price
     self.writer = SummaryWriter()
     if pretrained:
         self.model = load()
     else:
         self.model = model()
     for i in range(20):
         self.inventory.append(self.initial_price)
     self.gamma = 0.95  # affinity for long term reward
     self.epsilon = 1.0
     self.epsilon_min = 0.01
     self.epsilon_decay = 0.995
     self.learning_rate = 0.001
     self.n_iter = 1
     self.reset_every = 1000
     self.target_model = clone_model(self.model)
     self.target_model.set_weights(self.model.get_weights())
Exemple #2
0
def main(my_model):
    path_results = 'test'
    path_test = 'database/test'

    create_output('output')
    """
        Return the model trained. If don't have already a model trained, will
        going to train the model.
    """
    _model = model(shape=(32, 32, 3),
                   num_classes=4,
                   is_plot=True,
                   path_database='database/{}',
                   epochs=8,
                   my_model=my_model)
    """
        Path 'test/' is create exclusively to save model corrected images.
        After zip the directory 'test/' it is removed.
    """
    create_path(path_results)

    imgs = []
    rotate_img = []
    predicts = []

    labels = {
        '0': 'rotated_left',
        '1': 'rotated_right',
        '2': 'upright',
        '3': 'upside_down',
    }

    for pred, img in zip(_model.predictions, os.listdir(path_test)):
        pred = str(pred)

        imgs.append(img)
        predicts.append(labels.get(pred))

        rotate_img.append(
            rotate(path=path_test,
                   image=img,
                   orientation=pred,
                   save_path=path_results))
    """
        Dump in 'output/': numpy array with corrected orientation faces,
        csv with the labels resulting from the model and the zip files with
        images after corrected orientation process.
    """
    dump_results(imgs, predicts, path_results, rotate_img)
    logging.info('The result is dump in "output/"!')

    remove_path(path_results)
def grad(model, img, detector_mask, matching_true_boxes, class_one_hot, true_boxes, training=True):
	with tf.GradientTape() as tape:
		y_pred = model(img, training)
		loss, sub_loss = yolov2_loss(detector_mask, matching_true_boxes, class_one_hot, true_boxes, y_pred)
	return loss, sub_loss, tape.gradient(loss, model.trainable_variables)
Exemple #4
0
        IR = IR_to_uint8(get_data(IR_))
        FLAIR = to_uint8(get_data(FLAIR_))
        y.append(np.array(get_data(seg_)==label).astype(np.uint8)[None,...])
        X_T1.append(T1[None,...])
        X_IR.append(IR[None,...])
        X_FLAIR.append(FLAIR[None,...])
    X_T1 = np.array(X_T1)
    X_FLAIR = np.array(X_FLAIR)
    X_IR = np.array(X_IR)
    y = np.array(y)
    X_T1_val = histeq(to_uint8(get_data_with_skull_scraping(T1_val)))[None,None,...]
    X_FLAIR_val = to_uint8(get_data(FLAIR_val))[None,None,...]
    X_IR_val = IR_to_uint8(get_data(IR_val))[None,None,...]
    y_val = np.array(get_data(segm_val)==CLASS).astype(np.uint8)[None,...]
    print("STARTING TRAINING...")
    model_ = model()
    model_.compile('adam',dice_loss,[dice_coefficient])
    model_.summary()
    history = model_.fit([X_T1,X_FLAIR,X_IR],y=y,validation_data=([X_T1_val,X_FLAIR_val,X_IR_val],y_val),epochs=EPOCHS,callbacks=[keras.callbacks.ModelCheckpoint(
                      'weights/label'+str(label)+'/Model.val_dice_coefficient={val_dice_coefficient:.5f}.h5',
                      monitor='val_dice_coefficient',
                      verbose=0,
                      save_best_only=True,
                      save_weights_only=False,
                      mode='max',
                      period=1
          )])
print("FINISHED TRAINING...")
print("Saving training history")
with open('history/trainHistoryDict'+str(label)+'.pickle', 'wb') as file_pi:
    pickle.dump(history.history, file_pi)
                    help='Number of epochs (10 by default)')

args = parser.parse_args()

img_dir_path = args.imgs
img_dir_name = os.path.basename(os.path.normpath(img_dir_path))

label_dir_path = args.labels
label_dir_name = os.path.basename(os.path.normpath(label_dir_path))

epochs = args.epochs

imgs = glob.glob(img_dir_path + '/' + img_dir_name + '/*')
labels = glob.glob(label_dir_path + '/' + label_dir_name + '/*')

if len(imgs) != len(labels):
    raise ValueError('Error: Different number of images and labels')

if epochs is None:
    epochs = 10

img_path = imgs[0]
label_path = labels[0]

fcn_model = model()

train_generator = utils.image_generator(img_path, label_path, img_dir_path,
                                        label_dir_path)

utils.train_model(fcn_model, train_generator, len(imgs),
                  epochs).save('model.h5')