{"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":"import warnings\nwarnings.simplefilter('ignore')\nimport os\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow.keras.layers as tfl\nimport tensorflow_addons as tfa\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import image as Image\nimport cv2","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:05.426375Z","iopub.execute_input":"2023-09-15T20:20:05.426979Z","iopub.status.idle":"2023-09-15T20:20:21.077385Z","shell.execute_reply.started":"2023-09-15T20:20:05.426945Z","shell.execute_reply":"2023-09-15T20:20:21.076345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint('Number of replicas:', strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:21.079431Z","iopub.execute_input":"2023-09-15T20:20:21.080405Z","iopub.status.idle":"2023-09-15T20:20:21.100431Z","shell.execute_reply.started":"2023-09-15T20:20:21.080369Z","shell.execute_reply":"2023-09-15T20:20:21.099389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_filenames = tf.io.gfile.glob(\"/kaggle/input/gan-getting-started/monet_tfrec/*.tfrec\")\nprint(\"Monet TFReord Files: \", len(monet_filenames))\n\nphoto_filenames = tf.io.gfile.glob(\"/kaggle/input/gan-getting-started/photo_tfrec/*.tfrec\")\nprint('Monet TFRecord Files:', len(photo_filenames))\n\nprint(monet_filenames[0])","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:21.101875Z","iopub.execute_input":"2023-09-15T20:20:21.102223Z","iopub.status.idle":"2023-09-15T20:20:21.131067Z","shell.execute_reply.started":"2023-09-15T20:20:21.102192Z","shell.execute_reply":"2023-09-15T20:20:21.130269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_monet = Image.imread(\"/kaggle/input/gan-getting-started/photo_jpg/00068bc07f.jpg\")\nprint(image_monet.shape)\nplt.imshow(image_monet)\nplt.show()\n\nmonet_jpg_filepath = \"/kaggle/input/gan-getting-started/monet_jpg\"\nphoto_jpg_filepath = \"/kaggle/input/gan-getting-started/photo_jpg\"","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:21.135923Z","iopub.execute_input":"2023-09-15T20:20:21.136236Z","iopub.status.idle":"2023-09-15T20:20:21.609700Z","shell.execute_reply.started":"2023-09-15T20:20:21.136198Z","shell.execute_reply":"2023-09-15T20:20:21.608844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_image_paths = []\n\nfor dirname, _, filenames in os.walk(monet_jpg_filepath):\n    for filename in filenames:\n        fullpath = os.path.join(dirname, filename)\n        monet_image_paths.append(fullpath)\n\nmonet_image_paths[:2]","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:21.610643Z","iopub.execute_input":"2023-09-15T20:20:21.610965Z","iopub.status.idle":"2023-09-15T20:20:21.714461Z","shell.execute_reply.started":"2023-09-15T20:20:21.610932Z","shell.execute_reply":"2023-09-15T20:20:21.713466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"others_image_paths = []\nfor dirname, _, filenames in os.walk(photo_jpg_filepath):\n    for filename in filenames:\n        fullpath = os.path.join(dirname, filename)\n        others_image_paths.append(fullpath)\n        \nothers_image_paths[:2]","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:21.716106Z","iopub.execute_input":"2023-09-15T20:20:21.716475Z","iopub.status.idle":"2023-09-15T20:20:30.430895Z","shell.execute_reply.started":"2023-09-15T20:20:21.716442Z","shell.execute_reply":"2023-09-15T20:20:30.429806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of other imgs: \", len(others_image_paths))\nprint(\"Number of Monet imgs: \", len(monet_image_paths))","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:30.433227Z","iopub.execute_input":"2023-09-15T20:20:30.434326Z","iopub.status.idle":"2023-09-15T20:20:30.440184Z","shell.execute_reply.started":"2023-09-15T20:20:30.434270Z","shell.execute_reply":"2023-09-15T20:20:30.439196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"figure, ax = plt.subplots(nrows=3, ncols=3, figsize=(15,15))\n\nfor i, image_path in enumerate(monet_image_paths):\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    try:\n        ax.ravel()[i].imshow(image)\n        ax.ravel()[i].set_axis_off()\n    except:\n        continue\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:30.441535Z","iopub.execute_input":"2023-09-15T20:20:30.442573Z","iopub.status.idle":"2023-09-15T20:20:36.240267Z","shell.execute_reply.started":"2023-09-15T20:20:30.442539Z","shell.execute_reply":"2023-09-15T20:20:36.239008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"figure, ax = plt.subplots(nrows=3, ncols=3, figsize=(15,15))\n\nfor i, image_path in enumerate(others_image_paths):\n    image = cv2.imread(image_path)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    \n    try:\n        ax.ravel()[i].imshow(image)\n        ax.ravel()[i].set_axis_off()\n    except:\n        continue\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:20:36.243524Z","iopub.execute_input":"2023-09-15T20:20:36.245533Z","iopub.status.idle":"2023-09-15T20:21:57.136727Z","shell.execute_reply.started":"2023-09-15T20:20:36.245496Z","shell.execute_reply":"2023-09-15T20:21:57.135370Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model creation\n\nIMAGE_SIZE = [256, 256]\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    \n    return image","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:21:57.142770Z","iopub.execute_input":"2023-09-15T20:21:57.143431Z","iopub.status.idle":"2023-09-15T20:21:57.150259Z","shell.execute_reply.started":"2023-09-15T20:21:57.143395Z","shell.execute_reply":"2023-09-15T20:21:57.149119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":"2023-09-15T20:21:57.152108Z","iopub.execute_input":"2023-09-15T20:21:57.152565Z","iopub.status.idle":"2023-09-15T20:21:57.163002Z","shell.execute_reply.started":"2023-09-15T20:21:57.152533Z","shell.execute_reply":"2023-09-15T20:21:57.161965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filenames, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls = AUTOTUNE)\n    \n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:21:57.164778Z","iopub.execute_input":"2023-09-15T20:21:57.165181Z","iopub.status.idle":"2023-09-15T20:21:57.176230Z","shell.execute_reply.started":"2023-09-15T20:21:57.165149Z","shell.execute_reply":"2023-09-15T20:21:57.175170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_df = load_dataset(monet_filenames, labeled=True).batch(1)\nphoto_df = load_dataset(photo_filenames, labeled=True).batch(1)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:21:57.177858Z","iopub.execute_input":"2023-09-15T20:21:57.178215Z","iopub.status.idle":"2023-09-15T20:22:03.617846Z","shell.execute_reply.started":"2023-09-15T20:21:57.178186Z","shell.execute_reply":"2023-09-15T20:22:03.616782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.subplot(121)\nplt.title('Monet')\nplt.imshow(next(iter(monet_df))[0]*0.6 + 0.5)\n\nplt.subplot(122)\nplt.title('Photo')\nplt.imshow(next(iter(photo_df))[0]*0.6 + 0.5)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:03.620217Z","iopub.execute_input":"2023-09-15T20:22:03.620534Z","iopub.status.idle":"2023-09-15T20:22:04.412639Z","shell.execute_reply.started":"2023-09-15T20:22:03.620508Z","shell.execute_reply":"2023-09-15T20:22:04.411681Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CHANNELS = 3\n\ndef downsample(filters, size, instancenorm = True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    model = keras.Sequential()\n    model.add(tfl.Conv2D(filters = filters, kernel_size = size, strides = 2, padding='same',\n                             kernel_initializer = initializer, use_bias=False))\n\n    if instancenorm:\n        model.add(tfa.layers.InstanceNormalization(gamma_initializer = gamma_init))\n\n    model.add(tfl.LeakyReLU())\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:04.414124Z","iopub.execute_input":"2023-09-15T20:22:04.415570Z","iopub.status.idle":"2023-09-15T20:22:04.424484Z","shell.execute_reply.started":"2023-09-15T20:22:04.415518Z","shell.execute_reply":"2023-09-15T20:22:04.423146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def upsample(filters, size, dropout = False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    model = keras.Sequential()\n    model.add(tfl.Conv2DTranspose(filters = filters, kernel_size = size, strides = 2,\n                                      padding = 'same',\n                                      kernel_initializer = initializer,\n                                      use_bias = False))\n\n    model.add(tfa.layers.InstanceNormalization(gamma_initializer = gamma_init))\n\n    if dropout:\n        model.add(tfl.Dropout(0.5)) #We tried to change dropout to 0.2 but it was throwing an error\n\n    model.add(tfl.ReLU())\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:04.426157Z","iopub.execute_input":"2023-09-15T20:22:04.426846Z","iopub.status.idle":"2023-09-15T20:22:04.443044Z","shell.execute_reply.started":"2023-09-15T20:22:04.426811Z","shell.execute_reply":"2023-09-15T20:22:04.441960Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = tfl.Input(shape=[256,256,3])\n\n    down_stack = [\n        downsample(filters = 64, size = 4, instancenorm = False), # Every Downstack layer has stride = 2\n        downsample(filters = 128, size = 4),\n        downsample(filters = 256, size = 4),\n        downsample(filters = 512, size = 4),\n        downsample(filters = 512, size = 4),\n        downsample(filters = 512, size = 4),\n        downsample(filters = 512, size = 4),\n        downsample(filters = 512, size = 4),\n    ]\n\n    up_stack = [\n        upsample(filters = 512, size = 4, dropout = True), # (bs, 2, 2, 1024)\n        upsample(filters = 512, size = 4, dropout = True), # (bs, 4, 4, 1024)\n        upsample(filters = 512, size = 4, dropout = True), # (bs, 8, 8, 1024)\n        upsample(filters = 512, size = 4), # (bs, 16, 16, 1024)\n        upsample(256, 4),\n        upsample(128, 4),\n        upsample(64, 4),\n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last_layer = tfl.Conv2DTranspose(CHANNELS, kernel_size = 4, strides = 2, padding='same',\n                                  kernel_initializer = initializer,\n                                  activation = 'tanh')\n\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down_layer in down_stack:\n        x = down_layer(x)\n        skips.append(x)\n\n    skips = reversed(skips[:-1])\n\n    # Upsampling and establishing the skip connections\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = tfl.Concatenate()([x, skip])\n\n    x = last_layer(x)\n\n    return keras.Model(inputs = inputs, outputs = x)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:04.445398Z","iopub.execute_input":"2023-09-15T20:22:04.446161Z","iopub.status.idle":"2023-09-15T20:22:04.458585Z","shell.execute_reply.started":"2023-09-15T20:22:04.446122Z","shell.execute_reply":"2023-09-15T20:22:04.457694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    x = tfl.Input(shape=[256, 256, 3])\n    \n    \n    #Down layers are Conv2D layers with their own initializers and leakyReLU activation\n    \n    down_layer_1 = downsample(filters = 64, size = 4,instancenorm = False)(x)\n    down_layer_2 = downsample(filters = 128, size = 4)(down_layer_1)\n    down_layer_3 = downsample(filters = 256, size = 4)(down_layer_2) \n\n    zero_pad1 = tfl.ZeroPadding2D(padding = 2)(down_layer_3)\n    conv_layer_1 = tfl.Conv2D(filters = 512, kernel_size = 4, strides = 2,\n                         kernel_initializer = initializer, use_bias=False)(zero_pad1)\n\n    norm_1 = tfa.layers.InstanceNormalization(gamma_initializer = gamma_init)(conv_layer_1)\n\n    leaky_relu_1 = tfl.LeakyReLU()(norm_1)\n\n    zero_pad2 = tfl.ZeroPadding2D()(leaky_relu_1)\n    \n    last_layer = tfl.Conv2D(filters = 1, kernel_size = 4, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) \n\n    return keras.Model(inputs = x, outputs = last_layer)","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:04.461514Z","iopub.execute_input":"2023-09-15T20:22:04.462007Z","iopub.status.idle":"2023-09-15T20:22:04.477402Z","shell.execute_reply.started":"2023-09-15T20:22:04.461927Z","shell.execute_reply":"2023-09-15T20:22:04.476234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() \n    photo_generator = Generator() \n\n    monet_discriminator = Discriminator() \n    photo_discriminator = Discriminator()","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:04.480479Z","iopub.execute_input":"2023-09-15T20:22:04.480738Z","iopub.status.idle":"2023-09-15T20:22:07.873801Z","shell.execute_reply.started":"2023-09-15T20:22:04.480711Z","shell.execute_reply":"2023-09-15T20:22:07.872822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(keras.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        }","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:07.875249Z","iopub.execute_input":"2023-09-15T20:22:07.875616Z","iopub.status.idle":"2023-09-15T20:22:07.899623Z","shell.execute_reply.started":"2023-09-15T20:22:07.875582Z","shell.execute_reply":"2023-09-15T20:22:07.898327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def discriminator_loss(real, generated):\n        \n        cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits = True, \n                                                           reduction = tf.keras.losses.Reduction.NONE)\n        \n        # Loss for discriminator includes two parts, first where it tries to flag real image as real\n        # Second part where it try to minimize flagging generated images as real\n        \n        real_loss = cross_entropy(tf.ones_like(real), real)\n        fake_loss = cross_entropy(tf.zeros_like(generated), generated)\n\n        total_loss = real_loss + fake_loss\n\n        return total_loss*0.5\n    \n    \nwith strategy.scope():\n    def generator_loss(generated):\n        \n        cross_entropy = tf.keras.losses.BinaryCrossentropy(from_logits = True, \n                                                           reduction = tf.keras.losses.Reduction.NONE)\n        #For generator we have only one term for loss\n        \n        return cross_entropy(tf.ones_like(generated), generated)\n\n\nwith strategy.scope():\n    def calc_cycle_loss(real_image, cycled_image, LAMBDA):\n\n        loss1 = tf.reduce_mean(tf.abs(real_image - cycled_image))\n        \n        return LAMBDA*loss1\n    \n\nwith strategy.scope():\n    def identity_loss(real_image, same_image, LAMBDA):\n        \n        loss = tf.reduce_mean(tf.abs(real_image - same_image))\n        \n        return LAMBDA*0.5*loss","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:07.901392Z","iopub.execute_input":"2023-09-15T20:22:07.901850Z","iopub.status.idle":"2023-09-15T20:22:07.917830Z","shell.execute_reply.started":"2023-09-15T20:22:07.901815Z","shell.execute_reply":"2023-09-15T20:22:07.916744Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    \n    monet_generator_optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0002, beta_1 = 0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0002, beta_1 = 0.5)\n\n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0002, beta_1 = 0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate = 0.0002, beta_1 = 0.5)\n\nwith strategy.scope():\n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, monet_discriminator, photo_discriminator\n    )\n\n    cycle_gan_model.compile(\n        m_gen_optimizer = monet_generator_optimizer,\n        p_gen_optimizer = photo_generator_optimizer,\n        m_disc_optimizer = monet_discriminator_optimizer,\n        p_disc_optimizer = photo_discriminator_optimizer,\n        gen_loss_fn = generator_loss,\n        disc_loss_fn = discriminator_loss,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss\n    )","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:07.919277Z","iopub.execute_input":"2023-09-15T20:22:07.920065Z","iopub.status.idle":"2023-09-15T20:22:07.958561Z","shell.execute_reply.started":"2023-09-15T20:22:07.920030Z","shell.execute_reply":"2023-09-15T20:22:07.957574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_gan = cycle_gan_model.fit   (\n    tf.data.Dataset.zip((monet_df, photo_df)),\n    epochs = 25\n)\n\nwarnings.simplefilter('ignore')","metadata":{"execution":{"iopub.status.busy":"2023-09-15T20:22:07.960038Z","iopub.execute_input":"2023-09-15T20:22:07.960406Z","iopub.status.idle":"2023-09-15T21:20:38.427263Z","shell.execute_reply.started":"2023-09-15T20:22:07.960366Z","shell.execute_reply":"2023-09-15T21:20:38.426147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, ax = plt.subplots(5, 2, figsize=(6, 20))\nfor i, img in enumerate(photo_df.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":"2023-09-15T21:20:38.428944Z","iopub.execute_input":"2023-09-15T21:20:38.429328Z","iopub.status.idle":"2023-09-15T21:20:40.252451Z","shell.execute_reply.started":"2023-09-15T21:20:38.429274Z","shell.execute_reply":"2023-09-15T21:20:40.251574Z"},"trusted":true},"execution_count":null,"outputs":[]}]}