{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.10","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":30121,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \n\nimport os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:10.467112Z","iopub.execute_input":"2025-03-25T07:49:10.467804Z","iopub.status.idle":"2025-03-25T07:49:10.559731Z","shell.execute_reply.started":"2025-03-25T07:49:10.467356Z","shell.execute_reply":"2025-03-25T07:49:10.558565Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers\nimport tensorflow_addons as tfa\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:10.561930Z","iopub.execute_input":"2025-03-25T07:49:10.562330Z","iopub.status.idle":"2025-03-25T07:49:16.636942Z","shell.execute_reply.started":"2025-03-25T07:49:10.562289Z","shell.execute_reply":"2025-03-25T07:49:16.635945Z"}},"outputs":[],"execution_count":null},{"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)\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:16.638800Z","iopub.execute_input":"2025-03-25T07:49:16.639260Z","iopub.status.idle":"2025-03-25T07:49:16.651051Z","shell.execute_reply.started":"2025-03-25T07:49:16.639214Z","shell.execute_reply":"2025-03-25T07:49:16.650018Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:16.652092Z","iopub.execute_input":"2025-03-25T07:49:16.652323Z","iopub.status.idle":"2025-03-25T07:49:17.004487Z","shell.execute_reply.started":"2025-03-25T07:49:16.652300Z","shell.execute_reply":"2025-03-25T07:49:17.003831Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"MONET_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":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:17.005605Z","iopub.execute_input":"2025-03-25T07:49:17.005937Z","iopub.status.idle":"2025-03-25T07:49:17.394782Z","shell.execute_reply.started":"2025-03-25T07:49:17.005902Z","shell.execute_reply":"2025-03-25T07:49:17.393995Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"IMAGE_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    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":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:17.397015Z","iopub.execute_input":"2025-03-25T07:49:17.397282Z","iopub.status.idle":"2025-03-25T07:49:17.402964Z","shell.execute_reply.started":"2025-03-25T07:49:17.397256Z","shell.execute_reply":"2025-03-25T07:49:17.402102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import re\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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:17.404361Z","iopub.execute_input":"2025-03-25T07:49:17.404649Z","iopub.status.idle":"2025-03-25T07:49:17.415368Z","shell.execute_reply.started":"2025-03-25T07:49:17.404624Z","shell.execute_reply":"2025-03-25T07:49:17.414575Z"}},"outputs":[],"execution_count":null},{"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    return dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:17.416377Z","iopub.execute_input":"2025-03-25T07:49:17.416674Z","iopub.status.idle":"2025-03-25T07:49:17.425660Z","shell.execute_reply.started":"2025-03-25T07:49:17.416649Z","shell.execute_reply":"2025-03-25T07:49:17.424913Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"monet_dataset = load_dataset(MONET_FILENAMES).batch(1)\nphoto_dataset = load_dataset(PHOTO_FILENAMES).batch(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:17.426607Z","iopub.execute_input":"2025-03-25T07:49:17.426926Z","iopub.status.idle":"2025-03-25T07:49:19.452189Z","shell.execute_reply.started":"2025-03-25T07:49:17.426897Z","shell.execute_reply":"2025-03-25T07:49:19.451304Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fid_photo_ds = load_dataset(PHOTO_FILENAMES).take(1024).batch(32*strategy.num_replicas_in_sync).prefetch(32)\nfid_monet_ds = load_dataset(MONET_FILENAMES).batch(32*strategy.num_replicas_in_sync).prefetch(32)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:19.453410Z","iopub.execute_input":"2025-03-25T07:49:19.453824Z","iopub.status.idle":"2025-03-25T07:49:19.494943Z","shell.execute_reply.started":"2025-03-25T07:49:19.453786Z","shell.execute_reply":"2025-03-25T07:49:19.494004Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"example_monet = next(iter(monet_dataset))\nexample_photo = next(iter(photo_dataset))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:19.496298Z","iopub.execute_input":"2025-03-25T07:49:19.496665Z","iopub.status.idle":"2025-03-25T07:49:20.745023Z","shell.execute_reply.started":"2025-03-25T07:49:19.496627Z","shell.execute_reply":"2025-03-25T07:49:20.744287Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.subplot(121)\nplt.title('Photo')\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(122)\nplt.title('Monet')\nplt.imshow(example_monet[0] * 0.5 + 0.5)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:20.746180Z","iopub.execute_input":"2025-03-25T07:49:20.746471Z","iopub.status.idle":"2025-03-25T07:49:21.507536Z","shell.execute_reply.started":"2025-03-25T07:49:20.746443Z","shell.execute_reply":"2025-03-25T07:49:21.506574Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def prepare_dataset(monet_filenames, photo_filenames):\n    \n    monet_dataset = load_dataset(monet_filenames)\n    photo_dataset = load_dataset(photo_filenames)  \n\n    \n    monet_dataset = monet_dataset.repeat()\n    photo_dataset = photo_dataset.repeat()\n\n    \n    monet_dataset = monet_dataset.batch(4)\n    photo_dataset = photo_dataset.batch(4)\n    \n    monet_dataset = monet_dataset.prefetch(AUTOTUNE)\n    photo_dataset = photo_dataset.prefetch(AUTOTUNE)\n    \n    final_dataset = tf.data.Dataset.zip((monet_dataset, photo_dataset))\n    \n    return final_dataset","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:21.508822Z","iopub.execute_input":"2025-03-25T07:49:21.509078Z","iopub.status.idle":"2025-03-25T07:49:21.514531Z","shell.execute_reply.started":"2025-03-25T07:49:21.509053Z","shell.execute_reply":"2025-03-25T07:49:21.513601Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"final_dataset = prepare_dataset(MONET_FILENAMES, PHOTO_FILENAMES)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:21.515741Z","iopub.execute_input":"2025-03-25T07:49:21.516036Z","iopub.status.idle":"2025-03-25T07:49:21.566379Z","shell.execute_reply.started":"2025-03-25T07:49:21.515992Z","shell.execute_reply":"2025-03-25T07:49:21.565576Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n\n    inception_model = tf.keras.applications.InceptionV3(input_shape=(256,256,3),pooling=\"avg\",include_top=False)\n\n    mix3  = inception_model.get_layer(\"mixed9\").output\n    f0 = tf.keras.layers.GlobalAveragePooling2D()(mix3)\n\n    inception_model = tf.keras.Model(inputs=inception_model.input, outputs=f0)\n    inception_model.trainable = False\n\n    \n    \n    def calculate_activation_statistics_mod(images,fid_model):\n\n            act=tf.cast(fid_model.predict(images), tf.float32)\n\n            mu = tf.reduce_mean(act, axis=0)\n            mean_x = tf.reduce_mean(act, axis=0, keepdims=True)\n            mx = tf.matmul(tf.transpose(mean_x), mean_x)\n            vx = tf.matmul(tf.transpose(act), act)/tf.cast(tf.shape(act)[0], tf.float32)\n            sigma = vx - mx\n            return mu, sigma\n    myFID_mu2, myFID_sigma2 = calculate_activation_statistics_mod(fid_monet_ds,inception_model)\n    fids=[]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:21.567544Z","iopub.execute_input":"2025-03-25T07:49:21.567811Z","iopub.status.idle":"2025-03-25T07:49:34.039008Z","shell.execute_reply.started":"2025-03-25T07:49:21.567785Z","shell.execute_reply":"2025-03-25T07:49:34.037981Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    def calculate_frechet_distance(mu1,sigma1,mu2,sigma2):\n        fid_epsilon = 1e-14\n       \n        covmean = tf.linalg.sqrtm(tf.cast(tf.matmul(sigma1,sigma2),tf.complex64))\n\n        covmean = tf.cast(tf.math.real(covmean),tf.float32)\n  \n        tr_covmean = tf.linalg.trace(covmean)\n\n        return tf.matmul(tf.expand_dims(mu1 - mu2, axis=0),tf.expand_dims(mu1 - mu2, axis=1)) + tf.linalg.trace(sigma1) + tf.linalg.trace(sigma2) - 2 * tr_covmean\n    \n    \n    def FID(images,gen_model,inception_model=inception_model,myFID_mu2=myFID_mu2, myFID_sigma2=myFID_sigma2):\n        inp = layers.Input(shape=[256, 256, 3], name='input_image')\n        x  = gen_model(inp)\n        x=inception_model(x)\n        fid_model = tf.keras.Model(inputs=inp, outputs=x)\n\n        mu1, sigma1= calculate_activation_statistics_mod(images,fid_model)\n\n        fid_value = calculate_frechet_distance(mu1, sigma1,myFID_mu2, myFID_sigma2)\n\n\n        return fid_value","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:34.040631Z","iopub.execute_input":"2025-03-25T07:49:34.040937Z","iopub.status.idle":"2025-03-25T07:49:34.049532Z","shell.execute_reply.started":"2025-03-25T07:49:34.040902Z","shell.execute_reply":"2025-03-25T07:49:34.048619Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"OUTPUT_CHANNELS = 3\n\ndef downsample(filters, size, apply_instancenorm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = tf.keras.initializers.RandomNormal(mean=0., stddev=0.02)\n    \n    model_down = tf.keras.Sequential()\n    model_down.add(layers.Conv2D(filters, size, strides=2, padding='same', \n                                kernel_initializer=initializer, use_bias=False))\n    \n    if apply_instancenorm:\n        model_down.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n    \n    model_down.add(layers.LeakyReLU())\n    \n    return model_down\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:34.050869Z","iopub.execute_input":"2025-03-25T07:49:34.051233Z","iopub.status.idle":"2025-03-25T07:49:34.188419Z","shell.execute_reply.started":"2025-03-25T07:49:34.051190Z","shell.execute_reply":"2025-03-25T07:49:34.187534Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def upsample(filters, size, apply_dropout=False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = tf.keras.initializers.RandomNormal(mean=0., stddev=0.02)\n    \n    model_up = tf.keras.Sequential()\n    model_up.add(layers.Conv2DTranspose(filters, size, strides=2, padding='same', \n                                kernel_initializer=initializer, use_bias=False))\n    \n    model_up.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n    \n    if apply_dropout:\n        model_up.add(layers.Dropout(0.5))\n    \n    model_up.add(layers.ReLU())\n    \n    return model_up   ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:34.192056Z","iopub.execute_input":"2025-03-25T07:49:34.192386Z","iopub.status.idle":"2025-03-25T07:49:34.206889Z","shell.execute_reply.started":"2025-03-25T07:49:34.192345Z","shell.execute_reply":"2025-03-25T07:49:34.205951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input([256,256,3])\n    \n    down_stack = [\n        downsample(64, 4, apply_instancenorm=False),\n        downsample(128, 4),\n        downsample(256, 4),\n        downsample(512, 4),\n        downsample(512, 4),\n        downsample(512, 4),\n        downsample(512, 4),\n        downsample(512, 4),\n    ]\n    \n    up_stack = [\n        upsample(512, 4, apply_dropout=True),\n        upsample(512, 4, apply_dropout=True),\n        upsample(512, 4, apply_dropout=True),\n        upsample(512, 4),\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 = layers.Conv2DTranspose(OUTPUT_CHANNELS, 4, strides=2, padding='same', \n                                kernel_initializer=initializer, activation='tanh')\n    \n    x = inputs\n    \n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n    \n    skips = reversed(skips[:-1])\n    \n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = layers.Concatenate()([x, skip])\n    \n    x = last(x)\n    \n    return tf.keras.Model(inputs=inputs, outputs=x)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:34.208899Z","iopub.execute_input":"2025-03-25T07:49:34.209160Z","iopub.status.idle":"2025-03-25T07:49:34.221402Z","shell.execute_reply.started":"2025-03-25T07:49:34.209135Z","shell.execute_reply":"2025-03-25T07:49:34.220597Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Generator()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:34.222402Z","iopub.execute_input":"2025-03-25T07:49:34.222684Z","iopub.status.idle":"2025-03-25T07:49:35.596036Z","shell.execute_reply.started":"2025-03-25T07:49:34.222645Z","shell.execute_reply":"2025-03-25T07:49:35.595027Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = tf.keras.initializers.RandomNormal(mean=0., stddev=0.02)\n    \n    inp = layers.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 = layers.ZeroPadding2D()(down3)\n    \n    conv = layers.Conv2D(512, 4, strides=1, \n                        kernel_initializer=initializer, use_bias=False)(zero_pad1)\n    \n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n    \n    leaky_relu = layers.LeakyReLU()(norm1)\n    \n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu)\n    \n    last = layers.Conv2D(1, 4, strides=1, \n                        kernel_initializer=initializer)(zero_pad2)\n    \n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:35.597428Z","iopub.execute_input":"2025-03-25T07:49:35.597854Z","iopub.status.idle":"2025-03-25T07:49:35.607640Z","shell.execute_reply.started":"2025-03-25T07:49:35.597816Z","shell.execute_reply":"2025-03-25T07:49:35.606787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Discriminator()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:35.608807Z","iopub.execute_input":"2025-03-25T07:49:35.609071Z","iopub.status.idle":"2025-03-25T07:49:35.823586Z","shell.execute_reply.started":"2025-03-25T07:49:35.609044Z","shell.execute_reply":"2025-03-25T07:49:35.822536Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:35.824887Z","iopub.execute_input":"2025-03-25T07:49:35.825272Z","iopub.status.idle":"2025-03-25T07:49:38.048008Z","shell.execute_reply.started":"2025-03-25T07:49:35.825234Z","shell.execute_reply":"2025-03-25T07:49:38.047050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"to_monet = monet_generator(example_photo)\n\nplt.subplot(1, 2, 1)\nplt.title(\"Original Photo\")\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(1, 2, 2)\nplt.title(\"Monet-esque Photo\")\nplt.imshow(to_monet[0] * 0.5 + 0.5)\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.049193Z","iopub.execute_input":"2025-03-25T07:49:38.049458Z","iopub.status.idle":"2025-03-25T07:49:38.531409Z","shell.execute_reply.started":"2025-03-25T07:49:38.049433Z","shell.execute_reply":"2025-03-25T07:49:38.530579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CycleGan(tf.keras.Model):\n    def __init__(\n        self,\n        monet_generator,\n        photo_generator,\n        monet_discriminator,\n        photo_discriminator, \n        lambda_cycle=10):\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        aug_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        self.aug_fn = aug_fn\n        \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        batch_size = tf.shape(real_monet)[0]\n        \n        with tf.GradientTape(persistent=True) as tape:\n            fake_monet = self.m_gen(real_photo, training=True)\n            cycled_photo = self.p_gen(fake_monet, training=True)\n            \n            fake_photo = self.p_gen(real_monet, training=True)\n            cycled_monet = self.m_gen(fake_photo, training=True)\n            \n            same_monet = self.m_gen(real_monet, training=True)\n            same_photo = self.p_gen(real_photo, training=True)\n            \n            \n            both_monet = tf.concat([real_monet, fake_monet], axis=0)\n            aug_monet = self.aug_fn(both_monet)\n\n            aug_real_monet = aug_monet[:batch_size]\n            aug_fake_monet = aug_monet[batch_size:]\n\n            disc_real_monet = self.m_disc(aug_real_monet, training=True)\n            disc_real_photo = self.p_disc(real_photo, training=True)\n            \n            disc_fake_monet = self.m_disc(aug_fake_monet, training=True)\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo)\n            \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            total_monet_gen_loss = total_cycle_loss + monet_gen_loss + self.identity_loss_fn(real_monet,same_monet, self.lambda_cycle)\n            total_photo_gen_loss = total_cycle_loss + photo_gen_loss + self.identity_loss_fn(real_photo,same_photo, self.lambda_cycle)\n            \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        monet_generator_gradients = tape.gradient(total_monet_gen_loss, self.m_gen.trainable_variables) \n        photo_generator_gradients = tape.gradient(total_photo_gen_loss, self.p_gen.trainable_variables) \n\n        monet_discriminator_gradients = tape.gradient(monet_disc_loss, self.m_disc.trainable_variables) \n        photo_discriminator_gradients = tape.gradient(photo_disc_loss, self.p_disc.trainable_variables)\n\n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients, self.m_gen.trainable_variables))\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients, self.p_gen.trainable_variables))\n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients, self.m_disc.trainable_variables))\n        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients, 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.532485Z","iopub.execute_input":"2025-03-25T07:49:38.532754Z","iopub.status.idle":"2025-03-25T07:49:38.547423Z","shell.execute_reply.started":"2025-03-25T07:49:38.532723Z","shell.execute_reply":"2025-03-25T07:49:38.546402Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    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        generator_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 + generator_loss\n        \n        return 0.5*total_disc_loss","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.548674Z","iopub.execute_input":"2025-03-25T07:49:38.548968Z","iopub.status.idle":"2025-03-25T07:49:38.567711Z","shell.execute_reply.started":"2025-03-25T07:49:38.548924Z","shell.execute_reply":"2025-03-25T07:49:38.566727Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    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":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.568946Z","iopub.execute_input":"2025-03-25T07:49:38.569228Z","iopub.status.idle":"2025-03-25T07:49:38.582186Z","shell.execute_reply.started":"2025-03-25T07:49:38.569202Z","shell.execute_reply":"2025-03-25T07:49:38.581273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    def cycle_loss(real_image, cycled_image, LAMBDA):\n        return LAMBDA*(tf.reduce_mean(tf.abs(real_image-cycled_image)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.583357Z","iopub.execute_input":"2025-03-25T07:49:38.583663Z","iopub.status.idle":"2025-03-25T07:49:38.598415Z","shell.execute_reply.started":"2025-03-25T07:49:38.583635Z","shell.execute_reply":"2025-03-25T07:49:38.597440Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    def identity_loss(real_image, gen_image, LAMBDA):\n        return 0.5*LAMBDA*(tf.reduce_mean(tf.abs(real_image-gen_image)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.599497Z","iopub.execute_input":"2025-03-25T07:49:38.599794Z","iopub.status.idle":"2025-03-25T07:49:38.609851Z","shell.execute_reply.started":"2025-03-25T07:49:38.599766Z","shell.execute_reply":"2025-03-25T07:49:38.608964Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n\n    def DiffAugment(x, policy='', channels_first=False):\n        if policy:\n            if channels_first:\n                x = tf.transpose(x, [0, 2, 3, 1])\n            for p in policy.split(','):\n                for f in AUGMENT_FNS[p]:\n                    x = f(x)\n            if channels_first:\n                x = tf.transpose(x, [0, 3, 1, 2])\n        return x\n\n\n    def rand_brightness(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) - 0.5\n        x = x + magnitude\n        return x\n\n\n    def rand_saturation(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) * 2\n        x_mean = tf.reduce_sum(x, axis=3, keepdims=True) * 0.3333333333333333333\n        x = (x - x_mean) * magnitude + x_mean\n        return x\n\n\n    def rand_contrast(x):\n        magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) + 0.5\n        x_mean = tf.reduce_sum(x, axis=[1, 2, 3], keepdims=True) * 5.086e-6\n        x = (x - x_mean) * magnitude + x_mean\n        return x\n\n    def rand_translation(x, ratio=0.125):\n        batch_size = tf.shape(x)[0]\n        image_size = tf.shape(x)[1:3]\n        shift = tf.cast(tf.cast(image_size, tf.float32) * ratio + 0.5, tf.int32)\n        translation_x = tf.random.uniform([batch_size, 1], -shift[0], shift[0] + 1, dtype=tf.int32)\n        translation_y = tf.random.uniform([batch_size, 1], -shift[1], shift[1] + 1, dtype=tf.int32)\n        grid_x = tf.clip_by_value(tf.expand_dims(tf.range(image_size[0], dtype=tf.int32), 0) + translation_x + 1, 0, image_size[0] + 1)\n        grid_y = tf.clip_by_value(tf.expand_dims(tf.range(image_size[1], dtype=tf.int32), 0) + translation_y + 1, 0, image_size[1] + 1)\n        x = tf.gather_nd(tf.pad(x, [[0, 0], [1, 1], [0, 0], [0, 0]]), tf.expand_dims(grid_x, -1), batch_dims=1)\n        x = tf.transpose(tf.gather_nd(tf.pad(tf.transpose(x, [0, 2, 1, 3]), [[0, 0], [1, 1], [0, 0], [0, 0]]), tf.expand_dims(grid_y, -1), batch_dims=1), [0, 2, 1, 3])\n        return x\n\n\n    def rand_cutout(x, ratio=0.5):\n        batch_size = tf.shape(x)[0]\n        image_size = tf.shape(x)[1:3]\n        cutout_size = tf.cast(tf.cast(image_size, tf.float32) * ratio + 0.5, tf.int32)\n        offset_x = tf.random.uniform([tf.shape(x)[0], 1, 1], maxval=image_size[0] + (1 - cutout_size[0] % 2), dtype=tf.int32)\n        offset_y = tf.random.uniform([tf.shape(x)[0], 1, 1], maxval=image_size[1] + (1 - cutout_size[1] % 2), dtype=tf.int32)\n        grid_batch, grid_x, grid_y = tf.meshgrid(tf.range(batch_size, dtype=tf.int32), tf.range(cutout_size[0], dtype=tf.int32), tf.range(cutout_size[1], dtype=tf.int32), indexing='ij')\n        cutout_grid = tf.stack([grid_batch, grid_x + offset_x - cutout_size[0] // 2, grid_y + offset_y - cutout_size[1] // 2], axis=-1)\n        mask_shape = tf.stack([batch_size, image_size[0], image_size[1]])\n        cutout_grid = tf.maximum(cutout_grid, 0)\n        cutout_grid = tf.minimum(cutout_grid, tf.reshape(mask_shape - 1, [1, 1, 1, 3]))\n        mask = tf.maximum(1 - tf.scatter_nd(cutout_grid, tf.ones([batch_size, cutout_size[0], cutout_size[1]], dtype=tf.float32), mask_shape), 0)\n        x = x * tf.expand_dims(mask, axis=3)\n        return x\n\n\n    AUGMENT_FNS = {\n        'color': [rand_brightness, rand_saturation, rand_contrast],\n        'translation': [rand_translation],\n        'cutout': [rand_cutout],\n}\n    def aug_fn(image):\n        return DiffAugment(image,\"color,translation,cutout\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.611187Z","iopub.execute_input":"2025-03-25T07:49:38.611575Z","iopub.status.idle":"2025-03-25T07:49:38.632829Z","shell.execute_reply.started":"2025-03-25T07:49:38.611534Z","shell.execute_reply":"2025-03-25T07:49:38.631813Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    \n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    \n    callback = tf.keras.callbacks.EarlyStopping(monitor='loss', patience=3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.634155Z","iopub.execute_input":"2025-03-25T07:49:38.634564Z","iopub.status.idle":"2025-03-25T07:49:38.648481Z","shell.execute_reply.started":"2025-03-25T07:49:38.634523Z","shell.execute_reply":"2025-03-25T07:49:38.647660Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with strategy.scope():\n    cycle_gan_model = CycleGan(monet_generator, photo_generator, monet_discriminator, photo_discriminator)\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 = cycle_loss,\n        identity_loss_fn = identity_loss,\n        aug_fn = aug_fn\n    )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.649828Z","iopub.execute_input":"2025-03-25T07:49:38.650195Z","iopub.status.idle":"2025-03-25T07:49:38.675465Z","shell.execute_reply.started":"2025-03-25T07:49:38.650157Z","shell.execute_reply":"2025-03-25T07:49:38.674726Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cycle_gan_model.fit(\n    final_dataset, epochs=20, \n    steps_per_epoch=(max(n_monet_samples, n_photo_samples)//4)\n)\nFID(fid_photo_ds,monet_generator)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-03-25T07:49:38.676569Z","iopub.execute_input":"2025-03-25T07:49:38.676830Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ds_iter = iter(photo_dataset)\nfor n_sample in range(8):\n    example_sample = next(ds_iter)\n    generated_sample = monet_generator(example_sample)\n     \n    f = plt.figure(figsize=(32, 32))\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()","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import PIL\n! mkdir ../images","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"i = 1\nfor img in photo_dataset:\n    prediction = monet_generator(img, training=False)[0].numpy()\n    prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n    im = PIL.Image.fromarray(prediction)\n    im.save(\"../images/\" + str(i) + \".jpg\")\n    i += 1","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import shutil\nshutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}