{"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":"!pip install seaborn","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-07T17:09:56.923000Z","iopub.execute_input":"2023-11-07T17:09:56.923349Z","iopub.status.idle":"2023-11-07T17:10:02.189083Z","shell.execute_reply.started":"2023-11-07T17:09:56.923322Z","shell.execute_reply":"2023-11-07T17:10:02.187692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install imageio","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:10:02.191311Z","iopub.execute_input":"2023-11-07T17:10:02.191591Z","iopub.status.idle":"2023-11-07T17:10:06.072128Z","shell.execute_reply.started":"2023-11-07T17:10:02.191563Z","shell.execute_reply":"2023-11-07T17:10:06.071265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, random, json, PIL, shutil, re, imageio, glob\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nfrom PIL import ImageDraw\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nimport tensorflow.keras.backend as K\nimport tensorflow_addons as tfa\nfrom tensorflow.keras import Model, losses, optimizers\nfrom tensorflow.keras.callbacks import Callback\n\n\ndef seed_everything(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n    \nSEED = 0\nseed_everything(SEED)","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:10:06.073575Z","iopub.execute_input":"2023-11-07T17:10:06.073887Z","iopub.status.idle":"2023-11-07T17:10:53.762454Z","shell.execute_reply.started":"2023-11-07T17:10:06.073858Z","shell.execute_reply":"2023-11-07T17:10:53.761556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(f'Running on TPU {tpu.master()}')\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy()\n\n\nREPLICAS = strategy.num_replicas_in_sync\nAUTO = tf.data.experimental.AUTOTUNE\nprint(f'REPLICAS: {REPLICAS}')","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:10:53.764349Z","iopub.execute_input":"2023-11-07T17:10:53.764806Z","iopub.status.idle":"2023-11-07T17:11:01.630602Z","shell.execute_reply.started":"2023-11-07T17:10:53.764779Z","shell.execute_reply":"2023-11-07T17:11:01.629786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"HEIGHT = 256\nWIDTH = 256\nHEIGHT_RESIZE = 128\nWIDTH_RESIZE = 128\nCHANNELS = 3\nBATCH_SIZE = 16\nEPOCHS = 10\nTRANSFORMER_BLOCKS = 6\nGENERATOR_LR = 2e-4\nDISCRIMINATOR_LR = 2e-4","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:01.631601Z","iopub.execute_input":"2023-11-07T17:11:01.631871Z","iopub.status.idle":"2023-11-07T17:11:11.473099Z","shell.execute_reply.started":"2023-11-07T17:11:01.631845Z","shell.execute_reply":"2023-11-07T17:11:11.472046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#GCS_PATH = \"/kaggle/input/gan-getting-started\"#KaggleDatasets().get_gcs_path('gan-getting-started')\n#GCS_PATH = KaggleDatasets().get_gcs_path('gan-getting-started')\n# EXT_PATH = KaggleDatasets().get_gcs_path('tfrecords-monet-paintings-256x256')\n# EXT_PATH = KaggleDatasets().get_gcs_path('monet-tfrecords-256x256')\n\nMONET_FILENAMES = tf.io.gfile.glob(str('/kaggle/input/gan-getting-started/monet_tfrec/monet*.tfrec'))\nPHOTO_FILENAMES = tf.io.gfile.glob(str('/kaggle/input/gan-getting-started/photo_tfrec/photo*.tfrec'))\n# MONET_FILENAMES = tf.io.gfile.glob(str(EXT_PATH + '/monet*.tfrec'))\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nn_monet_samples = count_data_items(MONET_FILENAMES)\nn_photo_samples = count_data_items(PHOTO_FILENAMES)\n\nprint(f'Monet TFRecord files: {len(MONET_FILENAMES)}')\nprint(f'Monet image files: {n_monet_samples}')\nprint(f'Photo TFRecord files: {len(PHOTO_FILENAMES)}')\nprint(f'Photo image files: {n_photo_samples}')","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:11.474288Z","iopub.execute_input":"2023-11-07T17:11:11.474573Z","iopub.status.idle":"2023-11-07T17:11:11.618031Z","shell.execute_reply.started":"2023-11-07T17:11:11.474549Z","shell.execute_reply":"2023-11-07T17:11:11.617133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image):\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n#     p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n\n    \n#     # Random jitter\n#     image = tf.image.resize(image, [286, 286], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)\n    \n    # 90º rotations\n    if p_rotate > .8:\n        image = tf.image.rot90(image, k=3) # rotate 270º\n    elif p_rotate > .6:\n        image = tf.image.rot90(image, k=2) # rotate 180º\n    elif p_rotate > .4:\n        image = tf.image.rot90(image, k=1) # rotate 90º\n        \n    # Flips\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    if p_spatial > .75:\n        image = tf.image.transpose(image)\n        \n#     # Crops\n#     if p_crop > .6: # random crop\n#         crop_size = tf.random.uniform([], int(HEIGHT*.7), HEIGHT, dtype=tf.int32)\n#         image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n#     elif p_crop > .2: # central crop\n#         if p_crop > .5:\n#             image = tf.image.central_crop(image, central_fraction=.7)\n#         elif p_crop > .35:\n#             image = tf.image.central_crop(image, central_fraction=.8)\n#         else:\n#             image = tf.image.central_crop(image, central_fraction=.9)\n            \n    # Train on crops\n    image = tf.image.random_crop(image, size=[HEIGHT_RESIZE, WIDTH_RESIZE, CHANNELS])\n        \n    \n    return image","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:11.619295Z","iopub.execute_input":"2023-11-07T17:11:11.619884Z","iopub.status.idle":"2023-11-07T17:11:11.805959Z","shell.execute_reply.started":"2023-11-07T17:11:11.619856Z","shell.execute_reply":"2023-11-07T17:11:11.805178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def normalize_img(img):\n    img = tf.cast(img, dtype=tf.float32)\n    # Map values in the range [-1, 1]\n    return (img / 127.5) - 1.0\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=CHANNELS)\n    image = tf.reshape(image, [HEIGHT, WIDTH, CHANNELS])\n    return image\n\ndef read_tfrecord(example):\n    tfrecord_format = {\n        'image':      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\n\ndef load_dataset(filenames):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTO)\n    return dataset\n\ndef get_dataset(filenames, augment=None, repeat=True, shuffle=True, batch_size=1):\n    dataset = load_dataset(filenames)\n\n    if augment:\n        dataset = dataset.map(augment, num_parallel_calls=AUTO)\n    dataset = dataset.map(normalize_img, num_parallel_calls=AUTO)\n    if repeat:\n        dataset = dataset.repeat()\n    if shuffle:\n        dataset = dataset.shuffle(512)\n        \n    dataset = dataset.batch(batch_size)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    \n    return dataset\n\ndef display_samples(ds, n_samples):\n    ds_iter = iter(ds)\n    for n_sample in range(n_samples):\n        example_sample = next(ds_iter)\n        plt.subplot(121)\n        plt.imshow(example_sample[0] * 0.5 + 0.5)\n        plt.axis('off')\n        plt.show()\n        \ndef display_generated_samples(ds, model, n_samples):\n    ds_iter = iter(ds)\n    for n_sample in range(n_samples):\n        example_sample = next(ds_iter)\n        generated_sample = model.predict(example_sample)\n        \n        f = plt.figure(figsize=(12, 12))\n        \n        plt.subplot(121)\n        plt.title('Input image')\n        plt.imshow(example_sample[0] * 0.5 + 0.5)\n        plt.axis('off')\n        \n        plt.subplot(122)\n        plt.title('Generated image')\n        plt.imshow(generated_sample[0] * 0.5 + 0.5)\n        plt.axis('off')\n        plt.show()\n        \ndef evaluate_cycle(ds, generator_a, generator_b, n_samples=1):\n    fig, axes = plt.subplots(n_samples, 3, figsize=(22, (n_samples*6)))\n    axes = axes.flatten()\n    \n    ds_iter = iter(ds)\n    for n_sample in range(n_samples):\n        idx = n_sample*3\n        example_sample = next(ds_iter)\n        generated_a_sample = generator_a.predict(example_sample)\n        generated_b_sample = generator_b.predict(generated_a_sample)\n        \n        axes[idx].set_title('Input image', fontsize=18)\n        axes[idx].imshow(example_sample[0] * 0.5 + 0.5)\n        axes[idx].axis('off')\n        \n        axes[idx+1].set_title('Generated image', fontsize=18)\n        axes[idx+1].imshow(generated_a_sample[0] * 0.5 + 0.5)\n        axes[idx+1].axis('off')\n        \n        axes[idx+2].set_title('Cycled image', fontsize=18)\n        axes[idx+2].imshow(generated_b_sample[0] * 0.5 + 0.5)\n        axes[idx+2].axis('off')\n        \n    plt.show()\n\ndef create_gif(images_path, gif_path):\n    images = []\n    filenames = glob.glob(images_path)\n    filenames.sort(key=lambda x: int(''.join(filter(str.isdigit, x))))\n    for epoch, filename in enumerate(filenames):\n        img = PIL.ImageDraw.Image.open(filename)\n        ImageDraw.Draw(img).text((0, 0),  # Coordinates\n                                 f'Epoch {epoch+1}')\n        images.append(img)\n    imageio.mimsave(gif_path, images, fps=2) # Save gif\n        \ndef predict_and_save(input_ds, generator_model, output_path):\n    i = 1\n    for img in input_ds:\n        prediction = generator_model(img, training=False)[0].numpy() # make predition\n        prediction = (prediction * 127.5 + 127.5).astype(np.uint8)   # re-scale\n        im = PIL.Image.fromarray(prediction)\n        im.save(f'{output_path}{str(i)}.jpg')\n        i += 1","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:11.806975Z","iopub.execute_input":"2023-11-07T17:11:11.807223Z","iopub.status.idle":"2023-11-07T17:11:12.028307Z","shell.execute_reply.started":"2023-11-07T17:11:11.807201Z","shell.execute_reply":"2023-11-07T17:11:12.027466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"conv_initializer = tf.random_normal_initializer(mean=0.0, stddev=0.02)\ngamma_initializer = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    \ndef encoder_block(input_layer, filters, size=3, strides=2, apply_instancenorm=True, activation=L.ReLU(), name='block_x'):\n    block = L.Conv2D(filters, size, \n                     strides=strides, \n                     padding='same', \n                     use_bias=False, \n                     kernel_initializer=conv_initializer, \n                     name=f'encoder_{name}')(input_layer)\n\n    if apply_instancenorm:\n        block = tfa.layers.InstanceNormalization(gamma_initializer=gamma_initializer)(block)\n        \n    block = activation(block)\n\n    return block\n\ndef transformer_block(input_layer, size=3, strides=1, name='block_x'):\n    filters = input_layer.shape[-1]\n    \n    block = L.Conv2D(filters, size, strides=strides, padding='same', use_bias=False, \n                     kernel_initializer=conv_initializer, name=f'transformer_{name}_1')(input_layer)\n#     block = tfa.layers.InstanceNormalization(gamma_initializer=gamma_initializer)(block)\n    block = L.ReLU()(block)\n    \n    block = L.Conv2D(filters, size, strides=strides, padding='same', use_bias=False, \n                     kernel_initializer=conv_initializer, name=f'transformer_{name}_2')(block)\n#     block = tfa.layers.InstanceNormalization(gamma_initializer=gamma_initializer)(block)\n    \n    block = L.Add()([block, input_layer])\n\n    return block\n\ndef decoder_block(input_layer, filters, size=3, strides=2, apply_instancenorm=True, name='block_x'):\n    block = L.Conv2DTranspose(filters, size, \n                              strides=strides, \n                              padding='same', \n                              use_bias=False, \n                              kernel_initializer=conv_initializer, \n                              name=f'decoder_{name}')(input_layer)\n\n    if apply_instancenorm:\n        block = tfa.layers.InstanceNormalization(gamma_initializer=gamma_initializer)(block)\n\n    block = L.ReLU()(block)\n    \n    return block\n\n# Resized convolution\ndef decoder_rc_block(input_layer, filters, size=3, strides=1, apply_instancenorm=True, name='block_x'):\n    block = tf.image.resize(images=input_layer, method='bilinear', \n                            size=(input_layer.shape[1]*2, input_layer.shape[2]*2))\n    \n#     block = tf.pad(block, [[0, 0], [1, 1], [1, 1], [0, 0]], \"SYMMETRIC\") # Works only with GPU\n#     block = L.Conv2D(filters, size, strides=strides, padding='valid', use_bias=False, # Works only with GPU\n    block = L.Conv2D(filters, size, \n                     strides=strides, \n                     padding='same', \n                     use_bias=False, \n                     kernel_initializer=conv_initializer, \n                     name=f'decoder_{name}')(block)\n\n    if apply_instancenorm:\n        block = tfa.layers.InstanceNormalization(gamma_initializer=gamma_initializer)(block)\n\n    block = L.ReLU()(block)\n    \n    return block\n","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:12.029278Z","iopub.execute_input":"2023-11-07T17:11:12.029513Z","iopub.status.idle":"2023-11-07T17:11:12.235285Z","shell.execute_reply.started":"2023-11-07T17:11:12.029492Z","shell.execute_reply":"2023-11-07T17:11:12.234435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def generator_fn(height=HEIGHT, width=WIDTH, channels=CHANNELS, transformer_blocks=TRANSFORMER_BLOCKS):\n    OUTPUT_CHANNELS = 3\n    inputs = L.Input(shape=[height, width, channels], name='input_image')\n\n    # Encoder\n    enc_1 = encoder_block(inputs, 64,  7, 1, apply_instancenorm=True, activation=L.ReLU(), name='block_1') # (bs, 256, 256, 64)\n    drop = L.Dropout(0.5)\n    # Transformer\n    #x_skip = enc_1\n    \n    x_skip = drop(enc_1)\n    \n    enc_2 = encoder_block(x_skip, 256,  7, 1, apply_instancenorm=True, activation=L.ReLU(), name='block_2')\n    x_skip = drop(enc_2)\n    #x_skip = L.MaxPooling2D(pool_size=(2, 2),strides=(1, 1), padding='valid')(x_skip)\n    dec_1 = decoder_block(x_skip, 256, 3, 2, apply_instancenorm=True, name='block_1') # (bs, 128, 128, 128)\n    enc_3 = L.MaxPooling2D(pool_size=(1, 1),strides=(1, 1), padding='valid')(dec_1)\n    #dec_2 = decoder_block(x_skip, 64, 3, 2, apply_instancenorm=True, name='block_2')\n    x_skip = L.Concatenate(name='enc_dec_skip_2')([dec_1, enc_3])\n    outputs = last = L.Conv2D(OUTPUT_CHANNELS, 7, \n                              strides=2, padding='same', \n                              kernel_initializer=conv_initializer, \n                              use_bias=False, \n                              activation='tanh', \n                              name='decoder_output_block')(x_skip) # (bs, 256, 256, 3)\n    #outputs = x_skip\n    generator = Model(inputs, outputs)\n    \n    return generator\n    \n\nsample_generator = generator_fn()\nsample_generator.summary()\n","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:12.237724Z","iopub.execute_input":"2023-11-07T17:11:12.238033Z","iopub.status.idle":"2023-11-07T17:11:13.014671Z","shell.execute_reply.started":"2023-11-07T17:11:12.238010Z","shell.execute_reply":"2023-11-07T17:11:13.013704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def discriminator_fn(height=HEIGHT, width=WIDTH, channels=CHANNELS):\n    inputs = L.Input(shape=[height, width, channels], name='input_image')\n    #inputs_patch = L.experimental.preprocessing.RandomCrop(height=70, width=70, name='input_image_patch')(inputs) # Works only with GPU\n\n    # Encoder    \n    x = encoder_block(inputs, 64,  4, 2, apply_instancenorm=False, activation=L.LeakyReLU(0.2), name='block_1') # (bs, 128, 128, 64)\n    x = decoder_block(x, 512, 3, 2, apply_instancenorm=True, name='disc_block_1')\n    outputs = L.Conv2D(1, 4, strides=1, padding='valid', kernel_initializer=conv_initializer)(x)                # (bs, 29, 29, 1)\n    \n    discriminator = Model(inputs, outputs)\n    \n    return discriminator\n\n\nsample_discriminator = discriminator_fn()\nsample_discriminator.summary()","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:13.015963Z","iopub.execute_input":"2023-11-07T17:11:13.016234Z","iopub.status.idle":"2023-11-07T17:11:13.108349Z","shell.execute_reply.started":"2023-11-07T17:11:13.016209Z","shell.execute_reply":"2023-11-07T17:11:13.107541Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = generator_fn(height=None, width=None, transformer_blocks=TRANSFORMER_BLOCKS) # transforms photos to Monet-esque paintings\n    photo_generator = generator_fn(height=None, width=None, transformer_blocks=TRANSFORMER_BLOCKS) # transforms Monet paintings to be more like photos\n\n    monet_discriminator = discriminator_fn(height=None, width=None) # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = discriminator_fn(height=None, width=None) # differentiates real photos and generated photos\n\n\nclass 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 {'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-11-07T17:11:13.109417Z","iopub.execute_input":"2023-11-07T17:11:13.109657Z","iopub.status.idle":"2023-11-07T17:11:23.225395Z","shell.execute_reply.started":"2023-11-07T17:11:13.109636Z","shell.execute_reply":"2023-11-07T17:11:23.224122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    # Discriminator loss {0: fake, 1: real} (The discriminator loss outputs the average of the real and generated loss)\n    def discriminator_loss(real, generated):\n        real_loss = losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.NONE)(tf.ones_like(real), real)\n\n        generated_loss = losses.BinaryCrossentropy(from_logits=True, reduction=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\n    \n    # Generator loss\n    def generator_loss(generated):\n        return losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.NONE)(tf.ones_like(generated), generated)\n    \n    \n    # Cycle consistency loss (measures if original photo and the twice transformed photo to be similar to one another)\n    with strategy.scope():\n        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\n\n    # Identity loss (compares the image with its generator (i.e. photo with photo generator))\n    with strategy.scope():\n        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":"2023-11-07T17:11:23.226608Z","iopub.execute_input":"2023-11-07T17:11:23.226884Z","iopub.status.idle":"2023-11-07T17:11:23.235377Z","shell.execute_reply.started":"2023-11-07T17:11:23.226859Z","shell.execute_reply":"2023-11-07T17:11:23.234355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@tf.function\ndef linear_schedule_with_warmup(step):\n    \"\"\" Create a schedule with a learning rate that decreases linearly after\n    linearly increasing during a warmup period.\n    \"\"\"\n    lr_start   = 2e-4\n    lr_max     = 2e-4\n    lr_min     = 0.\n    \n    steps_per_epoch = int(max(n_monet_samples, n_photo_samples)//BATCH_SIZE)\n    total_steps = EPOCHS * steps_per_epoch\n    warmup_steps = 1\n    hold_max_steps = total_steps * 0.8\n    \n    if step < warmup_steps:\n        lr = (lr_max - lr_start) / warmup_steps * step + lr_start\n    elif step < warmup_steps + hold_max_steps:\n        lr = lr_max\n    else:\n        lr = lr_max * ((total_steps - step) / (total_steps - warmup_steps - hold_max_steps))\n        if lr_min is not None:\n            lr = tf.math.maximum(lr_min, lr)\n\n    return lr\n\nsteps_per_epoch = int(max(n_monet_samples, n_photo_samples) // BATCH_SIZE)\ntotal_steps = EPOCHS * steps_per_epoch\nrng = [i for i in range(0, total_steps, 50)]\ny = [linear_schedule_with_warmup(x) for x in rng]\n\nsns.set(style=\"whitegrid\")\nfig, ax = plt.subplots(figsize=(20, 6))\nplt.plot(rng, y)\nprint(f'{EPOCHS} total epochs and {steps_per_epoch} steps per epoch')\nprint(f'Learning rate schedule: {y[0]:.3g} to {max(y):.3g} to {y[-1]:.3g}')","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:23.236425Z","iopub.execute_input":"2023-11-07T17:11:23.236681Z","iopub.status.idle":"2023-11-07T17:11:42.050251Z","shell.execute_reply.started":"2023-11-07T17:11:23.236642Z","shell.execute_reply":"2023-11-07T17:11:42.049207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator_optimizer = optimizers.Adam(learning_rate=0.7, beta_1=0.5)\n    photo_generator_optimizer = optimizers.Adam(learning_rate=0.7, beta_1=0.5)\n\n    # Create generators\n    lr_monet_gen = lambda: linear_schedule_with_warmup(tf.cast(monet_generator_optimizer.iterations, tf.float32))\n    lr_photo_gen = lambda: linear_schedule_with_warmup(tf.cast(photo_generator_optimizer.iterations, tf.float32))\n    \n    monet_discriminator_optimizer = optimizers.Adam(learning_rate=0.7, beta_1=0.5)\n    photo_discriminator_optimizer = optimizers.Adam(learning_rate=0.7, beta_1=0.5)\n    # Create discriminators\n    lr_monet_disc = lambda: linear_schedule_with_warmup(tf.cast(monet_discriminator_optimizer.iterations, tf.float32))\n    lr_photo_disc = lambda: linear_schedule_with_warmup(tf.cast(photo_discriminator_optimizer.iterations, tf.float32))\n    \n    \n    # Create GAN\n    gan_model = CycleGan(monet_generator, photo_generator, \n                         monet_discriminator, photo_discriminator)\n\n    gan_model.compile(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)","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:42.051410Z","iopub.execute_input":"2023-11-07T17:11:42.051684Z","iopub.status.idle":"2023-11-07T17:11:42.313488Z","shell.execute_reply.started":"2023-11-07T17:11:42.051660Z","shell.execute_reply":"2023-11-07T17:11:42.312386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create dataset\nmonet_ds = get_dataset(MONET_FILENAMES, augment=data_augment, batch_size=BATCH_SIZE)\nphoto_ds = get_dataset(PHOTO_FILENAMES, augment=data_augment, batch_size=BATCH_SIZE)\ngan_ds = tf.data.Dataset.zip((monet_ds, photo_ds))\n\nphoto_ds_eval = get_dataset(PHOTO_FILENAMES, repeat=False, shuffle=False, batch_size=1)\nmonet_ds_eval = get_dataset(MONET_FILENAMES, repeat=False, shuffle=False, batch_size=1)\n\n# Callbacks\nclass GANMonitor(Callback):\n    \"\"\"A callback to generate and save images after each epoch\"\"\"\n\n    def __init__(self, num_img=1, monet_path='monet', photo_path='photo'):\n        self.num_img = num_img\n        self.monet_path = monet_path\n        self.photo_path = photo_path\n        # Create directories to save the generate images\n        if not os.path.exists(self.monet_path):\n            os.makedirs(self.monet_path)\n        if not os.path.exists(self.photo_path):\n            os.makedirs(self.photo_path)\n\n    def on_epoch_end(self, epoch, logs=None):\n        # Monet generated images\n        for i, img in enumerate(photo_ds_eval.take(self.num_img)):\n            prediction = monet_generator(img, training=False)[0].numpy()\n            prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n            prediction = PIL.Image.fromarray(prediction)\n            prediction.save(f'{self.monet_path}/generated_{i}_{epoch+1}.png')\n            \n        # Photo generated images\n        for i, img in enumerate(monet_ds_eval.take(self.num_img)):\n            prediction = photo_generator(img, training=False)[0].numpy()\n            prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n            prediction = PIL.Image.fromarray(prediction)\n            prediction.save(f'{self.photo_path}/generated_{i}_{epoch+1}.png')","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:42.314747Z","iopub.execute_input":"2023-11-07T17:11:42.315053Z","iopub.status.idle":"2023-11-07T17:11:45.015432Z","shell.execute_reply.started":"2023-11-07T17:11:42.315027Z","shell.execute_reply":"2023-11-07T17:11:45.014304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = gan_model.fit(gan_ds, \n                        epochs=EPOCHS, \n                        callbacks=[GANMonitor()], \n                        steps_per_epoch=(max(n_monet_samples, n_photo_samples)//BATCH_SIZE), \n                        verbose=2).history","metadata":{"execution":{"iopub.status.busy":"2023-11-07T17:11:45.016634Z","iopub.execute_input":"2023-11-07T17:11:45.016920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def func(x):\n    #x_ = x.copy\n    for i in range(len(x)):\n        x[i] = x[i].sum(axis=(0,1,2))\n    return x","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history['photo_gen_loss'][0].shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 6))\nplt.plot(func(history['monet_gen_loss']), label='Monet Generator Loss')\nplt.plot(func(history['photo_gen_loss']), label='Photo Generator Loss')\nplt.plot(func(history['monet_disc_loss']), label='Monet Discriminator Loss')\nplt.plot(func(history['photo_disc_loss']), label='Photo Discriminator Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.title('GAN Losses Over Time')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(12, 6))\nplt.plot(history['monet_gen_loss'], label='Monet Generator Loss')\nplt.plot(history['photo_gen_loss'], label='Photo Generator Loss')\nplt.plot(history['monet_disc_loss'], label='Monet Discriminator Loss')\nplt.plot(history['photo_disc_loss'], label='Photo Discriminator Loss')\nplt.xlabel('Epoch')\nplt.ylabel('Loss')\nplt.legend()\nplt.title('GAN Losses Over Time')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Got the idea from https://www.kaggle.com/matkneky/monet-cyclegan-trials\n# Create GIFs\ncreate_gif('/kaggle/working/monet/*.png', 'monet.gif') # Create monet gif","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}