Advertisement
lamiastella

new loss still error

Nov 18th, 2018
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.31 KB | None | 0 0
  1. from __future__ import print_function
  2. import os
  3. import glob
  4. import scipy
  5.  
  6. import tensorflow as tf
  7. import numpy as np
  8. from PIL import Image
  9. import skimage.io as io
  10. import matplotlib.pyplot as plt
  11.  
  12.  
  13. class Arguments(object):
  14.     data_path = 'results_celebA/preprocessed/'                     #path to CelebA dataset
  15.     save_path = 'results_celebA'                           #path to save preprocessed image folder
  16.     preproc_foldername = 'preprocessed'      #folder name for preprocessed images
  17.     image_size = 64                          #images are resized to image_size value
  18.     num_images = 202590                      #the number of training images
  19.     batch_size = 64                          #batch size
  20.     dim_z = 100                              #the dimension of z variable (the generator input dimension)        
  21.     n_g_filters = 64                         #the number of the generator filters (gets multiplied between layers)
  22.     n_f_filters = 64                         #the number of the discriminator filters (gets multiplied between layers)          
  23.     n_epoch = 25                             #the number of epochs
  24.     lr = 0.0002                              #learning rate
  25.     beta1 = 0.5                              #beta_1 parameter of Adam optimizer
  26.     beta2 = 0.99                             #beta_2 parameter of Adam optimizer
  27.  
  28. args = Arguments()
  29.  
  30.  
  31.  
  32. class Dataset(object):    
  33.     def __init__(self, data_path, num_imgs, target_imgsize):
  34.         self.data_path = data_path
  35.         self.num_imgs = num_imgs
  36.         self.target_imgsize = target_imgsize
  37.    
  38.     def normalize_np_image(self, image):
  39.         return (image / 255.0 - 0.5) / 0.5
  40.    
  41.     def denormalize_np_image(self, image):
  42.         return (image * 0.5 + 0.5) * 255
  43.    
  44.     def get_input(self, image_path):
  45.         image = np.array(Image.open(image_path)).astype(np.float32)
  46.         return self.normalize_np_image(image)
  47.    
  48.     def get_imagelist(self, data_path, celebA=False):
  49.         if celebA == True:
  50.             imgs_path = os.path.join(data_path, 'img_align_celeba/*.jpg')
  51.         else:
  52.             imgs_path = os.path.join(data_path, '*.jpg')
  53.         all_namelist = glob.glob(imgs_path, recursive=True)
  54.         return all_namelist[:self.num_imgs]
  55.    
  56.     def load_and_preprocess_image(self, image_path):
  57.         image = Image.open(image_path)
  58.         j = (image.size[0] - 100) // 2
  59.         i = (image.size[1] - 100) // 2
  60.         image = image.crop([j, i, j + 100, i + 100])    
  61.         image = image.resize([self.target_imgsize, self.target_imgsize], Image.BILINEAR)
  62.         image = np.array(image.convert('RGB')).astype(np.float32)
  63.         image = self.normalize_np_image(image)
  64.         return image    
  65.    
  66.     #reads data, preprocesses and saves to another folder with the given path.
  67.     def preprocess_and_save_images(self, dir_name, save_path=''):
  68.         preproc_folder_path = os.path.join(save_path, dir_name)
  69.         if not os.path.exists(preproc_folder_path):
  70.             os.makedirs(preproc_folder_path)  
  71.             imgs_path = os.path.join(self.data_path, 'img_align_celeba/*.jpg')
  72.             print('Saving and preprocessing images ...')
  73.             for num, imgname in enumerate(glob.iglob(imgs_path, recursive=True)):
  74.                 cur_image = self.load_and_preprocess_image(imgname)
  75.                 cur_image = Image.fromarray(np.uint8(self.denormalize_np_image(cur_image)))
  76.                 cur_image.save(preproc_folder_path + '/preprocessed_image_%d.jpg' %(num))
  77.         self.data_path= preproc_folder_path
  78.            
  79.     def get_nextbatch(self, batch_size):
  80.         assert (batch_size > 0),"Give a valid batch size"
  81.         cur_idx = 0
  82.         image_namelist = self.get_imagelist(self.data_path)
  83.         while cur_idx + batch_size <= self.num_imgs:
  84.             cur_namelist = image_namelist[cur_idx:cur_idx + batch_size]
  85.             cur_batch = [self.get_input(image_path) for image_path in cur_namelist]
  86.             cur_batch = np.array(cur_batch).astype(np.float32)
  87.             cur_idx += batch_size
  88.             yield cur_batch
  89.      
  90.     def show_image(self, image, normalized=True):
  91.         if not type(image).__module__ == np.__name__:
  92.             image = image.numpy()
  93.         if normalized:
  94.             npimg = (image * 0.5) + 0.5
  95.         npimg.astype(np.uint8)
  96.         plt.imshow(npimg, interpolation='nearest')
  97.  
  98.  
  99.  
  100. def generator(x, args, reuse=False):
  101.     with tf.device('/gpu:0'):
  102.         with tf.variable_scope("generator", reuse=reuse):
  103.             #Layer Block 1
  104.             with tf.variable_scope("layer1"):
  105.                 deconv1 = tf.layers.conv2d_transpose(inputs=x,
  106.                                              filters= args.n_g_filters*8,
  107.                                              kernel_size=4,
  108.                                              strides=1,
  109.                                              padding='valid',
  110.                                              use_bias=False,
  111.                                              name='deconv')
  112.                 batch_norm1=tf.layers.batch_normalization(deconv1,
  113.                                              name = 'batch_norm')
  114.                 relu1 = tf.nn.relu(batch_norm1, name='relu')
  115.             #Layer Block 2
  116.             with tf.variable_scope("layer2"):
  117.                 deconv2 = tf.layers.conv2d_transpose(inputs=relu1,
  118.                                              filters=args.n_g_filters*4,
  119.                                              kernel_size=4,
  120.                                              strides=2,
  121.                                              padding='same',
  122.                                              use_bias=False,
  123.                                              name='deconv')
  124.                 batch_norm2 = tf.layers.batch_normalization(deconv2,
  125.                                              name = 'batch_norm')
  126.                 relu2 = tf.nn.relu(batch_norm2, name='relu')
  127.             #Layer Block 3
  128.             with tf.variable_scope("layer3"):
  129.                 deconv3 = tf.layers.conv2d_transpose(inputs=relu2,
  130.                                              filters=args.n_g_filters*2,
  131.                                              kernel_size=4,
  132.                                              strides=2,
  133.                                              padding='same',
  134.                                              use_bias = False,
  135.                                              name='deconv')
  136.                 batch_norm3 = tf.layers.batch_normalization(deconv3,
  137.                                              name = 'batch_norm')
  138.                 relu3 = tf.nn.relu(batch_norm3, name='relu')
  139.             #Layer Block 4
  140.             with tf.variable_scope("layer4"):
  141.                 deconv4 = tf.layers.conv2d_transpose(inputs=relu3,
  142.                                              filters=args.n_g_filters,
  143.                                              kernel_size=4,
  144.                                              strides=2,
  145.                                              padding='same',
  146.                                              use_bias=False,
  147.                                              name='deconv')
  148.                 batch_norm4 = tf.layers.batch_normalization(deconv4,
  149.                                              name = 'batch_norm')
  150.                 relu4 = tf.nn.relu(batch_norm4, name='relu')
  151.             #Output Layer
  152.             with tf.variable_scope("last_layer"):
  153.                 logit = tf.layers.conv2d_transpose(inputs=relu4,
  154.                                              filters=3,
  155.                                              kernel_size=4,
  156.                                              strides=2,
  157.                                              padding='same',
  158.                                              use_bias=False,
  159.                                              name='logit')
  160.                 output = tf.nn.tanh(logit)
  161.     return output, logit
  162.  
  163.  
  164.  
  165. def discriminator(x, args, reuse=False):
  166.     with tf.device('/gpu:0'):
  167.         with tf.variable_scope("discriminator", reuse=reuse):
  168.             with tf.variable_scope("layer1"):
  169.                 conv1 = tf.layers.conv2d(inputs=x,
  170.                                          filters=args.n_f_filters,
  171.                                          kernel_size=4,
  172.                                          strides=2,
  173.                                          padding='same',
  174.                                          use_bias=False,
  175.                                          name='conv')
  176.                 relu1 = tf.nn.leaky_relu(conv1, alpha=0.2, name='relu')
  177.             with tf.variable_scope("layer2"):
  178.                 conv2 = tf.layers.conv2d(inputs=relu1,
  179.                                          filters=args.n_f_filters*2,
  180.                                          kernel_size=4,
  181.                                          strides=2,
  182.                                          padding='same',
  183.                                          use_bias=False,
  184.                                          name='conv')
  185.                 batch_norm2 = tf.layers.batch_normalization(conv2,name='batch_norm')
  186.                 relu2 = tf.nn.leaky_relu(batch_norm2, alpha=0.2, name='relu')
  187.             with tf.variable_scope("layer3"):
  188.                 conv3 = tf.layers.conv2d(inputs=relu2,
  189.                                          filters=args.n_f_filters*4,
  190.                                          kernel_size=4,
  191.                                          strides=2,
  192.                                          padding='same',
  193.                                          use_bias=False,
  194.                                          name='conv')
  195.                 batch_norm3 = tf.layers.batch_normalization(conv3, name='batch_norm')
  196.                 relu3 = tf.nn.leaky_relu(batch_norm3, name='relu')
  197.             with tf.variable_scope("layer4"):
  198.                 conv4 = tf.layers.conv2d(inputs=relu3,
  199.                                          filters=args.n_f_filters*8,
  200.                                          kernel_size=4,
  201.                                          strides=2,
  202.                                          padding='same',
  203.                                          use_bias=False,
  204.                                          name='conv')
  205.                 batch_norm4 = tf.layers.batch_normalization(conv4, name='batch_norm')
  206.                 relu4 = tf.nn.leaky_relu(batch_norm4, alpha=0.2, name='relu')
  207.             with tf.variable_scope("last_layer"):
  208.                 logit = tf.layers.conv2d(inputs=relu4,
  209.                                          filters=1,
  210.                                          kernel_size=4,
  211.                                          strides=1,
  212.                                          padding='valid',
  213.                                          use_bias=False,
  214.                                          name='conv')
  215.                 output = tf.nn.sigmoid(logit)
  216.     return output, logit
  217.  
  218.  
  219.  
  220. def sample_z(dim_z, num_batch):
  221.     mu = 0
  222.     sigma = 1
  223.     s = np.random.normal(mu, sigma, num_batch*dim_z)
  224.     samples = s.reshape(num_batch, 1, 1, dim_z)
  225.  
  226.     return samples
  227.  
  228.  
  229.  
  230.  
  231. def generator_loss(fake):
  232.     loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(fake), logits=fake))
  233.  
  234.     return loss
  235.  
  236.  
  237. def discriminator_loss(real, fake):
  238.     real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.ones_like(real), logits=real))
  239.     fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=tf.zeros_like(fake), logits=fake))
  240.     loss = real_loss + fake_loss
  241.  
  242.     return loss
  243.  
  244.  
  245. def get_losses(d_real_logits, d_fake_logits):
  246. #    d_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_real_logits,labels=tf.ones_like(d_real_logits)) + tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits,labels=tf.zeros_like(d_fake_logits)))
  247. #    g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_fake_logits,labels=tf.ones_like(d_fake_logits)))
  248.  
  249.     d_loss = discriminator_loss(real=d_real_logits, fake=d_fake_logits)
  250.     g_loss = generator_loss(fake=d_fake_logits)
  251.  
  252.  
  253.     return d_loss, g_loss
  254.  
  255.  
  256. def get_optimizers(learning_rate, beta1, beta2):
  257.     d_optimizer = tf.train.AdamOptimizer(learning_rate, beta1, beta2)
  258.     g_optimizer = tf.train.AdamOptimizer(learning_rate, beta1, beta2)
  259.  
  260.     return d_optimizer, g_optimizer
  261.  
  262.  
  263. def optimize(d_optimizer, g_optimizer, d_loss, g_loss):
  264.     d_step = d_optimizer.minimize(d_loss)
  265.     g_step = g_optimizer.minimize(g_loss)
  266.  
  267.     return d_step, g_step
  268.  
  269.  
  270. LOGDIR = "logs_basic_dcgan"
  271.  
  272. def merge_images(image_batch, size):
  273.     h,w = image_batch.shape[1], image_batch.shape[2]
  274.     c = image_batch.shape[3]
  275.     img = np.zeros((int(h*size[0]), w*size[1], c))
  276.     for idx, im in enumerate(image_batch):
  277.         i = idx % size[1]
  278.         j = idx // size[1]
  279.         img[j*h:j*h+h, i*w:i*w+w,:] = im
  280.     return img
  281. itr_fh = open('basic_gan_itr.txt', 'a+')
  282.  
  283. def train(args):
  284.     tf.reset_default_graph()
  285.     data_loader = Dataset(args.data_path, args.num_images, args.image_size)
  286.     #data_loader.preprocess_and_save_images('preprocessed', 'results_celebA') #preprocess the images once
  287.     X = tf.placeholder(tf.float32, shape=[args.batch_size, args.image_size , args.image_size, 3])
  288.     Z = tf.placeholder(tf.float32, shape=[args.batch_size, 1, 1, args.dim_z])
  289.  
  290.     G_sample, _ = generator(Z, args)
  291.     D_real, D_real_logits = discriminator(X, args)
  292.     D_fake, D_fake_logits = discriminator(G_sample, args, reuse=True)
  293.     d_loss, g_loss = get_losses(D_real_logits, D_fake_logits)
  294.     d_optimizer, g_optimizer = get_optimizers(args.lr, args.beta1, args.beta2)
  295.     d_step, g_step = optimize(d_optimizer, g_optimizer, d_loss, g_loss)
  296.  
  297.  
  298.     with tf.Session() as sess:
  299.  
  300.         sess.run(tf.global_variables_initializer())
  301.         for epoch in range(args.n_epoch):
  302.             for itr, real_batch in enumerate(data_loader.get_nextbatch(args.batch_size)):
  303.                 print('itr is %d, and epoch is %d' %(itr, epoch))
  304.                 itr_fh.write("epoch: " +  str(epoch) + " itr: " + str(itr) + "\n")
  305.  
  306.                 Z_sample = sample_z(args.dim_z, args.batch_size)
  307.  
  308.                 sess.run(d_step, feed_dict={X:real_batch , Z:Z_sample})
  309.                 sess.run(g_step, feed_dict={X:real_batch , Z:Z_sample})
  310.  
  311.                 sample = sess.run(G_sample, feed_dict={Z:Z_sample})
  312.                 print("sample size is: ", sample.shape)
  313.                 if itr==3164: #num_images/batch_size
  314.                     im_merged = merge_images(sample[:16], [4,4])
  315.                     plt.imsave('sample_gan_images/im_merged_epoch_%d.png' %(epoch), im_merged )
  316.                     scipy.misc.imsave('sample_gan_images/im_epoch_%d_itr_%d.png' %(epoch,itr), sample[1])
  317.                     ##merged_summary = sess.run(merged_summary, feed_dict={X:real_batch , Z:Z_sample})
  318.                     ###writer = tf.summary.FileWriter(LOGDIR)  
  319.                     ###writer.add_summary(merged_summary, itr)
  320.                     ###d_loss_summary = tf.summary.scalar("Discriminator_Total_Loss", d_loss) #how to store loss at the end of each epoch not at each iteration?
  321.                     ###g_loss_summary = tf.summary.scalar("Generator_Total_Loss", g_loss)
  322.                     ###merged_summary = tf.summary.merge_all()
  323.                     ###writer.add_graph(sess.graph)
  324.                     ###saver.save(sess, save_path='logs_basic_dcgan/gan.ckpt')
  325.  
  326.  
  327. train(args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement