{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"s_monet1 = cv2.imread(\"../input/gan-getting-started/monet_jpg/000c1e3bff.jpg\")\ns_monet2 = cv2.imread(\"../input/gan-getting-started/monet_jpg/011835cfbf.jpg\")\ns_monet3 = cv2.imread(\"../input/gan-getting-started/monet_jpg/0260d15306.jpg\")\ns_monet4 = cv2.imread(\"../input/gan-getting-started/monet_jpg/049e293b93.jpg\")\nfig1,ax = plt.subplots(1,4,figsize = (16,16)) \nax[0].imshow(s_monet1)\nax[1].imshow(s_monet2)\nax[2].imshow(s_monet3)\nax[3].imshow(s_monet4)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:14.263321Z","iopub.execute_input":"2022-04-29T11:03:14.264016Z","iopub.status.idle":"2022-04-29T11:03:14.914794Z","shell.execute_reply.started":"2022-04-29T11:03:14.263978Z","shell.execute_reply":"2022-04-29T11:03:14.913289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"s_photo1 = cv2.imread(\"../input/gan-getting-started/photo_jpg/00068bc07f.jpg\")\ns_photo2 = cv2.imread(\"../input/gan-getting-started/photo_jpg/000910d219.jpg\")\ns_photo3 = cv2.imread(\"../input/gan-getting-started/photo_jpg/000ded5c41.jpg\")\ns_photo4 = cv2.imread(\"../input/gan-getting-started/photo_jpg/00104fd531.jpg\")\nfig2,ax = plt.subplots(1,4,figsize = (16,16))\nax[0].imshow(s_photo1)\nax[1].imshow(s_photo2)\nax[2].imshow(s_photo3)\nax[3].imshow(s_photo4)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:17.279249Z","iopub.execute_input":"2022-04-29T11:03:17.279901Z","iopub.status.idle":"2022-04-29T11:03:17.88295Z","shell.execute_reply.started":"2022-04-29T11:03:17.279862Z","shell.execute_reply":"2022-04-29T11:03:17.882269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(np.shape(s_monet4))\nnp.shape(s_photo4)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:21.727856Z","iopub.execute_input":"2022-04-29T11:03:21.728407Z","iopub.status.idle":"2022-04-29T11:03:21.734817Z","shell.execute_reply.started":"2022-04-29T11:03:21.728368Z","shell.execute_reply":"2022-04-29T11:03:21.73412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMG_WIDTH = np.shape(s_photo4)[0]\nIMG_HEIGHT = np.shape(s_photo4)[1]\nlr = 2e-4\nact_r = \"relu\" \nact_n = None\nreg = None\nreg1 = regularizers.l1()\nreg2 = regularizers.l2()\nopt1 = Adam(learning_rate = lr)\nopt2 = Adadelta(learning_rate = lr/2)\ninp_shape = np.shape(s_monet1)\nks = 16","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:24.513326Z","iopub.execute_input":"2022-04-29T11:03:24.513942Z","iopub.status.idle":"2022-04-29T11:03:24.526851Z","shell.execute_reply.started":"2022-04-29T11:03:24.513904Z","shell.execute_reply":"2022-04-29T11:03:24.52616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\nGCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:26.489854Z","iopub.execute_input":"2022-04-29T11:03:26.490126Z","iopub.status.idle":"2022-04-29T11:03:26.892242Z","shell.execute_reply.started":"2022-04-29T11:03:26.490096Z","shell.execute_reply":"2022-04-29T11:03:26.891483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nMONET_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/monet_tfrec/*.tfrec'))\nprint('Monet TFRecord Files:', len(MONET_FILENAMES))\n\nPHOTO_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/photo_tfrec/*.tfrec'))\nprint('Photo TFRecord Files:', len(PHOTO_FILENAMES))","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:29.998317Z","iopub.execute_input":"2022-04-29T11:03:29.99888Z","iopub.status.idle":"2022-04-29T11:03:30.162105Z","shell.execute_reply.started":"2022-04-29T11:03:29.998844Z","shell.execute_reply":"2022-04-29T11:03:30.161406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [IMG_WIDTH,IMG_HEIGHT]\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = (tf.cast(image, tf.float32) / 127.5) - 1\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_tfrecord(example):\n    tfrecord_format = {\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"target\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    return image","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:33.704125Z","iopub.execute_input":"2022-04-29T11:03:33.704675Z","iopub.status.idle":"2022-04-29T11:03:33.713224Z","shell.execute_reply.started":"2022-04-29T11:03:33.70463Z","shell.execute_reply":"2022-04-29T11:03:33.712562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.data.experimental import AUTOTUNE\ndef load_dataset(filenames, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:35.686208Z","iopub.execute_input":"2022-04-29T11:03:35.686489Z","iopub.status.idle":"2022-04-29T11:03:35.695037Z","shell.execute_reply.started":"2022-04-29T11:03:35.686456Z","shell.execute_reply":"2022-04-29T11:03:35.694194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_ds = load_dataset(MONET_FILENAMES, labeled=True).batch(1)\nphoto_ds = load_dataset(PHOTO_FILENAMES, labeled=True).batch(1)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:37.241319Z","iopub.execute_input":"2022-04-29T11:03:37.241903Z","iopub.status.idle":"2022-04-29T11:03:39.749985Z","shell.execute_reply.started":"2022-04-29T11:03:37.241864Z","shell.execute_reply":"2022-04-29T11:03:39.749256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:42.812243Z","iopub.execute_input":"2022-04-29T11:03:42.812957Z","iopub.status.idle":"2022-04-29T11:03:43.533235Z","shell.execute_reply.started":"2022-04-29T11:03:42.81292Z","shell.execute_reply":"2022-04-29T11:03:43.53248Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.subplot(121)\nplt.title('Photo')\nplt.imshow(example_photo[0]*0.5+0.5)\nplt.show()\nplt.subplot(122)\nplt.title('Monet')\nplt.imshow(example_monet[0] * 0.5 + 0.5)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:48.532161Z","iopub.execute_input":"2022-04-29T11:03:48.532442Z","iopub.status.idle":"2022-04-29T11:03:48.91209Z","shell.execute_reply.started":"2022-04-29T11:03:48.532398Z","shell.execute_reply":"2022-04-29T11:03:48.911441Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport tensorflow_addons as tfa","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:51.994223Z","iopub.execute_input":"2022-04-29T11:03:51.994821Z","iopub.status.idle":"2022-04-29T11:03:52.111653Z","shell.execute_reply.started":"2022-04-29T11:03:51.99478Z","shell.execute_reply":"2022-04-29T11:03:52.110959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def downsample(filters,size,apply_instancenorm = False):\n        initializer = tf.random_normal_initializer(0.,0.02)\n        gamma_init = tf.keras.initializers.RandomNormal(mean = 0.0,stddev = 0.02)\n        result = tf.keras.Sequential()\n        result.add(Conv2D(filters,size,strides = 2,padding = \"same\",kernel_regularizer = reg ,kernel_initializer = initializer,use_bias = False,activation = act_r))\n        if apply_instancenorm:\n            result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n        else:\n             result.add(BatchNormalization(gamma_initializer=gamma_init))\n        return result","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:54.452862Z","iopub.execute_input":"2022-04-29T11:03:54.453719Z","iopub.status.idle":"2022-04-29T11:03:54.461534Z","shell.execute_reply.started":"2022-04-29T11:03:54.453668Z","shell.execute_reply":"2022-04-29T11:03:54.460816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.layers import Conv2DTranspose\ndef upsample(filters,size,dropout = True,apply_instancenorm = False,):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.02) \n    result = tf.keras.Sequential()\n    result.add(Conv2DTranspose(filters,size,strides = 2,padding = \"same\",kernel_regularizer = reg,kernel_initializer = initializer,use_bias = False,activation = act_r))\n    if apply_instancenorm:\n        result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n    else:\n        result.add(BatchNormalization(gamma_initializer=gamma_init))\n    if dropout:\n        result.add(Dropout(0.2))\n    return result    ","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:56.463616Z","iopub.execute_input":"2022-04-29T11:03:56.464153Z","iopub.status.idle":"2022-04-29T11:03:56.47499Z","shell.execute_reply.started":"2022-04-29T11:03:56.464113Z","shell.execute_reply":"2022-04-29T11:03:56.474261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = Input(shape = inp_shape)\n    n = int(math.log(inp_shape[0],2))\n    n0 = 2\n    down_lst = []\n    up_lst = []\n    k = []\n    for i in range(n-n0):\n        k.append(2*(2**i))\n        if i == n-n0 -1:\n            k.append(2*(2**i))\n            k.append(2*(2**i))\n    kr = k.copy()\n    kr.reverse()\n    for i in k:\n        down_lst.append(downsample(ks*i,4,apply_instancenorm =False ))\n    for i in kr:\n        up_lst.append(upsample(ks*i,4,dropout = True,apply_instancenorm = False))\n        \n    initializer = tf.random_normal_initializer(0.,0.02)\n    last = Conv2DTranspose(3,4,strides = 2,padding = \"same\",kernel_initializer =initializer,activation = \"tanh\")\n    x = inputs\n    skips = []\n    for down in down_lst:\n        x = down(x)\n        skips.append(x)\n    skips = reversed(skips[:-1])\n    for up,skip in zip(up_lst,skips):\n        x = up(x)\n        x = tf.keras.layers.Concatenate()([x,skip])\n    x = last(x)\n    \n    return Model(inputs = inputs,outputs = x)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:03:58.262232Z","iopub.execute_input":"2022-04-29T11:03:58.2628Z","iopub.status.idle":"2022-04-29T11:03:58.273175Z","shell.execute_reply.started":"2022-04-29T11:03:58.262759Z","shell.execute_reply":"2022-04-29T11:03:58.27232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gen1 = Generator()\ntf.keras.utils.plot_model(gen1,show_shapes = True,dpi = 50)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:04:03.727529Z","iopub.execute_input":"2022-04-29T11:04:03.728069Z","iopub.status.idle":"2022-04-29T11:04:05.217168Z","shell.execute_reply.started":"2022-04-29T11:04:03.728031Z","shell.execute_reply":"2022-04-29T11:04:05.216394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gen1.summary()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:04:19.338216Z","iopub.execute_input":"2022-04-29T11:04:19.338831Z","iopub.status.idle":"2022-04-29T11:04:19.361572Z","shell.execute_reply.started":"2022-04-29T11:04:19.338784Z","shell.execute_reply":"2022-04-29T11:04:19.360915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def Discriminator():\n#     initializer = tf.random_normal_initializer(0.,0.02)\n#     gamma_init = tf.keras.initializers.RandomNormal(mean=0.0,stddev=0.2)\n#     inp = Input(shape = inp_shape,name = \"input_image\")\n#     d1 = downsample(ks*4,4,False)(inp)\n#     d2 = downsample(ks*8,4,False)(d1)\n#     d3 = downsample(ks*16,4,False)(d2)\n#     d4 = downsample(ks*32,4,False)(d3)\n#     d5 = Dropout(0.2)(d4)\n#     last = Conv2D(1,4,strides = 1,kernel_initializer = initializer)(d5)\n#     return Model(inputs = inp,outputs = last) ","metadata":{"execution":{"iopub.status.busy":"2022-02-19T18:32:26.377822Z","iopub.execute_input":"2022-02-19T18:32:26.37817Z","iopub.status.idle":"2022-02-19T18:32:26.383505Z","shell.execute_reply.started":"2022-02-19T18:32:26.378112Z","shell.execute_reply":"2022-02-19T18:32:26.382303Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    inp = Input(shape=[256, 256, 3], name='input_image')\n\n    x = inp\n\n    down1 = downsample(64, 4, False)(x) \n    down2 = downsample(128, 4)(down1) \n    down3 = downsample(256, 4)(down2) \n\n    zero_pad1 = tf.keras.layers.ZeroPadding2D()(down3) \n    conv = Conv2D(512, 4, strides=1,\n                         kernel_initializer=initializer,\n                         use_bias=False)(zero_pad1)\n\n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n\n    leaky_relu = LeakyReLU()(norm1)\n\n    zero_pad2 = tf.keras.layers.ZeroPadding2D()(leaky_relu) \n    last = Conv2D(1, 4, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) \n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:05:33.752175Z","iopub.execute_input":"2022-04-29T11:05:33.752728Z","iopub.status.idle":"2022-04-29T11:05:33.763505Z","shell.execute_reply.started":"2022-04-29T11:05:33.75269Z","shell.execute_reply":"2022-04-29T11:05:33.762778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"disc1 = Discriminator()\ntf.keras.utils.plot_model(disc1,show_shapes = True,dpi = 64)    ","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:05:36.727555Z","iopub.execute_input":"2022-04-29T11:05:36.728252Z","iopub.status.idle":"2022-04-29T11:05:37.402219Z","shell.execute_reply.started":"2022-04-29T11:05:36.728208Z","shell.execute_reply":"2022-04-29T11:05:37.401423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_generator = Generator() # transforms photos to Monet-esque paintings\nphoto_generator = Generator() # transforms Monet paintings to be more like photos\nmonet_discriminator = Discriminator() # differentiates real Monet paintings and generated Monet paintings\nphoto_discriminator = Discriminator() # differentiates real photos and generated photos","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:05:51.904375Z","iopub.execute_input":"2022-04-29T11:05:51.905028Z","iopub.status.idle":"2022-04-29T11:05:52.980639Z","shell.execute_reply.started":"2022-04-29T11:05:51.904986Z","shell.execute_reply":"2022-04-29T11:05:52.979924Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(Model):\n    def __init__(\n        self,\n        monet_generator,\n        photo_generator,\n        monet_discriminator,\n        photo_discriminator,\n        lambda_cycle=10,\n    ):\n        super(CycleGan, self).__init__()\n        self.m_gen = monet_generator\n        self.p_gen = photo_generator\n        self.m_disc = monet_discriminator\n        self.p_disc = photo_discriminator\n        self.lambda_cycle = lambda_cycle\n        \n    def compile(\n        self,\n        m_gen_optimizer,\n        p_gen_optimizer,\n        m_disc_optimizer,\n        p_disc_optimizer,\n        gen_loss_fn,\n        disc_loss_fn,\n        cycle_loss_fn,\n        identity_loss_fn\n    ):\n        super(CycleGan, self).compile()\n        self.m_gen_optimizer = m_gen_optimizer\n        self.p_gen_optimizer = p_gen_optimizer\n        self.m_disc_optimizer = m_disc_optimizer\n        self.p_disc_optimizer = p_disc_optimizer\n        self.gen_loss_fn = gen_loss_fn\n        self.disc_loss_fn = disc_loss_fn\n        self.cycle_loss_fn = cycle_loss_fn\n        self.identity_loss_fn = identity_loss_fn\n        \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        \n        with tf.GradientTape(persistent=True) as tape:\n            # photo to monet back to photo\n            fake_monet = self.m_gen(real_photo, training=True)\n            cycled_photo = self.p_gen(fake_monet, training=True)\n\n            # monet to photo back to monet\n            fake_photo = self.p_gen(real_monet, training=True)\n            cycled_monet = self.m_gen(fake_photo, training=True)\n\n            # generating itself\n            same_monet = self.m_gen(real_monet, training=True)\n            same_photo = self.p_gen(real_photo, training=True)\n\n            # discriminator used to check, inputing real images\n            disc_real_monet = self.m_disc(real_monet, training=True)\n            disc_real_photo = self.p_disc(real_photo, training=True)\n\n            # discriminator used to check, inputing fake images\n            disc_fake_monet = self.m_disc(fake_monet, training=True)\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n\n            # evaluates generator loss\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo)\n\n            # evaluates total cycle consistency loss\n            total_cycle_loss = self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle) + self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle)\n\n            # evaluates total generator loss\n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss + self.identity_loss_fn(real_monet, same_monet, self.lambda_cycle)\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + self.identity_loss_fn(real_photo, same_photo, self.lambda_cycle)\n\n            # evaluates discriminator loss\n            monet_disc_loss = self.disc_loss_fn(disc_real_monet, disc_fake_monet)\n            photo_disc_loss = self.disc_loss_fn(disc_real_photo, disc_fake_photo)\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss,\n                                                  self.m_gen.trainable_variables)\n        photo_generator_gradients = tape.gradient(total_photo_gen_loss,\n                                                  self.p_gen.trainable_variables)\n\n        monet_discriminator_gradients = tape.gradient(monet_disc_loss,\n                                                      self.m_disc.trainable_variables)\n        photo_discriminator_gradients = tape.gradient(photo_disc_loss,\n                                                      self.p_disc.trainable_variables)\n\n        # Apply the gradients to the optimizer\n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients,\n                                                 self.m_gen.trainable_variables))\n\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients,\n                                                 self.p_gen.trainable_variables))\n\n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients,\n                                                  self.m_disc.trainable_variables))\n\n        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients,\n                                                  self.p_disc.trainable_variables))\n        \n        return {\n            \"monet_gen_loss\": total_monet_gen_loss,\n            \"photo_gen_loss\": total_photo_gen_loss,\n            \"monet_disc_loss\": monet_disc_loss,\n            \"photo_disc_loss\": photo_disc_loss\n        } \n    ","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:41.475256Z","iopub.execute_input":"2022-04-29T11:07:41.475544Z","iopub.status.idle":"2022-04-29T11:07:41.495531Z","shell.execute_reply.started":"2022-04-29T11:07:41.475513Z","shell.execute_reply":"2022-04-29T11:07:41.492945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def discriminator_loss(real, generated):\n        real_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(real), real)\n\n        generated_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(generated), generated)\n\n        total_disc_loss = real_loss + generated_loss\n\n        return total_disc_loss * 0.5","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:41.88609Z","iopub.execute_input":"2022-04-29T11:07:41.88632Z","iopub.status.idle":"2022-04-29T11:07:41.891946Z","shell.execute_reply.started":"2022-04-29T11:07:41.886287Z","shell.execute_reply":"2022-04-29T11:07:41.891259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def generator_loss(generated):\n    return tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(generated), generated)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:42.297087Z","iopub.execute_input":"2022-04-29T11:07:42.297402Z","iopub.status.idle":"2022-04-29T11:07:42.303981Z","shell.execute_reply.started":"2022-04-29T11:07:42.29737Z","shell.execute_reply":"2022-04-29T11:07:42.303305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def calc_cycle_loss(real_image, cycled_image, LAMBDA):\n        loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n\n        return LAMBDA * loss1","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:42.741528Z","iopub.execute_input":"2022-04-29T11:07:42.742079Z","iopub.status.idle":"2022-04-29T11:07:42.746631Z","shell.execute_reply.started":"2022-04-29T11:07:42.742041Z","shell.execute_reply":"2022-04-29T11:07:42.745914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def identity_loss(real_image, same_image, LAMBDA):\n        loss = tf.reduce_mean(tf.abs(real_image - same_image))\n        return LAMBDA * 0.5 * loss","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:43.339574Z","iopub.execute_input":"2022-04-29T11:07:43.340098Z","iopub.status.idle":"2022-04-29T11:07:43.344272Z","shell.execute_reply.started":"2022-04-29T11:07:43.340058Z","shell.execute_reply":"2022-04-29T11:07:43.343464Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# monet_generator_optimizer = opt1\n# photo_generator_optimizer = opt1\n# monet_discriminator_optimizer = opt1\n# photo_discriminator_optimizer = opt1\nmonet_generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\nphoto_generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n\nmonet_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\nphoto_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:43.812498Z","iopub.execute_input":"2022-04-29T11:07:43.812892Z","iopub.status.idle":"2022-04-29T11:07:43.819223Z","shell.execute_reply.started":"2022-04-29T11:07:43.812852Z","shell.execute_reply":"2022-04-29T11:07:43.8174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cycle_gan_model = CycleGan(monet_generator, photo_generator, monet_discriminator, photo_discriminator)\ncycle_gan_model.compile(\nm_gen_optimizer = monet_generator_optimizer,\np_gen_optimizer = photo_generator_optimizer,\nm_disc_optimizer = monet_discriminator_optimizer,\np_disc_optimizer = photo_discriminator_optimizer,\ngen_loss_fn = generator_loss,\ndisc_loss_fn = discriminator_loss,\ncycle_loss_fn = calc_cycle_loss,\nidentity_loss_fn = identity_loss)\n","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:44.23715Z","iopub.execute_input":"2022-04-29T11:07:44.23766Z","iopub.status.idle":"2022-04-29T11:07:44.261048Z","shell.execute_reply.started":"2022-04-29T11:07:44.237624Z","shell.execute_reply":"2022-04-29T11:07:44.260444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cycle_gan_model.fit(\n    tf.data.Dataset.zip((monet_ds, photo_ds)),\n    epochs=5)","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:07:44.88558Z","iopub.execute_input":"2022-04-29T11:07:44.886413Z","iopub.status.idle":"2022-04-29T11:23:14.244242Z","shell.execute_reply.started":"2022-04-29T11:07:44.886363Z","shell.execute_reply":"2022-04-29T11:23:14.24326Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i, img in enumerate(monet_ds.take(1)):\n    prediction = monet_generator(img, training=False)[0].numpy()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:24:29.782192Z","iopub.execute_input":"2022-04-29T11:24:29.78248Z","iopub.status.idle":"2022-04-29T11:24:29.958122Z","shell.execute_reply.started":"2022-04-29T11:24:29.782447Z","shell.execute_reply":"2022-04-29T11:24:29.957387Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, ax = plt.subplots(5, 2, figsize=(12, 12))\nfor i, img in enumerate(photo_ds.take(5)):\n    prediction = monet_generator(img, training=False)[0].numpy()\n    prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n    img = (img[0] * 127.5 + 127.5).numpy().astype(np.uint8)\n\n    ax[i, 0].imshow(img)\n    ax[i, 1].imshow(prediction)\n    ax[i, 0].set_title(\"Input Photo\")\n    ax[i, 1].set_title(\"Monet-esque\")\n    ax[i, 0].axis(\"off\")\n    ax[i, 1].axis(\"off\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-29T11:24:43.782998Z","iopub.execute_input":"2022-04-29T11:24:43.783247Z","iopub.status.idle":"2022-04-29T11:24:44.962386Z","shell.execute_reply.started":"2022-04-29T11:24:43.783219Z","shell.execute_reply":"2022-04-29T11:24:44.961717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2022-02-18T16:08:44.346797Z","iopub.execute_input":"2022-02-18T16:08:44.347319Z","iopub.status.idle":"2022-02-18T16:08:44.356851Z","shell.execute_reply.started":"2022-02-18T16:08:44.347281Z","shell.execute_reply":"2022-02-18T16:08:44.355979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}