Exemplo n.º 1
0
def srgan_model(features, labels, mode, params):
    del params
    global load_flag

    if mode == tf.estimator.ModeKeys.PREDICT:
        net_g_test = SRGAN_g(features, is_train=False)

        predictions = {'generated_images': net_g_test.outputs}

        return tf.estimator.EstimatorSpec(mode, predictions=predictions)

    net_g = SRGAN_g(features, is_train=True)
    net_d, logits_real = SRGAN_d(labels, is_train=True)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True)

    t_target_image_224 = tf.image.resize_images(labels,
                                                size=[224, 224],
                                                method=0,
                                                align_corners=False)
    t_predict_image_224 = tf.image.resize_images(
        net_g.outputs, size=[224, 224], method=0,
        align_corners=False)  # resize_generate_image_for_vgg

    net_vgg, vgg_target_emb = Vgg19_simple_api((t_target_image_224 + 1) / 2)
    _, vgg_predict_emb = Vgg19_simple_api((t_predict_image_224 + 1) / 2)

    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs, labels, is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + vgg_loss + g_gan_loss

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(config.TRAIN.lr_init, trainable=False)

    # SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v, beta1=config.TRAIN.beta1) \
        .minimize(g_loss, var_list=g_vars, global_step=tf.train.get_global_step())
    d_optim = tf.train.AdamOptimizer(lr_v, beta1=config.TRAIN.beta1) \
        .minimize(d_loss, var_list=d_vars, global_step=tf.train.get_global_step())

    joint_op = tf.group([g_optim, d_optim])

    load_vgg(net_vgg)

    return tf.estimator.EstimatorSpec(mode, loss=g_loss, train_op=joint_op)
Exemplo n.º 2
0
def g_init_model(features, labels, mode, params):
    del params

    if mode == tf.estimator.ModeKeys.PREDICT:
        net_g_test = SRGAN_g(features, is_train=False)

        predictions = {'generated_images': net_g_test.outputs}

        return tf.contrib.tpu.TPUEstimatorSpec(mode, predictions=predictions)

    net_g = SRGAN_g(features, is_train=True)
    _ = SRGAN_d(labels, is_train=True)

    mse_loss = tl.cost.mean_squared_error(net_g.outputs, labels, is_mean=True)

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(config.TRAIN.lr_init, trainable=False)

    g_optimizer = tf.train.AdamOptimizer(lr_v, beta1=config.TRAIN.beta1)
    g_optimizer = tf.contrib.tpu.CrossShardOptimizer(g_optimizer)
    init_ops = g_optimizer.minimize(mse_loss,
                                    var_list=g_vars,
                                    global_step=tf.train.get_global_step())

    return tf.contrib.tpu.TPUEstimatorSpec(mode,
                                           loss=mse_loss,
                                           train_op=init_ops)
Exemplo n.º 3
0
def train():
    ## create folders to save result images and trained model
    save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###====================== PRE-LOAD DATA ===========================###
    train_hr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.hr_img_path,
                                regx='.*.png',
                                printable=False))
    train_lr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.lr_img_path,
                                regx='.*.png',
                                printable=False))
    valid_hr_img_list = sorted(
        tl.files.load_file_list(path=config.VALID.hr_img_path,
                                regx='.*.png',
                                printable=False))
    valid_lr_img_list = sorted(
        tl.files.load_file_list(path=config.VALID.lr_img_path,
                                regx='.*.png',
                                printable=False))

    ## If your machine have enough memory, please pre-load the whole train set.
    train_hr_imgs = tl.vis.read_images(train_hr_img_list,
                                       path=config.TRAIN.hr_img_path,
                                       n_threads=32)
    # for im in train_hr_imgs:
    #     print(im.shape)
    # valid_lr_imgs = tl.vis.read_images(valid_lr_img_list, path=config.VALID.lr_img_path, n_threads=32)
    # for im in valid_lr_imgs:
    #     print(im.shape)
    # valid_hr_imgs = tl.vis.read_images(valid_hr_img_list, path=config.VALID.hr_img_path, n_threads=32)
    # for im in valid_hr_imgs:
    #     print(im.shape)
    # exit()

    ###========================== DEFINE MODEL ============================###
    ## train inference
    t_image = tf.placeholder('float32', [batch_size, 96, 96, 3],
                             name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder('float32', [batch_size, 384, 384, 3],
                                    name='t_target_image')

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    t_target_image_224 = tf.image.resize_images(
        t_target_image, size=[224, 224], method=0, align_corners=False
    )  # resize_target_image_for_vgg # http://tensorlayer.readthedocs.io/en/latest/_modules/tensorlayer/layers.html#UpSampling2dLayer
    t_predict_image_224 = tf.image.resize_images(
        net_g.outputs, size=[224, 224], method=0,
        align_corners=False)  # resize_generate_image_for_vgg

    net_vgg, vgg_target_emb = Vgg19_simple_api((t_target_image_224 + 1) / 2,
                                               reuse=False)
    _, vgg_predict_emb = Vgg19_simple_api((t_predict_image_224 + 1) / 2,
                                          reuse=True)

    ## test inference
    net_g_test = SRGAN_g(t_image, is_train=False, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs,
                                          t_target_image,
                                          is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + vgg_loss + g_gan_loss

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
        mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    tl.layers.initialize_global_variables(sess)
    if tl.files.load_and_assign_npz(
            sess=sess,
            name=checkpoint_dir + '/g_{}.npz'.format(tl.global_flag['mode']),
            network=net_g) is None:
        tl.files.load_and_assign_npz(
            sess=sess,
            name=checkpoint_dir +
            '/g_{}_init.npz'.format(tl.global_flag['mode']),
            network=net_g)
    tl.files.load_and_assign_npz(sess=sess,
                                 name=checkpoint_dir +
                                 '/d_{}.npz'.format(tl.global_flag['mode']),
                                 network=net_d)

    ###============================= LOAD VGG ===============================###
    vgg19_npy_path = "vgg19.npy"
    if not os.path.isfile(vgg19_npy_path):
        print(
            "Please download vgg19.npz from : https://github.com/machrisaa/tensorflow-vgg"
        )
        exit()
    npz = np.load(vgg19_npy_path, encoding='latin1').item()

    params = []
    for val in sorted(npz.items()):
        W = np.asarray(val[1][0])
        b = np.asarray(val[1][1])
        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
        params.extend([W, b])
    tl.files.assign_params(sess, params, net_vgg)
    # net_vgg.print_params(False)
    # net_vgg.print_layers()

    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    sample_imgs = train_hr_imgs[0:batch_size]
    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set
    sample_imgs_384 = tl.prepro.threading_data(sample_imgs,
                                               fn=crop_sub_imgs_fn,
                                               is_random=False)
    print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(),
          sample_imgs_384.max())
    sample_imgs_96 = tl.prepro.threading_data(sample_imgs_384,
                                              fn=downsample_fn)
    print('sample LR sub-image:', sample_imgs_96.shape, sample_imgs_96.min(),
          sample_imgs_96.max())
    tl.vis.save_images(sample_imgs_96, [ni, ni],
                       save_dir_ginit + '/_train_sample_96.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni],
                       save_dir_ginit + '/_train_sample_384.png')
    tl.vis.save_images(sample_imgs_96, [ni, ni],
                       save_dir_gan + '/_train_sample_96.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni],
                       save_dir_gan + '/_train_sample_384.png')

    ###========================= initialize G ====================###
    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update G
            errM, _ = sess.run([mse_loss, g_optim_init], {
                t_image: b_imgs_96,
                t_target_image: b_imgs_384
            })
            print("Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f " %
                  (epoch, n_epoch_init, n_iter, time.time() - step_time, errM))
            total_mse_loss += errM
            n_iter += 1
        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (
            epoch, n_epoch_init, time.time() - epoch_time,
            total_mse_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: sample_imgs_96
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni],
                               save_dir_ginit + '/train_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(net_g.all_params,
                              name=checkpoint_dir +
                              '/g_{}_init.npz'.format(tl.global_flag['mode']),
                              sess=sess)

    ###========================= train GAN (SRGAN) =========================###
    for epoch in range(0, n_epoch + 1):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update D
            errD, _ = sess.run([d_loss, d_optim], {
                t_image: b_imgs_96,
                t_target_image: b_imgs_384
            })
            ## update G
            errG, errM, errV, errA, _ = sess.run(
                [g_loss, mse_loss, vgg_loss, g_gan_loss, g_optim], {
                    t_image: b_imgs_96,
                    t_target_image: b_imgs_384
                })
            print(
                "Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f vgg: %.6f adv: %.6f)"
                % (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG,
                   errM, errV, errA))
            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: sample_imgs_96
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni],
                               save_dir_gan + '/train_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(net_g.all_params,
                              name=checkpoint_dir +
                              '/g_{}.npz'.format(tl.global_flag['mode']),
                              sess=sess)
            tl.files.save_npz(net_d.all_params,
                              name=checkpoint_dir +
                              '/d_{}.npz'.format(tl.global_flag['mode']),
                              sess=sess)
def train():
    ## create folders to save result images and trained model
    save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###====================== PRE-LOAD DATA ===========================###
    train_hr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.hr_img_path,
                                regx='.*.png',
                                printable=False))
    train_lr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.lr_img_path,
                                regx='.*.png',
                                printable=False))

    ## If your machine have enough memory, please pre-load the whole train set.
    print("reading images")

    train_hr_imgs = []  #[None] * len(train_hr_img_list)

    train_lr_imgs = []  #[None] * len(train_hr_img_list)
    #sess = tf.Session()
    for img__ in train_lr_img_list:

        image_loaded = scipy.misc.imread(
            os.path.join(config.TRAIN.hr_img_path, img__))
        image_loaded = image_loaded.reshape(
            (image_loaded.shape[0], image_loaded.shape[1], 1))
        print(image_loaded.shape)
        image_loaded = image_loaded / (np.max(image_loaded) + 1)
        train_hr_imgs.append(image_loaded)
        aug1, aug2, aug3 = data_augment(image_loaded, is_mask=True)
        train_hr_imgs.append(aug1)
        train_hr_imgs.append(aug2)
        train_hr_imgs.append(aug3)

    for img__ in train_lr_img_list:

        image_loaded = scipy.misc.imread(
            os.path.join(config.TRAIN.lr_img_path, img__))
        image_loaded = image_loaded.reshape(
            (image_loaded.shape[0], image_loaded.shape[1], 1))
        print(image_loaded.shape)
        image_loaded = image_loaded / (np.max(image_loaded) + 1)
        train_lr_imgs.append(image_loaded)
        aug1, aug2, aug3 = data_augment(image_loaded, is_mask=False)
        train_lr_imgs.append(aug1)
        train_lr_imgs.append(aug2)
        train_lr_imgs.append(aug3)

    #shuffle lists
    random.seed(2018)
    shuffle(train_hr_imgs)
    random.seed(2018)
    shuffle(train_lr_imgs)

    ###========================== DEFINE MODEL ============================###
    ## train inference

    t_image = tf.placeholder('float32', [batch_size, 128, 128, 1],
                             name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder(
        'float32', [batch_size, 128, 128, 1], name='t_target_image'
    )  # may have to convert 224x224x1 into 224x224x3, with channel 1 & 2 as 0. May have to have separate place-holder ?

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    #net_g = u_net(t_image, is_train=True, reuse=False)

    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    t_target_image_224 = tf.image.resize_images(
        t_target_image, size=[224, 224], method=0, align_corners=False
    )  # resize_target_image_for_vgg # http://tensorlayer.readthedocs.io/en/latest/_modules/tensorlayer/layers.html#UpSampling2dLayer
    t_predict_image_224 = tf.image.resize_images(
        net_g.outputs, size=[224, 224], method=0,
        align_corners=False)  # resize_generate_image_for_vgg

    ## test inference
    net_g_test = SRGAN_g(t_image, is_train=False, reuse=True)
    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-4 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    w_t_target_image = t_target_image
    weight = 3
    weights = tf.multiply(tf.cast(weight, tf.float32),
                          tf.cast(w_t_target_image, tf.float32)) + 1

    mse_loss = tf.reduce_mean(
        tf.losses.mean_squared_error(w_t_target_image,
                                     net_g.outputs,
                                     weights=weights))

    bce_loss = tf.reduce_mean(
        tf.nn.sigmoid_cross_entropy_with_logits(labels=t_target_image,
                                                logits=net_g.outputs))
    vgg_loss = 0  #2e-3 * tl.cost.mean_squared_error(vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True) #-6

    g_loss = mse_loss + g_gan_loss  #+vgg_loss

    d_loss1_summary = tf.summary.scalar('Disciminator logits_real loss',
                                        d_loss1)
    d_loss2_summary = tf.summary.scalar('Disciminator logits_fake loss',
                                        d_loss2)
    d_loss_summary = tf.summary.scalar('Disciminator total loss', d_loss)

    g_gan_loss_summary = tf.summary.scalar('Generator GAN loss', g_gan_loss)
    mse_loss_summary = tf.summary.scalar('Generator MSE loss', mse_loss)
    vgg_loss_summary = tf.summary.scalar('Generator VGG loss', vgg_loss)
    g_loss_summary = tf.summary.scalar('Generator total loss', g_loss)

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)  #SRGAN_g
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
        mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    tl.layers.initialize_global_variables(sess)

    # restore model from .ckpt
    saver = tf.train.Saver()
    saver.restore(sess, checkpoint_dir + '/model_init_srgan_35.ckpt')

    #tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_srgan_20.npz', network=net_g)
    #init of generator
    #tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_srgan_35_init.npz', network=net_g)
    #ac dis
    #tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/d_srgan_25.npz', network=net_d)

    ###============================= LOAD VGG ===============================###
    #    vgg19_npy_path = "vgg19.npy"
    #    if not os.path.isfile(vgg19_npy_path):
    #        print("Please download vgg19.npz from : https://github.com/machrisaa/tensorflow-vgg")
    #        exit()
    #    npz = np.load(vgg19_npy_path, encoding='latin1').item()
    #
    #    params = []
    #    for val in sorted(npz.items()):
    #        W = np.asarray(val[1][0])
    #        b = np.asarray(val[1][1])
    #        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
    #        params.extend([W, b])
    #    tl.files.assign_params(sess, params, net_vgg)
    #    # net_vgg.print_params(False)
    #    # net_vgg.print_layers()
    #
    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    sample_imgs = train_hr_imgs[0:batch_size]

    sample_imgs1 = train_lr_imgs[0:batch_size]

    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set

    print("sample_imgs size:", len(sample_imgs), sample_imgs[0].shape)

    sample_imgs_384 = sample_imgs  #tl.prepro.threading_data(sample_imgs, fn=crop_sub_imgs_fn, is_random=False)
    #print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(), sample_imgs_384.max())
    sample_imgs_96 = sample_imgs1  #tl.prepro.threading_data(sample_imgs_384, fn=downsample_fn)
    #Ankit print list of input images
    print(sample_imgs_96)
    ###========================= initialize G ===================mse#
    merged_summary_initial_G = tf.summary.merge([mse_loss_summary])
    summary_intial_G_writer = tf.summary.FileWriter("./log/train/initial_G")

    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    count = 0
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.

        intial_MSE_G_summary_per_epoch = []

        train_hr = []
        train_lr = []
        for idx in range(0, len(train_hr_imgs) - 4, batch_size):
            step_time = time.time()
            train_hr = train_hr_imgs[idx:idx + batch_size]
            train_lr = train_lr_imgs[idx:idx + batch_size]
            ## update G
            errM, _, mse_summary_initial_G, out1 = sess.run(
                [
                    mse_loss, g_optim_init, merged_summary_initial_G,
                    net_g.outputs
                ], {
                    t_image: train_lr,
                    t_target_image: train_hr
                })
            print("Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f " %
                  (epoch, n_epoch_init, n_iter, time.time() - step_time, errM))

            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(mse_summary_initial_G)

            intial_G_summaries = {}
            for val in summary_pb.value:
                # Assuming all summaries are scalars.
                intial_G_summaries[val.tag] = val.simple_value

            intial_MSE_G_summary_per_epoch.append(
                intial_G_summaries['Generator_MSE_loss'])

            total_mse_loss += errM
            n_iter += 1
        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (
            epoch, n_epoch_init, time.time() - epoch_time,
            total_mse_loss / n_iter)
        print(log)

        summary_intial_G_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_Initial_MSE_loss per epoch",
                                 simple_value=np.mean(
                                     intial_MSE_G_summary_per_epoch)),
            ]), (epoch))

        ## quick evaluation on train set
        #if (epoch != 0) and (epoch % 10 == 0):
        out = sess.run(
            net_g_test.outputs,
            {t_image: sample_imgs_96
             })  #; print('gen sub-image:', out.shape, out.min(), out.max())
        print("[*] save images")
        tl.vis.save_images(out, [2, 4],
                           save_dir_ginit + '/train_%d.png' % epoch)
        tl.vis.save_images(np.asarray(sample_imgs_384), [2, 4],
                           save_dir_ginit + '/train_gt_%d.png' % epoch)
        tl.vis.save_images(np.asarray(sample_imgs_96), [2, 4],
                           save_dir_ginit + '/train_in_%d.png' % epoch)
        tl.vis.save_images(out1, [2, 4],
                           save_dir_ginit + '/train_out_%d.png' % epoch)

        # save model as .ckpt
        saver = tf.train.Saver(tf.global_variables())
        save_path = saver.save(
            sess, checkpoint_dir +
            "/model_init_{}_{}.ckpt".format(tl.global_flag['mode'], epoch))
    ###========================= train GAN (SRGAN) =========================###

    merged_summary_discriminator = tf.summary.merge(
        [d_loss1_summary, d_loss2_summary, d_loss_summary])
    summary_discriminator_writer = tf.summary.FileWriter(
        "./log/train/discriminator")

    merged_summary_generator = tf.summary.merge([
        g_gan_loss_summary, mse_loss_summary, vgg_loss_summary, g_loss_summary
    ])
    summary_generator_writer = tf.summary.FileWriter("./log/train/generator")

    learning_rate_writer = tf.summary.FileWriter("./log/train/learning_rate")

    count = 0
    for epoch in range(0, n_epoch + 1):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)

            learning_rate_writer.add_summary(
                tf.Summary(value=[
                    tf.Summary.Value(tag="Learning_rate per epoch",
                                     simple_value=(lr_init * new_lr_decay)),
                ]), (epoch))

        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

            learning_rate_writer.add_summary(
                tf.Summary(value=[
                    tf.Summary.Value(tag="Learning_rate per epoch",
                                     simple_value=lr_init),
                ]), (epoch))

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.

        loss_per_batch = []

        d_loss1_summary_per_epoch = []
        d_loss2_summary_per_epoch = []
        d_loss_summary_per_epoch = []

        g_gan_loss_summary_per_epoch = []
        mse_loss_summary_per_epoch = []
        vgg_loss_summary_per_epoch = []
        g_loss_summary_per_epoch = []

        img_target = []
        img_in = []
        for idx in range(0, len(train_hr_imgs) - 4, batch_size):
            step_time = time.time()
            ## update D
            img_in = train_lr_imgs[idx:idx + batch_size]
            img_target = train_hr_imgs[idx:idx + batch_size]
            errD, _, discriminator_summary = sess.run(
                [d_loss, d_optim, merged_summary_discriminator], {
                    t_image: img_in,
                    t_target_image: img_target
                })

            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(discriminator_summary)

            discriminator_summaries = {}
            for val in summary_pb.value:
                # Assuming all summaries are scalars.
                discriminator_summaries[val.tag] = val.simple_value

            d_loss1_summary_per_epoch.append(
                discriminator_summaries['Disciminator_logits_real_loss'])
            d_loss2_summary_per_epoch.append(
                discriminator_summaries['Disciminator_logits_fake_loss'])
            d_loss_summary_per_epoch.append(
                discriminator_summaries['Disciminator_total_loss'])

            ## update G- GMV
            errG, errM, errA, _, generator_summary = sess.run(
                [
                    g_loss, mse_loss, g_gan_loss, g_optim,
                    merged_summary_generator
                ], {
                    t_image: img_in,
                    t_target_image: img_target
                })

            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(generator_summary)
            #print("generator_summary", summary_pb, type(summary_pb))

            generator_summaries = {}
            for val in summary_pb.value:
                # Assuming all summaries are scalars.
                generator_summaries[val.tag] = val.simple_value

            #print("generator_summaries:", generator_summaries)

            g_gan_loss_summary_per_epoch.append(
                generator_summaries['Generator_GAN_loss'])
            mse_loss_summary_per_epoch.append(
                generator_summaries['Generator_MSE_loss'])
            vgg_loss_summary_per_epoch.append(
                generator_summaries['Generator_VGG_loss'])
            g_loss_summary_per_epoch.append(
                generator_summaries['Generator_total_loss'])

            print(
                "Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f adv: %.6f)"
                % (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG,
                   errM, errA))
            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter)
        print(log)

        #####
        #
        # logging discriminator summary
        #
        ######

        # logging per epcoch summary of logit_real_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_logits_real_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss1_summary_per_epoch)),
            ]), (epoch))

        # logging per epcoch summary of logit_fake_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_logits_fake_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss2_summary_per_epoch)),
            ]), (epoch))

        # logging per epcoch summary of total_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_total_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss_summary_per_epoch)),
            ]), (epoch))

        #####
        #
        # logging generator summary
        #
        ######

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_GAN_loss per epoch",
                                 simple_value=np.mean(
                                     g_gan_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_MSE_loss per epoch",
                                 simple_value=np.mean(
                                     mse_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_VGG_loss per epoch",
                                 simple_value=np.mean(
                                     vgg_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_total_loss per epoch",
                                 simple_value=np.mean(
                                     g_loss_summary_per_epoch)),
            ]), (epoch))

        ## quick evaluation on train set
        #if (epoch != 0) and (epoch % 10 == 0):
        out = sess.run(
            net_g_test.outputs,
            {t_image: sample_imgs_96
             })  #; print('gen sub-image:', out.shape, out.min(), out.max())
        print("[*] save images")
        tl.vis.save_images(out, [2, 4], save_dir_gan + '/train_%d.png' % epoch)
        tl.vis.save_images(np.asarray(sample_imgs_384), [2, 4],
                           save_dir_gan + '/train_gt_%d.png' % epoch)
        tl.vis.save_images(np.asarray(sample_imgs_96), [2, 4],
                           save_dir_gan + '/train_in_%d.png' % epoch)

        ## save model
        if (epoch % 5 == 0):

            # save model as .ckpt
            saver = tf.train.Saver(tf.global_variables())
            save_path = saver.save(
                sess, checkpoint_dir +
                "/model_{}_{}.ckpt".format(tl.global_flag['mode'], epoch))
Exemplo n.º 5
0
def train(train_lr_imgs, train_hr_imgs):
    ## create folders to save result images and trained model
    checkpoint_dir = "models_checkpoints"
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###========================== DEFINE MODEL ============================###
    ## train inference
    t_image = tf.placeholder(dtype='float32',
                             shape=(batch_size, 512, 512, 1),
                             name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder(dtype='float32',
                                    shape=(batch_size, 512, 512, 1),
                                    name='t_target_image')

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    t_target_image_224 = tf.image.resize_images(
        t_target_image, size=[224, 224], method=0, align_corners=False
    )  # resize_target_image_for_vgg # http://tensorlayer.readthedocs.io/en/latest/_modules/tensorlayer/layers.html#UpSampling2dLayer
    t_predict_image_224 = tf.image.resize_images(
        net_g.outputs, size=[224, 224], method=0,
        align_corners=False)  # resize_generate_image_for_vgg
    net_vgg, vgg_target_emb = Vgg19_simple_api(input=(t_target_image_224 + 1) /
                                               2,
                                               reuse=False)
    _, vgg_predict_emb = Vgg19_simple_api(input=(t_predict_image_224 + 1) / 2,
                                          reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs,
                                          t_target_image,
                                          is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + vgg_loss + g_gan_loss

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
        mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    tl.layers.initialize_global_variables(sess)
    if tl.files.load_and_assign_npz(
            sess=sess,
            name=checkpoint_dir + '/g_{}.npz'.format(tl.global_flag['mode']),
            network=net_g) is False:
        tl.files.load_and_assign_npz(
            sess=sess,
            name=checkpoint_dir +
            '/g_{}_init.npz'.format(tl.global_flag['mode']),
            network=net_g)
    tl.files.load_and_assign_npz(sess=sess,
                                 name=checkpoint_dir +
                                 '/d_{}.npz'.format(tl.global_flag['mode']),
                                 network=net_d)

    ###============================= LOAD VGG ===============================###
    vgg19_npy_path = "vgg19.npy"
    npz = np.load(vgg19_npy_path, encoding='latin1').item()

    params = []
    for val in sorted(npz.items()):
        W = np.asarray(val[1][0])
        b = np.asarray(val[1][1])
        if val[0] == 'conv1_1':
            W = np.mean(W, axis=2)
            W = W.reshape((3, 3, 1, 64))
        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
        params.extend([W, b])

    tl.files.assign_params(sess, params, net_vgg)

    ###============================= TRAINING ===============================###

    ###========================= initialize G ====================###
    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    start_time = time.time()
    for epoch in range(0, n_epoch_init):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        step_time = None
        for idx in range(0, len(train_hr_imgs), batch_size):
            if idx % 1000 == 0: step_time = time.time()
            b_imgs_hr = train_hr_imgs[idx:idx + batch_size]
            b_imgs_lr = train_lr_imgs[idx:idx + batch_size]
            b_imgs_hr = np.asarray(b_imgs_hr).reshape(
                (batch_size, 512, 512, 1))
            b_imgs_lr = np.asarray(b_imgs_lr).reshape(
                (batch_size, 512, 512, 1))

            ## update G
            errM, _ = sess.run([mse_loss, g_optim_init], {
                t_image: b_imgs_lr,
                t_target_image: b_imgs_hr
            })

            if idx % 1000 == 0:
                print("Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f " %
                      (epoch, n_epoch_init, n_iter, time.time() - step_time,
                       errM))
                tl.files.save_npz(
                    net_g.all_params,
                    name=checkpoint_dir +
                    '/g_{}_init.npz'.format(tl.global_flag['mode']),
                    sess=sess)

            total_mse_loss += errM
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (
            epoch, n_epoch_init, time.time() - epoch_time,
            total_mse_loss / n_iter)
        print(log)

        ## save model
        tl.files.save_npz(net_g.all_params,
                          name=checkpoint_dir +
                          '/g_{}_init.npz'.format(tl.global_flag['mode']),
                          sess=sess)
    print("G init took: %4.4fs" % (time.time() - start_time))

    ###========================= train GAN (SRGAN) =========================###
    start_time = time.time()
    epoch_losses = defaultdict(list)
    iter_losses = defaultdict(list)

    for epoch in range(0, n_epoch):
        ## update learning rate
        if epoch != 0 and decay_every != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        step_time = None
        for idx in range(0, len(train_hr_imgs), batch_size):
            if idx % 1000 == 0: step_time = time.time()
            b_imgs_hr = train_hr_imgs[idx:idx + batch_size]
            b_imgs_lr = train_lr_imgs[idx:idx + batch_size]
            b_imgs_hr = np.asarray(b_imgs_hr).reshape(
                (batch_size, 512, 512, 1))
            b_imgs_lr = np.asarray(b_imgs_lr).reshape(
                (batch_size, 512, 512, 1))

            ## update D
            errD, _ = sess.run([d_loss, d_optim], {
                t_image: b_imgs_lr,
                t_target_image: b_imgs_hr
            })
            ## update G
            errG, errM, errV, errA, _ = sess.run(
                [g_loss, mse_loss, vgg_loss, g_gan_loss, g_optim], {
                    t_image: b_imgs_lr,
                    t_target_image: b_imgs_hr
                })

            if idx % 1000 == 0:
                print(
                    "Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f vgg: %.6f adv: %.6f)"
                    % (epoch, n_epoch, n_iter, time.time() - step_time, errD,
                       errG, errM, errV, errA))
                tl.files.save_npz(net_g.all_params,
                                  name=checkpoint_dir +
                                  '/g_{}.npz'.format(tl.global_flag['mode']),
                                  sess=sess)
                tl.files.save_npz(net_d.all_params,
                                  name=checkpoint_dir +
                                  '/d_{}.npz'.format(tl.global_flag['mode']),
                                  sess=sess)

            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1

            iter_losses['d_loss'].append(errD)
            iter_losses['g_loss'].append(errG)
            iter_losses['mse_loss'].append(errM)
            iter_losses['vgg_loss'].append(errV)
            iter_losses['adv_loss'].append(errA)

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter)
        print(log)
        epoch_losses['d_loss'].append(total_d_loss)
        epoch_losses['g_loss'].append(total_g_loss)

        ## save model
        tl.files.save_npz(net_g.all_params,
                          name=checkpoint_dir +
                          '/g_{}.npz'.format(tl.global_flag['mode']),
                          sess=sess)
        tl.files.save_npz(net_d.all_params,
                          name=checkpoint_dir +
                          '/d_{}.npz'.format(tl.global_flag['mode']),
                          sess=sess)
    print("G train took: %4.4fs" % (time.time() - start_time))

    ## create visualizations for losses from training
    plot_total_losses(epoch_losses)
    plot_iterative_losses(iter_losses)
    for loss, values in epoch_losses.items():
        np.save(checkpoint_dir + "/epoch_" + loss + '.npy', np.asarray(values))
    for loss, values in iter_losses.items():
        np.save(checkpoint_dir + "/iter_" + loss + '.npy', np.asarray(values))
    print("[*] saved losses")
Exemplo n.º 6
0
def train():
    n_epoch_init = 12
    ## create folders to save result images and trained model
    # save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    # save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    # tl.files.exists_or_mkdir(save_dir_ginit)
    # tl.files.exists_or_mkdir(save_dir_gan)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    log_dir = "logs"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###====================== PRE-LOAD DATA ===========================###

    train_hr_img_list = sorted(
        get_synthia_imgs_list(config.VALID.hr_img_path,
                              is_train=True,
                              synthia_dataset=config.TRAIN.hr_img_path))
    valid_hr_img_list = sorted(
        get_synthia_imgs_list(config.VALID.hr_img_path,
                              is_train=False,
                              synthia_dataset=config.TRAIN.hr_img_path))
    print(len(train_hr_img_list))
    print(len(valid_hr_img_list))

    ###========================== DEFINE MODEL ============================###
    ## train inference
    t_input = tf.placeholder(tf.float32,
                             shape=(None, None, None, 1),
                             name='t_input')
    # try with log?
    t_input = tf.log(t_input)

    d_flg = tf.placeholder(tf.bool, name='is_train')

    t_image, t_target_image, t_interpolated = preprocess(t_input)

    net_g_outputs = SRGAN_g(t_image,
                            t_interpolated,
                            is_train=d_flg,
                            reuse=False)

    net_d, logits_real = SRGAN_d(t_target_image, is_train=d_flg, reuse=False)
    _, logits_fake = SRGAN_d(net_g_outputs, is_train=d_flg, reuse=True)

    vgg_model_true = VGG16(vgg16_npy_path)
    vgg_model_gen = VGG16(vgg16_npy_path)

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    # to 3 channels
    y_true_normalized = (t_target_image - tf.reduce_min(t_target_image)) / (
        tf.reduce_max(t_target_image) - tf.reduce_min(t_target_image))
    gen_normalized = (net_g_outputs - tf.reduce_min(net_g_outputs)) / (
        tf.reduce_max(net_g_outputs) - tf.reduce_min(net_g_outputs))

    t_target_image_3ch = tf.concat([y_true_normalized] * 3, 3)
    t_predict_image_3ch = tf.concat([gen_normalized] * 3, 3)

    vgg_model_true.build(t_target_image_3ch)
    true_features = vgg_model_true.conv3_1
    vgg_model_gen.build(t_predict_image_3ch)
    gen_features = vgg_model_gen.conv3_1

    ## test inference
    net_g_test = SRGAN_g(t_image, t_interpolated, is_train=d_flg, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    # d_vgg_loss =  2e-6*tl.cost.mean_squared_error(true_features, gen_features, is_mean=True)

    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-2 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')  # 1e-3 *
    mse_loss = tl.cost.mean_squared_error(net_g_outputs,
                                          t_target_image,
                                          is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        true_features, gen_features, is_mean=True)  # 2e-6 *
    tv_loss = 2e-6 * tf.reduce_mean(tf.square(net_g_outputs[:, :-1, :, :] - net_g_outputs[:, 1:, :, :])) + \
              tf.reduce_mean(tf.square(net_g_outputs[:, :, :-1, :] - net_g_outputs[:, :, 1:, :]))  # 2e-6*

    g_init_loss = mse_loss + vgg_loss  # mse_loss # + vgg_loss + tv_loss
    g_loss = g_gan_loss + mse_loss + vgg_loss  # + mse_loss

    g_vars = tl.layers.get_variables_with_name('G_Depth_SR', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    glob_step_t = tf.Variable(0,
                              dtype=tf.int32,
                              trainable=False,
                              name='global_step')

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
        ## Pretrain
        g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
            g_init_loss, var_list=g_vars, global_step=glob_step_t)
        ## SRGAN
        g_optim = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
            g_loss, var_list=g_vars, global_step=glob_step_t)
        d_optim = tf.train.AdamOptimizer(lr_v,
                                         beta1=beta1).minimize(d_loss,
                                                               var_list=d_vars)

    ###========================== RESTORE MODEL =============================###

    saver = tf.train.Saver(max_to_keep=5)
    saver_d = tf.train.Saver(d_vars, max_to_keep=5)
    saver_g = tf.train.Saver(g_vars, max_to_keep=5)
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    tl.layers.initialize_global_variables(sess)

    with tf.variable_scope('summaries'):
        tf.summary.scalar('d_loss', d_loss)
        tf.summary.scalar('g_loss', g_loss)
        tf.summary.scalar('mse_loss', mse_loss)
        tf.summary.scalar('vgg_loss', vgg_loss)
        tf.summary.scalar('tv_loss', tv_loss)
        tf.summary.scalar('g_gan_loss', g_gan_loss)
        mae = tf.reduce_mean(
            tf.abs(net_g_outputs - t_target_image) /
            (t_target_image + tf.constant(1e-8)))
        rmse = tf.sqrt(
            tf.reduce_mean(tf.square(net_g_outputs - t_target_image)))
        tf.summary.scalar('MAE', mae)
        tf.summary.scalar('RMSE', rmse)
        tf.summary.scalar('learning_rate', lr_v)
        # tf.summary.image('input', t_input , max_outputs=1)
        tf.summary.image('GT', t_target_image, max_outputs=1)
        tf.summary.image('input_small_size', t_image, max_outputs=1)
        tf.summary.image('interpolated', t_interpolated, max_outputs=1)
        tf.summary.image('result', net_g_outputs, max_outputs=1)
        summary_op = tf.summary.merge_all()
        train_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph)
        test_writer = tf.summary.FileWriter(log_dir + '/test')

    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    # sample_imgs = train_hr_imgs[0:batch_size]
    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set

    # sample_imgs = tl.prepro.threading_data(train_hr_img_list[0:batch_size], fn=get_imgs_fn)  # if no pre-load train set
    # print('sample images:', sample_imgs.shape, sample_imgs.min(), sample_imgs.max())

    n_batches = int(len(train_hr_img_list) / batch_size)
    n_batches_valid = int(len(valid_hr_img_list) / batch_size)

    ###========================= initialize G ====================###

    if not do_init_g:
        n_epoch_init = -1
        try:
            saver_g.restore(
                sess, tf.train.latest_checkpoint(checkpoint_dir + '/g_init'))
        except Exception as e:
            print(
                ' ** You need to initialize generator: put do_init_g to True or provide a valid restore path'
            )
            raise e

    else:
        try:
            #saver.restore(sess, tf.train.latest_checkpoint(checkpoint_dir+'/gan')) # 2 round
            saver.restore(
                sess, tf.train.latest_checkpoint(checkpoint_dir + '/g_init'))
        except:
            print(' ** Creating new g_init model')
            pass

    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)

    train_iter, test_iter = 0, 0
    for epoch in range(0, n_epoch_init + 1):
        try:
            epoch_time = time.time()

            val_mae, val_mse, val_g_loss = 0, 0, 0
            batch_it = tqdm(SynthiaIterator(valid_hr_img_list,
                                            batchsize=batch_size,
                                            shuffle=True,
                                            buffer_size=70),
                            total=n_batches_valid,
                            leave=False)
            for b in batch_it:
                xb = b[0]
                errM, errG, mae_score = sess.run([mse_loss, g_loss, mae],
                                                 feed_dict={
                                                     t_input: xb,
                                                     d_flg: False
                                                 })
                val_mae += mae_score
                val_mse += errM
                val_g_loss += errG

            print("Validation: Epoch {0} val mae {1} val mse {2}".format(
                epoch - 1, val_mae / n_batches_valid,
                val_mse / n_batches_valid))

            total_mse_loss, total_g_loss = 0, 0
            batch_it = tqdm(SynthiaIterator(train_hr_img_list,
                                            batchsize=batch_size,
                                            shuffle=True,
                                            buffer_size=70),
                            total=n_batches,
                            leave=False)
            for b in batch_it:
                xb = b[0]
                xb = augment_imgs(xb)
                glob_step, errM, errG, _ = sess.run(
                    [glob_step_t, mse_loss, g_loss, g_optim_init],
                    feed_dict={
                        t_input: xb,
                        d_flg: True
                    })

                total_mse_loss += errM
                total_g_loss += errG
                if (train_iter + 1) % 200 == 0:
                    summary = sess.run(summary_op,
                                       feed_dict={
                                           t_input: xb,
                                           d_flg: False
                                       })
                    train_writer.add_summary(summary, train_iter + 1)

                train_iter += 1

            log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (
                epoch, n_epoch_init, time.time() - epoch_time,
                total_mse_loss / n_batches)

            val_mse_summary = tf.Summary.Value(tag='g_init/val_mse_loss',
                                               simple_value=val_mse /
                                               n_batches_valid)
            val_g_loss_summary = tf.Summary.Value(tag='g_init/val_loss',
                                                  simple_value=val_g_loss /
                                                  n_batches_valid)

            train_mse_loss_summary = tf.Summary.Value(
                tag='g_init/train_mse_loss',
                simple_value=total_mse_loss / n_batches)
            train_g_loss_summary = tf.Summary.Value(tag='g_init/train_loss',
                                                    simple_value=total_g_loss /
                                                    n_batches)

            epoch_summary = tf.Summary(value=[
                val_mse_summary, val_g_loss_summary, train_mse_loss_summary,
                train_g_loss_summary
            ])

            train_writer.add_summary(epoch_summary, glob_step)

            print(log)
            saver.save(
                sess,
                os.path.join(checkpoint_dir + '/g_init',
                             'model' + str(epoch) + '.ckpt'))

        except Exception as e:
            batch_it.iterable.stop()
            raise e

    ###========================= train GAN (SRGAN) =========================###
    try:
        # saver.restore(sess, tf.train.latest_checkpoint(checkpoint_dir+'/g_init'))
        # saver.restore(sess, tf.train.latest_checkpoint(checkpoint_dir+'/gan'))
        pass
    except:
        print(' ** Creating new GAN model')
        pass

    train_iter, test_iter = 0, 0
    for epoch in range(0, n_epoch + 1):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

        try:
            epoch_time = time.time()

            val_mae, val_mse, val_g_loss, val_d_loss = 0, 0, 0, 0
            batch_it = tqdm(SynthiaIterator(valid_hr_img_list,
                                            batchsize=batch_size,
                                            shuffle=True,
                                            buffer_size=70),
                            total=n_batches_valid,
                            leave=False)
            for b in batch_it:
                xb = b[0]
                errM, mae_score, errG, errD = sess.run(
                    [mse_loss, mae, g_loss, d_loss],
                    feed_dict={
                        t_input: xb,
                        d_flg: False
                    })
                val_mae += mae_score
                val_mse += errM
                val_g_loss += errG
                val_d_loss += errD

            print("Validation (GAN): Epoch {0} val mae {1} val mse {2}".format(
                epoch - 1, val_mae / n_batches_valid,
                val_mse / n_batches_valid))

            total_d_loss, total_g_loss, total_mse_loss = 0, 0, 0
            batch_it = tqdm(SynthiaIterator(train_hr_img_list,
                                            batchsize=batch_size,
                                            shuffle=True,
                                            buffer_size=70),
                            total=n_batches,
                            leave=False)
            for b in batch_it:
                xb = b[0]
                xb = augment_imgs(xb)
                ## update D
                errD, _ = sess.run([d_loss, d_optim], {
                    t_input: xb,
                    d_flg: True
                })
                ## update G
                glob_step, errG, errM, _, summary = sess.run(
                    [glob_step_t, g_loss, mse_loss, g_optim, summary_op], {
                        t_input: xb,
                        d_flg: True
                    })
                total_mse_loss += errM
                total_d_loss += errD
                total_g_loss += errG
                if (train_iter + 1) % 10 == 0:
                    train_writer.add_summary(summary, train_iter + 1)

                train_iter += 1

        except Exception as e:
            batch_it.iterable.stop()
            raise e
            break

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f mse_loss: %.8f" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_batches,
            total_g_loss / n_batches, total_mse_loss / n_batches)

        val_mse_summary = tf.Summary.Value(tag='gan/val_mse_loss',
                                           simple_value=val_mse /
                                           n_batches_valid)
        val_g_loss_summary = tf.Summary.Value(tag='gan/val_g_loss',
                                              simple_value=val_g_loss /
                                              n_batches_valid)
        val_d_loss_summary = tf.Summary.Value(tag='gan/val_d_loss',
                                              simple_value=val_d_loss /
                                              n_batches_valid)

        train_mse_loss_summary = tf.Summary.Value(tag='gan/train_mse_loss',
                                                  simple_value=total_mse_loss /
                                                  n_batches)
        train_g_loss_summary = tf.Summary.Value(tag='gan/train_g_loss',
                                                simple_value=total_g_loss /
                                                n_batches)
        train_d_loss_summary = tf.Summary.Value(tag='gan/train_d_loss',
                                                simple_value=total_d_loss /
                                                n_batches)

        epoch_summary = tf.Summary(value=[
            val_mse_summary, val_g_loss_summary, val_d_loss_summary,
            train_mse_loss_summary, train_g_loss_summary, train_d_loss_summary
        ])

        train_writer.add_summary(epoch_summary, glob_step)

        print(log)
        saver.save(
            sess,
            os.path.join(checkpoint_dir + '/gan',
                         'model' + str(n_epoch_init + epoch) + '.ckpt'))
Exemplo n.º 7
0
def train():
    ## create folders to save result images and trained model
    save_dir_gan = samples_path + "gan"
    tl.files.exists_or_mkdir(save_dir_gan)
    tl.files.exists_or_mkdir(checkpoint_path)

    ###====================== PRE-LOAD DATA ===========================###
    valid_hr_img_list = sorted(
        tl.files.load_file_list(path=valid_hr_img_path,
                                regx='.*\.(bmp|png|webp|jpg)',
                                printable=False))

    ###========================== DEFINE MODEL ============================###
    ## train inference
    sample_t_image = tf.compat.v1.placeholder(
        'float32', [sample_batch_size, 96, 96, 3],
        name='sample_t_image_input_to_SRGAN_generator')
    t_image = tf.compat.v1.placeholder('float32', [batch_size, 96, 96, 3],
                                       name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.compat.v1.placeholder('float32',
                                              [batch_size, 384, 384, 3],
                                              name='t_target_image')

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## test inference
    net_g_test = SRGAN_g(sample_t_image, is_train=False, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###

    # MAE Loss
    mae_loss = tf.reduce_mean(tf.map_fn(tf.abs,
                                        t_target_image - net_g.outputs))

    # GAN Loss
    d_loss = 0.5 * (
        tf.reduce_mean(
            tf.square(logits_real - tf.reduce_mean(logits_fake) - 1)) +
        tf.reduce_mean(
            tf.square(logits_fake - tf.reduce_mean(logits_real) + 1)))
    g_gan_loss = 0.5 * (
        tf.reduce_mean(
            tf.square(logits_real - tf.reduce_mean(logits_fake) + 1)) +
        tf.reduce_mean(
            tf.square(logits_fake - tf.reduce_mean(logits_real) - 1)))

    g_loss = 1e-1 * g_gan_loss + mae_loss

    d_real = tf.reduce_mean(logits_real)
    d_fake = tf.reduce_mean(logits_fake)

    with tf.variable_scope('learning_rate'):
        learning_rate_var = tf.Variable(learning_rate, trainable=False)

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    ## SRGAN
    g_optim = tf.compat.v1.train.AdamOptimizer(
        learning_rate=learning_rate_var).minimize(g_loss, var_list=g_vars)
    d_optim = tf.compat.v1.train.AdamOptimizer(
        learning_rate=learning_rate_var).minimize(d_loss, var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    sess.run(tf.variables_initializer(tf.global_variables()))
    tl.files.load_and_assign_npz(sess=sess,
                                 name=checkpoint_path + 'g.npz',
                                 network=net_g)
    tl.files.load_and_assign_npz(sess=sess,
                                 name=checkpoint_path + 'd.npz',
                                 network=net_d)

    ###============================= TRAINING ===============================###
    sample_imgs = tl.prepro.threading_data(
        valid_hr_img_list[0:sample_batch_size],
        fn=get_imgs_fn,
        path=valid_hr_img_path)
    sample_imgs_384 = tl.prepro.threading_data(sample_imgs,
                                               fn=crop_sub_imgs_fn,
                                               is_random=False)
    print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(),
          sample_imgs_384.max())
    sample_imgs_96 = tl.prepro.threading_data(sample_imgs_384,
                                              fn=downsample_fn)
    print('sample LR sub-image:', sample_imgs_96.shape, sample_imgs_96.min(),
          sample_imgs_96.max())
    save_images(sample_imgs_96, [ni, ni], save_file_format,
                save_dir_gan + '/_train_sample_96')
    save_images(sample_imgs_384, [ni, ni], save_file_format,
                save_dir_gan + '/_train_sample_384')

    ###========================= train GAN =========================###
    sess.run(tf.assign(learning_rate_var, learning_rate))
    for epoch in range(0, n_epoch_gan + 1):
        epoch_time = time.time()
        total_d_loss, total_g_loss_mae, total_g_loss_gan, n_iter = 0, 0, 0, 0

        train_hr_img_list = load_deep_file_list(path=train_hr_img_path,
                                                regx='.*\.(bmp|png|webp|jpg)',
                                                recursive=True,
                                                printable=False)
        random.shuffle(train_hr_img_list)

        list_length = len(train_hr_img_list)
        print("Number of images: %d" % (list_length))

        if list_length % batch_size != 0:
            train_hr_img_list += train_hr_img_list[0:batch_size -
                                                   list_length % batch_size:1]

        list_length = len(train_hr_img_list)
        print("Length of list: %d" % (list_length))

        for idx in range(0, list_length, batch_size):
            step_time = time.time()
            b_imgs_list = train_hr_img_list[idx:idx + batch_size]
            b_imgs = tl.prepro.threading_data(b_imgs_list,
                                              fn=get_imgs_fn,
                                              path=train_hr_img_path)
            b_imgs_384 = tl.prepro.threading_data(b_imgs,
                                                  fn=crop_data_augment_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            b_imgs_384 = tl.prepro.threading_data(b_imgs_384, fn=rescale_m1p1)

            ## update D
            errD, d_r, d_f, _ = sess.run([d_loss, d_real, d_fake, d_optim], {
                t_image: b_imgs_96,
                t_target_image: b_imgs_384
            })
            ## update G
            errM, errA, _, _ = sess.run(
                [mae_loss, g_gan_loss, g_loss, g_optim], {
                    t_image: b_imgs_96,
                    t_target_image: b_imgs_384
                })
            print(
                "Epoch[%2d/%2d] %4d time: %4.2fs d_loss: %.8f g_loss_mae: %.8f g_loss_gan: %.8f d_r: %.8f d_f: %.8f"
                % (epoch, n_epoch_gan, n_iter, time.time() - step_time, errD,
                   errM, errA, d_r, d_f))
            total_d_loss += errD
            total_g_loss_mae += errM
            total_g_loss_gan += errA
            n_iter += 1

        log = (
            "[*] Epoch[%2d/%2d] time: %4.2fs d_loss: %.8f g_loss_mae: %.8f g_loss_gan: %.8f"
            % (epoch, n_epoch_gan, time.time() - epoch_time, total_d_loss /
               n_iter, total_g_loss_mae / n_iter, total_g_loss_gan / n_iter))
        print(log)

        ## quick evaluation on train set
        out = sess.run(net_g_test.outputs, {sample_t_image: sample_imgs_96})
        print("[*] save images")
        save_images(out, [ni, ni], save_file_format,
                    save_dir_gan + '/train_%d' % epoch)

        ## save model
        tl.files.save_npz(net_g.all_params,
                          name=checkpoint_path + 'g.npz',
                          sess=sess)
        tl.files.save_npz(net_d.all_params,
                          name=checkpoint_path + 'd.npz',
                          sess=sess)
Exemplo n.º 8
0
def train():
    ## create folders to save result images and trained model
    save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###====================== PRE-LOAD DATA ===========================###
    train_hr_img_list = sorted(tl.files.load_file_list(path=config.TRAIN.hr_img_path, regx='.*.png', printable=False))
    train_lr_img_list = sorted(tl.files.load_file_list(path=config.TRAIN.lr_img_path, regx='.*.png', printable=False))
    valid_hr_img_list = sorted(tl.files.load_file_list(path=config.VALID.hr_img_path, regx='.*.png', printable=False))
    valid_lr_img_list = sorted(tl.files.load_file_list(path=config.VALID.lr_img_path, regx='.*.png', printable=False))

    ## If your machine have enough memory, please pre-load the whole train set.
    train_hr_imgs = tl.vis.read_images(train_hr_img_list, path=config.TRAIN.hr_img_path, n_threads=32)
    # for im in train_hr_imgs:
    #     print(im.shape)
    # valid_lr_imgs = tl.vis.read_images(valid_lr_img_list, path=config.VALID.lr_img_path, n_threads=32)
    # for im in valid_lr_imgs:
    #     print(im.shape)
    # valid_hr_imgs = tl.vis.read_images(valid_hr_img_list, path=config.VALID.hr_img_path, n_threads=32)
    # for im in valid_hr_imgs:
    #     print(im.shape)
    # exit()

    ###========================== DEFINE MODEL ============================###
    ## train inference
    t_image = tf.placeholder('float32', [batch_size, 96, 96, 3], name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder('float32', [batch_size, 384, 384, 3], name='t_target_image')

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    t_target_image_224 = tf.image.resize_images(
        t_target_image, size=[224, 224], method=0,
        align_corners=False)  # resize_target_image_for_vgg # http://tensorlayer.readthedocs.io/en/latest/_modules/tensorlayer/layers.html#UpSampling2dLayer
    t_predict_image_224 = tf.image.resize_images(net_g.outputs, size=[224, 224], method=0, align_corners=False)  # resize_generate_image_for_vgg

    net_vgg, vgg_target_emb = Vgg19_simple_api((t_target_image_224 + 1) / 2, reuse=False)
    _, vgg_predict_emb = Vgg19_simple_api((t_predict_image_224 + 1) / 2, reuse=True)

    ## test inference
    net_g_test = SRGAN_g(t_image, is_train=False, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real, tf.ones_like(logits_real), name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake, tf.zeros_like(logits_fake), name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs, t_target_image, is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + vgg_loss + g_gan_loss

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(g_loss, var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(d_loss, var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=False))
    tl.layers.initialize_global_variables(sess)
    if tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_{}.npz'.format(tl.global_flag['mode']), network=net_g) is False:
        tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_{}_init.npz'.format(tl.global_flag['mode']), network=net_g)
    tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/d_{}.npz'.format(tl.global_flag['mode']), network=net_d)

    ###============================= LOAD VGG ===============================###
    vgg19_npy_path = "vgg19.npy"
    if not os.path.isfile(vgg19_npy_path):
        print("Please download vgg19.npz from : https://github.com/machrisaa/tensorflow-vgg")
        exit()
    npz = np.load(vgg19_npy_path, encoding='latin1').item()

    params = []
    for val in sorted(npz.items()):
        W = np.asarray(val[1][0])
        b = np.asarray(val[1][1])
        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
        params.extend([W, b])
    tl.files.assign_params(sess, params, net_vgg)
    # net_vgg.print_params(False)
    # net_vgg.print_layers()

    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    sample_imgs = train_hr_imgs[0:batch_size]
    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set
    sample_imgs_384 = tl.prepro.threading_data(sample_imgs, fn=crop_sub_imgs_fn, is_random=False)
    print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(), sample_imgs_384.max())
    sample_imgs_96 = tl.prepro.threading_data(sample_imgs_384, fn=downsample_fn)
    print('sample LR sub-image:', sample_imgs_96.shape, sample_imgs_96.min(), sample_imgs_96.max())
    tl.vis.save_images(sample_imgs_96, [ni, ni], save_dir_ginit + '/_train_sample_96.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni], save_dir_ginit + '/_train_sample_384.png')
    tl.vis.save_images(sample_imgs_96, [ni, ni], save_dir_gan + '/_train_sample_96.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni], save_dir_gan + '/_train_sample_384.png')

    ###========================= initialize G ====================###
    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx + batch_size], fn=crop_sub_imgs_fn, is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update G
            errM, _ = sess.run([mse_loss, g_optim_init], {t_image: b_imgs_96, t_target_image: b_imgs_384})
            print("Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f " % (epoch, n_epoch_init, n_iter, time.time() - step_time, errM))
            total_mse_loss += errM
            n_iter += 1
        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (epoch, n_epoch_init, time.time() - epoch_time, total_mse_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {t_image: sample_imgs_96})  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni], save_dir_ginit + '/train_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(net_g.all_params, name=checkpoint_dir + '/g_{}_init.npz'.format(tl.global_flag['mode']), sess=sess)

    ###========================= train GAN (SRGAN) =========================###
    for epoch in range(0, n_epoch + 1):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init * new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (lr_init, decay_every, lr_decay)
            print(log)

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx + batch_size], fn=crop_sub_imgs_fn, is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update D
            errD, _ = sess.run([d_loss, d_optim], {t_image: b_imgs_96, t_target_image: b_imgs_384})
            ## update G
            errG, errM, errV, errA, _ = sess.run([g_loss, mse_loss, vgg_loss, g_gan_loss, g_optim], {t_image: b_imgs_96, t_target_image: b_imgs_384})
            print("Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f vgg: %.6f adv: %.6f)" %
                  (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG, errM, errV, errA))
            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
                                                                                total_g_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {t_image: sample_imgs_96})  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni], save_dir_gan + '/train_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(net_g.all_params, name=checkpoint_dir + '/g_{}.npz'.format(tl.global_flag['mode']), sess=sess)
            tl.files.save_npz(net_d.all_params, name=checkpoint_dir + '/d_{}.npz'.format(tl.global_flag['mode']), sess=sess)
Exemplo n.º 9
0
def train():
    ## create folders to save result images and trained model
    save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###====================== PRE-LOAD DATA ===========================###
    train_hr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.hr_img_path,
                                regx='.*.png',
                                printable=False))
    train_lr_img_list = sorted(
        tl.files.load_file_list(path=config.TRAIN.lr_img_path,
                                regx='.*.png',
                                printable=False))
    valid_hr_img_list = sorted(
        tl.files.load_file_list(path=config.VALID.hr_img_path,
                                regx='.*.png',
                                printable=False))
    valid_lr_img_list = sorted(
        tl.files.load_file_list(path=config.VALID.lr_img_path,
                                regx='.*.png',
                                printable=False))

    ## If your machine have enough memory, please pre-load the whole train set.

    print("reading images")
    train_hr_imgs = []  #[None] * len(train_hr_img_list)

    #sess = tf.Session()
    for img__ in train_hr_img_list:

        image_loaded = scipy.misc.imread(os.path.join(config.TRAIN.hr_img_path,
                                                      img__),
                                         mode='L')
        image_loaded = image_loaded.reshape(
            (image_loaded.shape[0], image_loaded.shape[1], 1))

        train_hr_imgs.append(image_loaded)

    print(type(train_hr_imgs), len(train_hr_img_list))

    ###========================== DEFINE MODEL ============================###
    ## train inference

    #t_image = tf.placeholder('float32', [batch_size, 96, 96, 3], name='t_image_input_to_SRGAN_generator')
    #t_target_image = tf.placeholder('float32', [batch_size, 384, 384, 3], name='t_target_image')

    t_image = tf.placeholder('float32', [batch_size, 28, 224, 1],
                             name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder(
        'float32', [batch_size, 224, 224, 1], name='t_target_image'
    )  # may have to convert 224x224x1 into 224x224x3, with channel 1 & 2 as 0. May have to have separate place-holder ?

    print("t_image:", tf.shape(t_image))
    print("t_target_image:", tf.shape(t_target_image))

    net_g = SRGAN_g(t_image, is_train=True, reuse=False)
    print("net_g.outputs:", tf.shape(net_g.outputs))

    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## vgg inference. 0, 1, 2, 3 BILINEAR NEAREST BICUBIC AREA
    t_target_image_224 = tf.image.resize_images(
        t_target_image, size=[224, 224], method=0, align_corners=False
    )  # resize_target_image_for_vgg # http://tensorlayer.readthedocs.io/en/latest/_modules/tensorlayer/layers.html#UpSampling2dLayer
    t_predict_image_224 = tf.image.resize_images(
        net_g.outputs, size=[224, 224], method=0,
        align_corners=False)  # resize_generate_image_for_vgg

    ## Added as VGG works for RGB and expects 3 channels.
    t_target_image_224 = tf.image.grayscale_to_rgb(t_target_image_224)
    t_predict_image_224 = tf.image.grayscale_to_rgb(t_predict_image_224)

    print("net_g.outputs:", tf.shape(net_g.outputs))
    print("t_predict_image_224:", tf.shape(t_predict_image_224))

    net_vgg, vgg_target_emb = Vgg19_simple_api((t_target_image_224 + 1) / 2,
                                               reuse=False)
    _, vgg_predict_emb = Vgg19_simple_api((t_predict_image_224 + 1) / 2,
                                          reuse=True)

    ## test inference
    net_g_test = SRGAN_g(t_image, is_train=False, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs,
                                          t_target_image,
                                          is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + vgg_loss + g_gan_loss

    d_loss1_summary = tf.summary.scalar('Disciminator logits_real loss',
                                        d_loss1)
    d_loss2_summary = tf.summary.scalar('Disciminator logits_fake loss',
                                        d_loss2)
    d_loss_summary = tf.summary.scalar('Disciminator total loss', d_loss)

    g_gan_loss_summary = tf.summary.scalar('Generator GAN loss', g_gan_loss)
    mse_loss_summary = tf.summary.scalar('Generator MSE loss', mse_loss)
    vgg_loss_summary = tf.summary.scalar('Generator VGG loss', vgg_loss)
    g_loss_summary = tf.summary.scalar('Generator total loss', g_loss)

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    #	UNCOMMENT THE LINE BELOW!!!
    #g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    tl.layers.initialize_global_variables(sess)
    #if tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_{}.npz'.format(tl.global_flag['mode']), network=net_g) is False:
    #   tl.fites.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/g_{}_init.npz'.format(tl.global_flag['mode']), network=net_g)
    #tl.files.load_and_assign_npz(sess=sess, name=checkpoint_dir + '/d_{}.npz'.format(tl.global_flag['mode']), network=net_d)

    ###============================= LOAD VGG ===============================###
    vgg19_npy_path = "vgg19.npy"
    if not os.path.isfile(vgg19_npy_path):
        print(
            "Please download vgg19.npz from : https://github.com/machrisaa/tensorflow-vgg"
        )
        exit()
    npz = np.load(vgg19_npy_path, encoding='latin1').item()

    params = []
    for val in sorted(npz.items()):
        W = np.asarray(val[1][0])
        b = np.asarray(val[1][1])
        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
        params.extend([W, b])
    tl.files.assign_params(sess, params, net_vgg)
    # net_vgg.print_params(False)
    # net_vgg.print_layers()

    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    sample_imgs = train_hr_imgs[0:batch_size]
    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set

    print("sample_imgs size:", len(sample_imgs), sample_imgs[0].shape)

    sample_imgs_384 = tl.prepro.threading_data(sample_imgs,
                                               fn=crop_sub_imgs_fn,
                                               is_random=False)
    print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(),
          sample_imgs_384.max())
    sample_imgs_96 = tl.prepro.threading_data(sample_imgs_384,
                                              fn=downsample_fn_mod)
    print('sample LR sub-image:', sample_imgs_96.shape, sample_imgs_96.min(),
          sample_imgs_96.max())
    #tl.vis.save_images(sample_imgs_96, [ni, ni], save_dir_ginit + '/_train_sample_96.png')
    #tl.vis.save_images(sample_imgs_384, [ni, ni], save_dir_ginit + '/_train_sample_384.png')
    #tl.vis.save_images(sample_imgs_96, [ni, ni], save_dir_gan + '/_train_sample_96.png')
    #tl.vis.save_images(sample_imgs_384, [ni, ni], save_dir_gan + '/_train_sample_384.png')
    '''
    ###========================= initialize G ====================###
    
    merged_summary_initial_G = tf.summary.merge([mse_loss_summary])
    summary_intial_G_writer = tf.summary.FileWriter("./log/train/initial_G")
    
    

    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    count = 0
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.
        
        
        intial_MSE_G_summary_per_epoch = []
        
        
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx + batch_size], fn=crop_sub_imgs_fn, is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn_mod)
            ## update G
            errM, _, mse_summary_initial_G = sess.run([mse_loss, g_optim_init, merged_summary_initial_G], {t_image: b_imgs_96, t_target_image: b_imgs_384})
            print("Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f " % (epoch, n_epoch_init, n_iter, time.time() - step_time, errM))

            
            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(mse_summary_initial_G)
            
            intial_G_summaries = {}
            for val in summary_pb.value:
            # Assuming all summaries are scalars.
                intial_G_summaries[val.tag] = val.simple_value
            #print("intial_G_summaries:", intial_G_summaries)
            
            
            intial_MSE_G_summary_per_epoch.append(intial_G_summaries['Generator_MSE_loss'])
            
            
            #summary_intial_G_writer.add_summary(mse_summary_initial_G, (count + 1)) #(epoch + 1)*(n_iter+1))
            #count += 1


            total_mse_loss += errM
            n_iter += 1
        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (epoch, n_epoch_init, time.time() - epoch_time, total_mse_loss / n_iter)
        print(log)

        
        summary_intial_G_writer.add_summary(tf.Summary(value=[tf.Summary.Value(tag="Generator_Initial_MSE_loss per epoch", simple_value=np.mean(intial_MSE_G_summary_per_epoch)),]), (epoch))


        ## quick evaluation on train set
        #if (epoch != 0) and (epoch % 10 == 0):
        out = sess.run(net_g_test.outputs, {t_image: sample_imgs_96})  #; print('gen sub-image:', out.shape, out.min(), out.max())
        print("[*] save images")
        for im in range(len(out)):
            if(im%4==0 or im==1197):
                tl.vis.save_image(out[im], save_dir_ginit + '/train_%d_%d.png' % (epoch,im))

        ## save model
        saver=tf.train.Saver()
        if (epoch%10==0 and epoch!=0):
            saver.save(sess, 'checkpoint/init_'+str(epoch)+'.ckpt')      

   #if (epoch != 0) and (epoch % 10 == 0):
        #tl.files.save_npz(net_g.all_params, name=checkpoint_dir + '/g_{}_{}_init.npz'.format(tl.global_flag['mode'], epoch), sess=sess)
    '''
    ###========================= train GAN (SRGAN) =========================###
    saver = tf.train.Saver()
    saver.restore(sess, 'checkpoint/main_10.ckpt')
    print('Restored main_10, begin 11/50')
    merged_summary_discriminator = tf.summary.merge(
        [d_loss1_summary, d_loss2_summary, d_loss_summary])
    summary_discriminator_writer = tf.summary.FileWriter(
        "./log/train/discriminator")

    merged_summary_generator = tf.summary.merge([
        g_gan_loss_summary, mse_loss_summary, vgg_loss_summary, g_loss_summary
    ])
    summary_generator_writer = tf.summary.FileWriter("./log/train/generator")

    learning_rate_writer = tf.summary.FileWriter("./log/train/learning_rate")

    count = 0
    for epoch in range(11, n_epoch + 11):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)

            learning_rate_writer.add_summary(
                tf.Summary(value=[
                    tf.Summary.Value(tag="Learning_rate per epoch",
                                     simple_value=(lr_init * new_lr_decay)),
                ]), (epoch))

        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

            learning_rate_writer.add_summary(
                tf.Summary(value=[
                    tf.Summary.Value(tag="Learning_rate per epoch",
                                     simple_value=lr_init),
                ]), (epoch))

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        ## If your machine cannot load all images into memory, you should use
        ## this one to load batch of images while training.
        # random.shuffle(train_hr_img_list)
        # for idx in range(0, len(train_hr_img_list), batch_size):
        #     step_time = time.time()
        #     b_imgs_list = train_hr_img_list[idx : idx + batch_size]
        #     b_imgs = tl.prepro.threading_data(b_imgs_list, fn=get_imgs_fn, path=config.TRAIN.hr_img_path)
        #     b_imgs_384 = tl.prepro.threading_data(b_imgs, fn=crop_sub_imgs_fn, is_random=True)
        #     b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)

        ## If your machine have enough memory, please pre-load the whole train set.

        loss_per_batch = []

        d_loss1_summary_per_epoch = []
        d_loss2_summary_per_epoch = []
        d_loss_summary_per_epoch = []

        g_gan_loss_summary_per_epoch = []
        mse_loss_summary_per_epoch = []
        vgg_loss_summary_per_epoch = []
        g_loss_summary_per_epoch = []

        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384,
                                                 fn=downsample_fn_mod)
            ## update D
            errD, _, discriminator_summary = sess.run(
                [d_loss, d_optim, merged_summary_discriminator], {
                    t_image: b_imgs_96,
                    t_target_image: b_imgs_384
                })

            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(discriminator_summary)
            #print("discriminator_summary", summary_pb, type(summary_pb))

            discriminator_summaries = {}
            for val in summary_pb.value:
                # Assuming all summaries are scalars.
                discriminator_summaries[val.tag] = val.simple_value

            d_loss1_summary_per_epoch.append(
                discriminator_summaries['Disciminator_logits_real_loss'])
            d_loss2_summary_per_epoch.append(
                discriminator_summaries['Disciminator_logits_fake_loss'])
            d_loss_summary_per_epoch.append(
                discriminator_summaries['Disciminator_total_loss'])

            ## update G
            errG, errM, errV, errA, _, generator_summary = sess.run(
                [
                    g_loss, mse_loss, vgg_loss, g_gan_loss, g_optim,
                    merged_summary_generator
                ], {
                    t_image: b_imgs_96,
                    t_target_image: b_imgs_384
                })

            summary_pb = tf.summary.Summary()
            summary_pb.ParseFromString(generator_summary)
            #print("generator_summary", summary_pb, type(summary_pb))

            generator_summaries = {}
            for val in summary_pb.value:
                # Assuming all summaries are scalars.
                generator_summaries[val.tag] = val.simple_value

            #print("generator_summaries:", generator_summaries)

            g_gan_loss_summary_per_epoch.append(
                generator_summaries['Generator_GAN_loss'])
            mse_loss_summary_per_epoch.append(
                generator_summaries['Generator_MSE_loss'])
            vgg_loss_summary_per_epoch.append(
                generator_summaries['Generator_VGG_loss'])
            g_loss_summary_per_epoch.append(
                generator_summaries['Generator_total_loss'])

            #summary_generator_writer.add_summary(generator_summary, (count + 1))

            #summary_total = sess.run(summary_total_merged, {t_image: b_imgs_96, t_target_image: b_imgs_384})
            #summary_total_merged_writer.add_summary(summary_total, (count + 1))

            #count += 1

            tot_epoch = n_epoch + 10
            print(
                "Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f vgg: %.6f adv: %.6f)"
                % (epoch, tot_epoch, n_iter, time.time() - step_time, errD,
                   errG, errM, errV, errA))
            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1
            #remove this for normal running:

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (
            epoch, tot_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter)
        print(log)

        #####
        #
        # logging discriminator summary
        #
        ######

        # logging per epcoch summary of logit_real_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_logits_real_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss1_summary_per_epoch)),
            ]), (epoch))

        # logging per epcoch summary of logit_fake_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_logits_fake_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss2_summary_per_epoch)),
            ]), (epoch))

        # logging per epcoch summary of total_loss per epoch. Value logged is averaged across batches used per epoch.
        summary_discriminator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Disciminator_total_loss per epoch",
                                 simple_value=np.mean(
                                     d_loss_summary_per_epoch)),
            ]), (epoch))

        #####
        #
        # logging generator summary
        #
        ######

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_GAN_loss per epoch",
                                 simple_value=np.mean(
                                     g_gan_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_MSE_loss per epoch",
                                 simple_value=np.mean(
                                     mse_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_VGG_loss per epoch",
                                 simple_value=np.mean(
                                     vgg_loss_summary_per_epoch)),
            ]), (epoch))

        summary_generator_writer.add_summary(
            tf.Summary(value=[
                tf.Summary.Value(tag="Generator_total_loss per epoch",
                                 simple_value=np.mean(
                                     g_loss_summary_per_epoch)),
            ]), (epoch))

        ## quick evaluation on train set
        #if (epoch != 0) and (epoch % 10 == 0):
        out = sess.run(
            net_g_test.outputs,
            {t_image: sample_imgs_96
             })  #; print('gen sub-image:', out.shape, out.min(), out.max())
        ## save model
        if (epoch % 10 == 0 and epoch != 0):
            saver.save(sess, 'checkpoint/main_' + str(epoch) + '.ckpt')

            print("[*] save images")
            for im in range(len(out)):
                tl.vis.save_image(
                    out[im], save_dir_gan + '/train_%d_%d.png' % (epoch, im))
Exemplo n.º 10
0
def train():
    ## create folders to save result images and trained model
    save_dir_ginit = "samples/{}_ginit".format(tl.global_flag['mode'])
    save_dir_gan = "samples/{}_gan".format(tl.global_flag['mode'])
    save_dir_valid = "samples/{}_valid".format(tl.global_flag['mode'])
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    tl.files.exists_or_mkdir(save_dir_valid)
    checkpoint_dir = "checkpoint"  # checkpoint_resize_conv
    tl.files.exists_or_mkdir(checkpoint_dir)

    train_hr_imgs = read_csv_data(config.TRAIN.hr_img_path,
                                  width=48,
                                  height=48,
                                  channel=1)
    valid_hr_imgs = read_csv_data(config.VALID.hr_img_path,
                                  width=48,
                                  height=48,
                                  channel=1)

    ###========================== DEFINE MODEL ============================###
    ## train inference  ## t = train
    t_image = tf.placeholder('float32', [None, 16, 16, 1],
                             name='t_image_input_to_SRGAN_generator')
    t_target_image = tf.placeholder('float32', [None, 48, 48, 1],
                                    name='t_target_image')

    net_g = SRGAN_g(t_image, is_train=True, reuse=False, nb_block=16)
    net_d, logits_real = SRGAN_d(t_target_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    net_g.print_params(False)
    net_g.print_layers()
    net_d.print_params(False)
    net_d.print_layers()

    ## test inference
    net_g_test = SRGAN_g(t_image, is_train=False, reuse=True)

    # ###========================== DEFINE TRAIN OPS ==========================###
    # d_loss: for discriminator
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    # g_loss: for generator
    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs,
                                          t_target_image,
                                          is_mean=True)
    # vgg_loss = 2e-6 * tl.cost.mean_squared_error(vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + g_gan_loss
    # g_loss = mse_loss + vgg_loss + g_gan_loss

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)
    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
        mse_loss, var_list=g_vars)
    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###============================= TRAINING ===============================###
    ## use first `batch_size` of train set to have a quick test during training
    sample_imgs = train_hr_imgs[0:9]
    valid_imgs = valid_hr_imgs[44:53]
    # sample_imgs = tl.vis.read_images(train_hr_img_list[0:batch_size], path=config.TRAIN.hr_img_path, n_threads=32) # if no pre-load train set
    sample_imgs_384 = tl.prepro.threading_data(sample_imgs,
                                               fn=crop_sub_imgs_fn,
                                               is_random=False)
    valid_imgs_48 = tl.prepro.threading_data(valid_imgs,
                                             fn=crop_sub_imgs_fn,
                                             is_random=False)
    print('sample HR sub-image:', sample_imgs_384.shape, sample_imgs_384.min(),
          sample_imgs_384.max())
    sample_imgs_96 = tl.prepro.threading_data(sample_imgs_384,
                                              fn=downsample_fn,
                                              down_rate=3)
    valid_imgs_16 = tl.prepro.threading_data(valid_imgs_48,
                                             fn=downsample_fn,
                                             down_rate=3)
    print('sample LR sub-image:', sample_imgs_96.shape, sample_imgs_96.min(),
          sample_imgs_96.max())
    tl.vis.save_images(sample_imgs_96, [ni, ni],
                       save_dir_ginit + '/_train_sample_16.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni],
                       save_dir_ginit + '/_train_sample_48.png')
    tl.vis.save_images(sample_imgs_96, [ni, ni],
                       save_dir_gan + '/_train_sample_16.png')
    tl.vis.save_images(sample_imgs_384, [ni, ni],
                       save_dir_gan + '/_train_sample_48.png')
    tl.vis.save_images(valid_imgs_48, [ni, ni],
                       save_dir_valid + '/_valid_sample_48.png')
    tl.vis.save_images(valid_imgs_16, [ni, ni],
                       save_dir_valid + '/_valid_sample_16.png')
    sample_hr_imgs_bicubic = tl.prepro.threading_data(sample_imgs_96,
                                                      fn=upsample_fn,
                                                      up_rate=3)
    valid_hr_imgs_bicubic = tl.prepro.threading_data(valid_imgs_16,
                                                     fn=upsample_fn,
                                                     up_rate=3)
    tl.vis.save_images(sample_hr_imgs_bicubic, [ni, ni],
                       save_dir_ginit + '/_sample_bicubic_48.png')
    tl.vis.save_images(valid_hr_imgs_bicubic, [ni, ni],
                       save_dir_valid + '/_valid_sample_bicubic_48.png')

    ###========================= initialize G ====================###
    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    train_writer_path = "./log/train"
    tl.files.exists_or_mkdir(train_writer_path)
    train_writer = tf.summary.FileWriter(train_writer_path,
                                         graph=tf.get_default_graph())
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, n_iter = 0, 0

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            if idx + batch_size > len(train_hr_imgs):
                break

            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update G
            errM, _ = sess.run([mse_loss, g_optim_init], {
                t_image: b_imgs_96,
                t_target_image: b_imgs_384
            })
            sys.stdout.write(
                "Epoch [%2d/%2d] %4d time: %4.4fs, mse: %.8f \r" %
                (epoch, n_epoch_init, n_iter, time.time() - step_time, errM))
            sys.stdout.flush()
            total_mse_loss += errM
            n_iter += 1
        log = "\n[*] Epoch: [%2d/%2d] time: %4.4fs, mse: %.8f" % (
            epoch, n_epoch_init, time.time() - epoch_time,
            total_mse_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: sample_imgs_96
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni],
                               save_dir_ginit + '/train_%d.png' % epoch)

        ## quick evaluation on validation set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: valid_imgs_16
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            tl.vis.save_images(out, [ni, ni],
                               save_dir_valid + '/valid_ganit_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(
                net_g.all_params,
                name=checkpoint_dir +
                '/g_{}_init_{}.npz'.format(tl.global_flag['mode'], epoch),
                sess=sess)

    ###========================= train GAN (SRGAN) =========================###
    for epoch in range(0, n_epoch + 1):
        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

        epoch_time = time.time()
        total_d_loss, total_g_loss, n_iter = 0, 0, 0

        ## If your machine have enough memory, please pre-load the whole train set.
        for idx in range(0, len(train_hr_imgs), batch_size):
            step_time = time.time()
            b_imgs_384 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_384, fn=downsample_fn)
            ## update D
            errD, _ = sess.run([d_loss, d_optim], {
                t_image: b_imgs_96,
                t_target_image: b_imgs_384
            })
            ## update G
            # errG, errM, errV, errA, _ = sess.run([g_loss, mse_loss, vgg_loss, g_gan_loss, g_optim], {t_image: b_imgs_96, t_target_image: b_imgs_384})
            errG, errM, errA, _ = sess.run(
                [g_loss, mse_loss, g_gan_loss, g_optim], {
                    t_image: b_imgs_96,
                    t_target_image: b_imgs_384
                })
            # sys.stdout.write("Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f vgg: %.6f adv: %.6f)\n" %
            #       (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG, errM, errV, errA))
            sys.stdout.write(
                "Epoch [%2d/%2d] %4d time: %4.4fs, d_loss: %.8f g_loss: %.8f (mse: %.6f adv: %.6f) \r"
                % (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG,
                   errM, errA))
            sys.stdout.flush()
            total_d_loss += errD
            total_g_loss += errG
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.4fs, d_loss: %.8f g_loss: %.8f" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter)
        print(log)

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: sample_imgs_96
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            print("[*] save images")
            tl.vis.save_images(out, [ni, ni],
                               save_dir_gan + '/train_%d.png' % epoch)

        ## quick evaluation on validation set
        if (epoch != 0) and (epoch % 10 == 0):
            out = sess.run(net_g_test.outputs, {
                t_image: valid_imgs_16
            })  #; print('gen sub-image:', out.shape, out.min(), out.max())
            tl.vis.save_images(out, [ni, ni],
                               save_dir_valid + '/valid_gan_%d.png' % epoch)

        ## save model
        if (epoch != 0) and (epoch % 10 == 0):
            tl.files.save_npz(
                net_g.all_params,
                name=checkpoint_dir +
                '/g_{}_{}.npz'.format(tl.global_flag['mode'], epoch),
                sess=sess)
            tl.files.save_npz(
                net_d.all_params,
                name=checkpoint_dir +
                '/d_{}_{}.npz'.format(tl.global_flag['mode'], epoch),
                sess=sess)
Exemplo n.º 11
0
def train(train_lr_path,
          train_hr_path,
          save_path,
          save_every_epoch=2,
          validation=True,
          ratio=0.9,
          batch_size=16,
          lr_init=1e-4,
          beta1=0.9,
          n_epoch_init=10,
          n_epoch=20,
          lr_decay=0.1):
    '''
    Parameters:
    data:
        train_lr_path/train_hr_path: path of data
        save_path: the parent folder to save model result
        validation: whether to split data into train set and validation set
        save_every_epoch: how frequent to save the checkpoints and sample images
    Adam: 
        batch_size
        lr_init
        beta1
    Generator Initialization
        n_epoch_init
    Adversarial Net
        n_epoch
        lr_decay
    '''

    ## Folders to save results
    save_dir_ginit = os.path.join(save_path, 'srgan_ginit')
    save_dir_gan = os.path.join(save_path, 'srgan_gan')
    checkpoint_dir = os.path.join(save_path, 'checkpoint')
    tl.files.exists_or_mkdir(save_dir_ginit)
    tl.files.exists_or_mkdir(save_dir_gan)
    tl.files.exists_or_mkdir(checkpoint_dir)

    ###======LOAD DATA======###
    train_lr_img_list = sorted(
        tl.files.load_file_list(path=train_lr_path,
                                regx='.*.jpg',
                                printable=False))
    train_hr_img_list = sorted(
        tl.files.load_file_list(path=train_hr_path,
                                regx='.*.jpg',
                                printable=False))

    if validation:
        idx = np.random.choice(len(train_lr_img_list),
                               int(len(train_lr_img_list) * ratio),
                               replace=False)
        valid_lr_img_list = sorted(
            [x for i, x in enumerate(train_lr_img_list) if i not in idx])
        valid_hr_img_list = sorted(
            [x for i, x in enumerate(train_hr_img_list) if i not in idx])
        train_lr_img_list = sorted(
            [x for i, x in enumerate(train_lr_img_list) if i in idx])
        train_hr_img_list = sorted(
            [x for i, x in enumerate(train_hr_img_list) if i in idx])

        valid_lr_imgs = tl.vis.read_images(valid_lr_img_list,
                                           path=train_lr_path,
                                           n_threads=32)
        valid_hr_imgs = tl.vis.read_images(valid_hr_img_list,
                                           path=train_hr_path,
                                           n_threads=32)

    train_lr_imgs = tl.vis.read_images(train_lr_img_list,
                                       path=train_lr_path,
                                       n_threads=32)
    train_hr_imgs = tl.vis.read_images(train_hr_img_list,
                                       path=train_hr_path,
                                       n_threads=32)

    ###======DEFINE MODEL======###
    ## train inference
    lr_image = tf.placeholder('float32', [None, 96, 96, 3], name='lr_image')
    hr_image = tf.placeholder('float32', [None, 192, 192, 3], name='hr_image')

    net_g = SRGAN_g(lr_image, is_train=True, reuse=False)
    net_d, logits_real = SRGAN_d(hr_image, is_train=True, reuse=False)
    _, logits_fake = SRGAN_d(net_g.outputs, is_train=True, reuse=True)

    # net_g.print_params(False)
    # net_g.print_layers()
    # net_d.print_params(False)
    # net_d.print_layers()

    ## resize original hr images for VGG19
    hr_image_224 = tf.image.resize_images(
        hr_image,
        size=[224, 224],
        method=0,  # BICUBIC
        align_corners=False)

    ## generated hr image for VGG19
    generated_image_224 = tf.image.resize_images(
        net_g.outputs,
        size=[224, 224],
        method=0,  #BICUBIC
        align_corners=False)

    ## scale image to [0,1] and get conv characteristics
    net_vgg, vgg_target_emb = Vgg19_simple_api((hr_image_224 + 1) / 2,
                                               reuse=False)
    _, vgg_predict_emb = Vgg19_simple_api((generated_image_224 + 1) / 2,
                                          reuse=True)

    ## test inference
    net_g_test = SRGAN_g(lr_image, is_train=False, reuse=True)

    ###======DEFINE TRAIN PROCESS======###
    d_loss1 = tl.cost.sigmoid_cross_entropy(logits_real,
                                            tf.ones_like(logits_real),
                                            name='d1')
    d_loss2 = tl.cost.sigmoid_cross_entropy(logits_fake,
                                            tf.zeros_like(logits_fake),
                                            name='d2')
    d_loss = d_loss1 + d_loss2

    prediction1 = tf.greater(logits_real, tf.fill(tf.shape(logits_real), 0.5))
    acc_metric1 = tf.reduce_mean(tf.cast(prediction1, tf.float32))
    prediction2 = tf.less(logits_fake, tf.fill(tf.shape(logits_fake), 0.5))
    acc_metric2 = tf.reduce_mean(tf.cast(prediction2, tf.float32))
    acc_metric = acc_metric1 + acc_metric2

    g_gan_loss = 1e-3 * tl.cost.sigmoid_cross_entropy(
        logits_fake, tf.ones_like(logits_fake), name='g')
    mse_loss = tl.cost.mean_squared_error(net_g.outputs,
                                          hr_image,
                                          is_mean=True)
    vgg_loss = 2e-6 * tl.cost.mean_squared_error(
        vgg_predict_emb.outputs, vgg_target_emb.outputs, is_mean=True)

    g_loss = mse_loss + g_gan_loss + vgg_loss

    psnr_metric = tf.image.psnr(net_g.outputs,
                                hr_image,
                                max_val=2.0,
                                name='psnr')

    g_vars = tl.layers.get_variables_with_name('SRGAN_g', True, True)
    d_vars = tl.layers.get_variables_with_name('SRGAN_d', True, True)

    with tf.variable_scope('learning_rate'):
        lr_v = tf.Variable(lr_init, trainable=False)

    ## Pretrain
    g_optim_init = tf.train.AdamOptimizer(lr_v, beta1=beta1).minimize(
        mse_loss, var_list=g_vars)

    ## SRGAN
    g_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(g_loss,
                                                           var_list=g_vars)
    d_optim = tf.train.AdamOptimizer(lr_v,
                                     beta1=beta1).minimize(d_loss,
                                                           var_list=d_vars)

    ###========================== RESTORE MODEL =============================###
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=False))
    sess.run(tf.global_variables_initializer())

    if tl.files.file_exists(os.path.join(checkpoint_dir, 'g_srgan.npz')):
        tl.files.load_and_assign_npz(sess=sess,
                                     name=os.path.join(checkpoint_dir,
                                                       'g_srgan.npz'),
                                     network=net_g)
    else:
        tl.files.load_and_assign_npz(sess=sess,
                                     name=os.path.join(checkpoint_dir,
                                                       'g_srgan_init.npz'),
                                     network=net_g)

    tl.files.load_and_assign_npz(sess=sess,
                                 name=os.path.join(checkpoint_dir,
                                                   'd_srgan.npz'),
                                 network=net_d)

    ###======LOAD VGG======###
    vgg19_npy_path = '../lib/SRGAN/vgg19.npy'
    npz = np.load(vgg19_npy_path, encoding='latin1').item()

    params = []
    for val in sorted(npz.items()):
        W = np.asarray(val[1][0])
        b = np.asarray(val[1][1])
        print("  Loading %s: %s, %s" % (val[0], W.shape, b.shape))
        params.extend([W, b])
    tl.files.assign_params(sess, params, net_vgg)
    # net_vgg.print_params(False)
    # net_vgg.print_layers()

    ###======TRAINING======###
    ## use train set to have a quick test during training
    ni = 4
    num_sample = ni * ni
    idx = np.random.choice(len(train_lr_imgs), num_sample, replace=False)
    sample_imgs_lr = tl.prepro.threading_data(
        [img for i, img in enumerate(train_lr_imgs) if i in idx],
        fn=crop_sub_imgs_fn,
        size=(96, 96),
        is_random=False)
    sample_imgs_hr = tl.prepro.threading_data(
        [img for i, img in enumerate(train_hr_imgs) if i in idx],
        fn=crop_sub_imgs_fn,
        size=(192, 192),
        is_random=False)

    print('sample LR sub-image:', sample_imgs_lr.shape, sample_imgs_lr.min(),
          sample_imgs_lr.max())
    print('sample HR sub-image:', sample_imgs_hr.shape, sample_imgs_hr.min(),
          sample_imgs_hr.max())

    ## save the images
    tl.vis.save_images(sample_imgs_lr, [ni, ni],
                       os.path.join(save_dir_ginit, '_train_sample_96.jpg'))
    tl.vis.save_images(sample_imgs_hr, [ni, ni],
                       os.path.join(save_dir_ginit, '_train_sample_192.jpg'))
    tl.vis.save_images(sample_imgs_lr, [ni, ni],
                       os.path.join(save_dir_gan, '_train_sample_96.jpg'))
    tl.vis.save_images(sample_imgs_hr, [ni, ni],
                       os.path.join(save_dir_gan, '_train_sample_192.jpg'))
    print('finish saving sample images')

    ###====== initialize G ======###
    ## fixed learning rate
    sess.run(tf.assign(lr_v, lr_init))
    print(" ** fixed learning rate: %f (for init G)" % lr_init)
    for epoch in range(0, n_epoch_init + 1):
        epoch_time = time.time()
        total_mse_loss, total_psnr, n_iter = 0, 0, 0

        # random shuffle the train set for each epoch
        random.shuffle(train_hr_imgs)

        for idx in range(0, len(train_lr_imgs), batch_size):
            step_time = time.time()
            b_imgs_192 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  size=(192, 192),
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_192,
                                                 fn=downsample_fn,
                                                 size=(96, 96))
            ## update G
            errM, metricP, _ = sess.run([mse_loss, psnr_metric, g_optim_init],
                                        {
                                            lr_image: b_imgs_96,
                                            hr_image: b_imgs_192
                                        })
            print("Epoch [%2d/%2d] %4d time: %4.2fs, mse: %.4f, psnr: %.4f " %
                  (epoch, n_epoch_init, n_iter, time.time() - step_time, errM,
                   metricP.mean()))
            total_mse_loss += errM
            total_psnr += metricP.mean()
            n_iter += 1
        log = "[*] Epoch: [%2d/%2d] time: %4.2fs, mse: %.4f, psnr: %.4f" % (
            epoch, n_epoch_init, time.time() - epoch_time,
            total_mse_loss / n_iter, total_psnr / n_iter)
        print(log)
        if validation:
            b_imgs_192_V = tl.prepro.threading_data(valid_hr_imgs,
                                                    fn=crop_sub_imgs_fn,
                                                    size=(192, 192),
                                                    is_random=True)
            b_imgs_96_V = tl.prepro.threading_data(b_imgs_192_V,
                                                   fn=downsample_fn,
                                                   size=(96, 96))
            errM_V, metricP_V, _ = sess.run(
                [mse_loss, psnr_metric, g_optim_init], {
                    lr_image: b_imgs_96_V,
                    hr_image: b_imgs_192_V
                })
            print("Validation | mse: %.4f, psnr: %.4f" %
                  (errM_V, metricP_V.mean()))

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % save_every_epoch == 0):
            out = sess.run(net_g_test.outputs, {lr_image: sample_imgs_lr})
            print("[*] save sample images")
            tl.vis.save_images(
                out, [ni, ni],
                os.path.join(save_dir_ginit, 'train_{}.jpg'.format(epoch)))

        ## save model
        if (epoch != 0) and (epoch % save_every_epoch == 0):
            tl.files.save_npz(net_g.all_params,
                              name=os.path.join(checkpoint_dir,
                                                'g_srgan_init.npz'),
                              sess=sess)

    ###========================= train GAN (SRGAN) =========================###
    ## Learning rate decay
    decay_every = int(n_epoch / 2) if int(n_epoch / 2) > 0 else 1

    for epoch in range(0, n_epoch + 1):

        # random shuffle the train set for each epoch
        random.shuffle(train_hr_imgs)

        ## update learning rate
        if epoch != 0 and (epoch % decay_every == 0):
            new_lr_decay = lr_decay**(epoch // decay_every)
            sess.run(tf.assign(lr_v, lr_init * new_lr_decay))
            log = " ** new learning rate: %f (for GAN)" % (lr_init *
                                                           new_lr_decay)
            print(log)
        elif epoch == 0:
            sess.run(tf.assign(lr_v, lr_init))
            log = " ** init lr: %f  decay_every_init: %d, lr_decay: %f (for GAN)" % (
                lr_init, decay_every, lr_decay)
            print(log)

        epoch_time = time.time()
        total_d_loss, total_g_loss, total_mse_loss, total_psnr, total_acc, n_iter = 0, 0, 0, 0, 0, 0

        for idx in range(0, len(train_lr_imgs), batch_size):
            step_time = time.time()
            b_imgs_192 = tl.prepro.threading_data(train_hr_imgs[idx:idx +
                                                                batch_size],
                                                  fn=crop_sub_imgs_fn,
                                                  size=(192, 192),
                                                  is_random=True)
            b_imgs_96 = tl.prepro.threading_data(b_imgs_192,
                                                 fn=downsample_fn,
                                                 size=(96, 96))
            ## update D
            errD, metricA, _ = sess.run([d_loss, acc_metric, d_optim], {
                lr_image: b_imgs_96,
                hr_image: b_imgs_192
            })
            ## update G
            errG, errM, metricP, _ = sess.run(
                [g_loss, mse_loss, psnr_metric, g_optim], {
                    lr_image: b_imgs_96,
                    hr_image: b_imgs_192
                })
            print(
                "Epoch [%2d/%2d] %4d time: %4.2fs, d_loss: %.4f g_loss: %.4f (mse: %.4f, psnr: %.4f, accuracy: %.4f)"
                % (epoch, n_epoch, n_iter, time.time() - step_time, errD, errG,
                   errM, metricP.mean(), metricA / 2))
            total_d_loss += errD
            total_g_loss += errG
            total_mse_loss += errM
            total_psnr += metricP.mean()
            total_acc += metricA / 2
            n_iter += 1

        log = "[*] Epoch: [%2d/%2d] time: %4.2fs, d_loss: %.4f g_loss: %.4f (mse: %4f, psnr: %.4f, accuracy: %.4f)" % (
            epoch, n_epoch, time.time() - epoch_time, total_d_loss / n_iter,
            total_g_loss / n_iter, total_mse_loss / n_iter,
            total_psnr / n_iter, total_acc / n_iter)
        print(log)

        if validation:
            b_imgs_192_V = tl.prepro.threading_data(valid_hr_imgs,
                                                    fn=crop_sub_imgs_fn,
                                                    size=(192, 192),
                                                    is_random=True)
            b_imgs_96_V = tl.prepro.threading_data(b_imgs_192_V,
                                                   fn=downsample_fn,
                                                   size=(96, 96))
            errM_V, metricP_V, _ = sess.run([mse_loss, psnr_metric, g_optim], {
                lr_image: b_imgs_96_V,
                hr_image: b_imgs_192_V
            })
            print("Validation | mse: %.4f, psnr: %.4f" %
                  (errM_V, metricP_V.mean()))

        ## quick evaluation on train set
        if (epoch != 0) and (epoch % save_every_epoch == 0):
            out = sess.run(net_g_test.outputs, {lr_image: sample_imgs_lr})
            print("[*] save images")
            tl.vis.save_images(
                out, [ni, ni],
                os.path.join(save_dir_gan, 'train_{}.jpg'.format(epoch)))

        ## save model
        if (epoch != 0) and (epoch % save_every_epoch == 0):
            tl.files.save_npz(net_g.all_params,
                              name=os.path.join(checkpoint_dir, 'g_srgan.npz'),
                              sess=sess)
            tl.files.save_npz(net_d.all_params,
                              name=os.path.join(checkpoint_dir, 'd_srgan.npz'),
                              sess=sess)