{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":21755,"databundleVersionId":1475600,"sourceType":"competition"}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:31.693166Z","iopub.execute_input":"2026-01-20T08:31:31.693963Z","iopub.status.idle":"2026-01-20T08:31:31.698178Z","shell.execute_reply.started":"2026-01-20T08:31:31.693930Z","shell.execute_reply":"2026-01-20T08:31:31.697289Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **LOAD DATASET**","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ntry:\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\n    \nprint(tf.__version__)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:31.699480Z","iopub.execute_input":"2026-01-20T08:31:31.699713Z","iopub.status.idle":"2026-01-20T08:31:31.714802Z","shell.execute_reply.started":"2026-01-20T08:31:31.699693Z","shell.execute_reply":"2026-01-20T08:31:31.714050Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:31.715805Z","iopub.execute_input":"2026-01-20T08:31:31.716111Z","iopub.status.idle":"2026-01-20T08:31:32.035201Z","shell.execute_reply.started":"2026-01-20T08:31:31.716080Z","shell.execute_reply":"2026-01-20T08:31:32.034665Z"}},"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":"2026-01-20T08:31:32.036591Z","iopub.execute_input":"2026-01-20T08:31:32.036784Z","iopub.status.idle":"2026-01-20T08:31:32.209725Z","shell.execute_reply.started":"2026-01-20T08:31:32.036766Z","shell.execute_reply":"2026-01-20T08:31:32.209044Z"}},"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":"2026-01-20T08:31:32.210625Z","iopub.execute_input":"2026-01-20T08:31:32.210883Z","iopub.status.idle":"2026-01-20T08:31:32.215861Z","shell.execute_reply.started":"2026-01-20T08:31:32.210859Z","shell.execute_reply":"2026-01-20T08:31:32.215237Z"}},"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":"2026-01-20T08:31:32.216723Z","iopub.execute_input":"2026-01-20T08:31:32.217028Z","iopub.status.idle":"2026-01-20T08:31:32.232904Z","shell.execute_reply.started":"2026-01-20T08:31:32.216958Z","shell.execute_reply":"2026-01-20T08:31:32.232222Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:32.233845Z","iopub.execute_input":"2026-01-20T08:31:32.234105Z","iopub.status.idle":"2026-01-20T08:31:32.320078Z","shell.execute_reply.started":"2026-01-20T08:31:32.234084Z","shell.execute_reply":"2026-01-20T08:31:32.319489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"example_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:32.320835Z","iopub.execute_input":"2026-01-20T08:31:32.321096Z","iopub.status.idle":"2026-01-20T08:31:33.113101Z","shell.execute_reply.started":"2026-01-20T08:31:32.321077Z","shell.execute_reply":"2026-01-20T08:31:33.112475Z"}},"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)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.113917Z","iopub.execute_input":"2026-01-20T08:31:33.114245Z","iopub.status.idle":"2026-01-20T08:31:33.362264Z","shell.execute_reply.started":"2026-01-20T08:31:33.114222Z","shell.execute_reply":"2026-01-20T08:31:33.361470Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **The Generator (ResNet-Based)**","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import layers\n\ndef resnet_block(input_layer, n_filters):\n    # Standard ResNet block for style preservation\n    g = layers.Conv2D(n_filters, (3,3), padding='same')(input_layer)\n    g = layers.BatchNormalization()(g)\n    g = layers.Activation('relu')(g)\n    \n    g = layers.Conv2D(n_filters, (3,3), padding='same')(g)\n    g = layers.BatchNormalization()(g)\n    \n    # Concatenate original input (skip connection)\n    return layers.Add()([g, input_layer])\n\ndef build_generator(n_resnet=9):\n    inputs = layers.Input(shape=(256, 256, 3))\n\n    # 1. Initial Convolution\n    x = layers.Conv2D(64, (7,7), padding='same')(inputs)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation('relu')(x)\n\n    # 2. Downsampling (Reduced to 128x128, then 64x64)\n    # This helps the model 'see' larger areas of the photo at once\n    for filters in [128, 256]:\n        x = layers.Conv2D(filters, (3,3), strides=(2,2), padding='same')(x)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation('relu')(x)\n\n    # 3. Transform: ResNet blocks (Operating at 64x64 resolution)\n    for _ in range(n_resnet):\n        x = resnet_block(x, 256)\n\n    # 4. Upsampling (Back to 128x128, then 256x256)\n    for filters in [128, 64]:\n        x = layers.Conv2DTranspose(filters, (3,3), strides=(2,2), padding='same')(x)\n        x = layers.BatchNormalization()(x)\n        x = layers.Activation('relu')(x)\n\n    # 5. Final Output (256, 256, 3)\n    outputs = layers.Conv2D(3, (7,7), padding='same', activation='tanh')(x)\n\n    return tf.keras.Model(inputs, outputs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.364463Z","iopub.execute_input":"2026-01-20T08:31:33.365113Z","iopub.status.idle":"2026-01-20T08:31:33.372879Z","shell.execute_reply.started":"2026-01-20T08:31:33.365089Z","shell.execute_reply":"2026-01-20T08:31:33.372148Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **The Discriminator (PatchGAN)**","metadata":{}},{"cell_type":"code","source":"def build_discriminator():\n    inputs = layers.Input(shape=(256, 256, 3))\n    x = layers.Conv2D(64, (4,4), strides=(2,2), padding='same')(inputs)\n    x = layers.LeakyReLU(alpha=0.2)(x)\n    \n    # Downsample to patches\n    x = layers.Conv2D(128, (4,4), strides=(2,2), padding='same')(x)\n    x = layers.LeakyReLU(alpha=0.2)(x)\n    \n    # Output a 1-channel prediction map\n    outputs = layers.Conv2D(1, (4,4), padding='same')(x)\n    return tf.keras.Model(inputs, outputs)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.373822Z","iopub.execute_input":"2026-01-20T08:31:33.374437Z","iopub.status.idle":"2026-01-20T08:31:33.391037Z","shell.execute_reply.started":"2026-01-20T08:31:33.374415Z","shell.execute_reply":"2026-01-20T08:31:33.390289Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CycleGan(tf.keras.Model):\n    def __init__(self, generator_g, generator_f, discriminator_x, discriminator_y, lambda_cycle=10.0, lambda_id=5.0):\n        super(CycleGan, self).__init__()\n        self.gen_g = generator_g  # Photo -> Monet\n        self.gen_f = generator_f  # Monet -> Photo\n        self.disc_x = discriminator_x # Discriminator for Photo\n        self.disc_y = discriminator_y # Discriminator for Monet\n        self.lambda_cycle = lambda_cycle\n        self.lambda_id = lambda_id\n\n    def compile(self, gen_g_optimizer, gen_f_optimizer, disc_x_optimizer, disc_y_optimizer, gen_loss_fn, disc_loss_fn):\n        super(CycleGan, self).compile()\n        self.gen_g_optimizer = gen_g_optimizer\n        self.gen_f_optimizer = gen_f_optimizer\n        self.disc_x_optimizer = disc_x_optimizer\n        self.disc_y_optimizer = disc_y_optimizer\n        self.gen_loss_fn = gen_loss_fn\n        self.disc_loss_fn = disc_loss_fn\n        self.cycle_loss_fn = tf.keras.losses.MeanAbsoluteError()\n        self.identity_loss_fn = tf.keras.losses.MeanAbsoluteError()\n\n    @tf.function\n    def train_step(self, batch_data):\n        real_x, real_y = batch_data # x is Photo, y is Monet\n\n        with tf.GradientTape(persistent=True) as tape:\n            # 1. Generator G translates Photo -> Fake Monet\n            # 2. Generator F translates Monet -> Fake Photo\n            fake_y = self.gen_g(real_x, training=True)\n            fake_x = self.gen_f(real_y, training=True)\n\n            # 3. Cycle Consistency: translate back to original domain\n            cycled_x = self.gen_f(fake_y, training=True)\n            cycled_y = self.gen_g(fake_x, training=True)\n\n            # 4. Identity Mapping: feed domain image to its own generator\n            same_x = self.gen_f(real_x, training=True)\n            same_y = self.gen_g(real_y, training=True)\n\n            # Calculate Generator Losses\n            gen_g_loss = self.gen_loss_fn(self.disc_y(fake_y))\n            gen_f_loss = self.gen_loss_fn(self.disc_x(fake_x))\n\n            # Cycle Loss: How close is cycled_x to real_x?\n            cycle_loss_g = self.cycle_loss_fn(real_x, cycled_x) * self.lambda_cycle\n            cycle_loss_f = self.cycle_loss_fn(real_y, cycled_y) * self.lambda_cycle\n\n            # Identity Loss: Does the model preserve color/composition?\n            id_loss_g = self.identity_loss_fn(real_y, same_y) * self.lambda_id\n            id_loss_f = self.identity_loss_fn(real_x, same_x) * self.lambda_id\n\n            total_gen_g_loss = gen_g_loss + cycle_loss_g + id_loss_g\n            total_gen_f_loss = gen_f_loss + cycle_loss_f + id_loss_f\n\n            # Calculate Discriminator Losses\n            disc_x_loss = self.disc_loss_fn(\n                self.disc_x(real_x, training=True),\n                self.disc_x(tf.stop_gradient(fake_x), training=True)\n            )\n            \n            disc_y_loss = self.disc_loss_fn(\n                self.disc_y(real_y, training=True),\n                self.disc_y(tf.stop_gradient(fake_y), training=True)\n            )\n\n            grads_g = tape.gradient(total_gen_g_loss, self.gen_g.trainable_variables)\n            # Generator F gradients\n            grads_f = tape.gradient(total_gen_f_loss, self.gen_f.trainable_variables)\n            \n            # Discriminator gradients\n            grads_dx = tape.gradient(disc_x_loss, self.disc_x.trainable_variables)\n            grads_dy = tape.gradient(disc_y_loss, self.disc_y.trainable_variables)\n            \n            # Apply gradients\n            self.gen_g_optimizer.apply_gradients(zip(grads_g, self.gen_g.trainable_variables))\n            self.gen_f_optimizer.apply_gradients(zip(grads_f, self.gen_f.trainable_variables))\n            \n            self.disc_x_optimizer.apply_gradients(zip(grads_dx, self.disc_x.trainable_variables))\n            self.disc_y_optimizer.apply_gradients(zip(grads_dy, self.disc_y.trainable_variables))\n\n        \n        return {\"g_loss\": total_gen_g_loss, \"f_loss\": total_gen_f_loss, \"dx_loss\": disc_x_loss, \"dy_loss\": disc_y_loss}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.392037Z","iopub.execute_input":"2026-01-20T08:31:33.392390Z","iopub.status.idle":"2026-01-20T08:31:33.415881Z","shell.execute_reply.started":"2026-01-20T08:31:33.392359Z","shell.execute_reply":"2026-01-20T08:31:33.415230Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Loss Function**","metadata":{}},{"cell_type":"code","source":"# Binary Cross Entropy is fine, but MSE is often more stable for CycleGAN\nloss_obj = tf.keras.losses.MeanSquaredError()\n\ndef discriminator_loss(real, generated):\n    real_loss = loss_obj(tf.ones_like(real), real)\n    generated_loss = loss_obj(tf.zeros_like(generated), generated)\n    return (real_loss + generated_loss) * 0.5\n\ndef generator_loss(generated):\n    return loss_obj(tf.ones_like(generated), generated)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.416676Z","iopub.execute_input":"2026-01-20T08:31:33.417183Z","iopub.status.idle":"2026-01-20T08:31:33.435191Z","shell.execute_reply.started":"2026-01-20T08:31:33.417161Z","shell.execute_reply":"2026-01-20T08:31:33.434637Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **Data Augmentation**","metadata":{}},{"cell_type":"code","source":"def load_and_decode_function(file_path):\n    # Read the file from the disk\n    img = tf.io.read_file(file_path)\n    \n    # Convert the compressed string to a 3D uint8 tensor\n    img = tf.image.decode_jpeg(img, channels=3)\n    \n    # Convert to floats in the [0, 1] range\n    img = tf.image.convert_image_dtype(img, tf.float32)\n    \n    # Resize the image to the model's expected input size\n    img = tf.image.resize(img, [256, 256])\n    \n    return img","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.435978Z","iopub.execute_input":"2026-01-20T08:31:33.436268Z","iopub.status.idle":"2026-01-20T08:31:33.451581Z","shell.execute_reply.started":"2026-01-20T08:31:33.436239Z","shell.execute_reply":"2026-01-20T08:31:33.450895Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create the generator and discriminator instances\nmonet_generator = build_generator() # Photo -> Monet\nphoto_generator = build_generator() # Monet -> Photo\nmonet_discriminator = build_discriminator()\nphoto_discriminator = build_discriminator()\n\n# Initialize the CycleGAN model\ncycle_gan_model = CycleGan(\n    monet_generator, photo_generator, \n    photo_discriminator, monet_discriminator\n)\n\n# Compile with optimizers and losses\ncycle_gan_model.compile(\n    gen_g_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5),\n    gen_f_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5),\n    disc_x_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5),\n    disc_y_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5),\n    gen_loss_fn = generator_loss,\n    disc_loss_fn = discriminator_loss\n)\n\n# Train the model (at least 25-50 epochs for decent results)\ncycle_gan_model.fit(\n    tf.data.Dataset.zip((photo_ds, monet_ds)),\n    epochs=5\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:31:33.452437Z","iopub.execute_input":"2026-01-20T08:31:33.452820Z","iopub.status.idle":"2026-01-20T08:43:39.265393Z","shell.execute_reply.started":"2026-01-20T08:31:33.452790Z","shell.execute_reply":"2026-01-20T08:43:39.264821Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# **SUBMISSION**","metadata":{}},{"cell_type":"code","source":"import os, shutil\nfrom PIL import Image\ngenerator = cycle_gan_model.gen_g\n\nos.makedirs(\"../images\", exist_ok=True)\nfor i, photo in enumerate(photo_ds.repeat().take(7000)):\n\n    if len(photo.shape) == 4:\n        img = photo[0]\n    else:\n        img = photo\n    \n\n    input_tensor = tf.expand_dims(img, axis=0)\n\n    # Generate image\n    pred = generator(input_tensor, training=False)\n    pred = pred[0].numpy()\n\n    # De-normalize\n    pred = (pred * 127.5 + 127.5)\n    pred = np.clip(pred, 0, 255).astype(np.uint8)\n\n    im = Image.fromarray(pred)\n    im.save(f\"../images/{i}.jpg\", quality=95)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:43:39.266213Z","iopub.execute_input":"2026-01-20T08:43:39.266476Z","iopub.status.idle":"2026-01-20T08:52:47.440042Z","shell.execute_reply.started":"2026-01-20T08:43:39.266448Z","shell.execute_reply":"2026-01-20T08:52:47.439185Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"shutil.make_archive(\n    \"/kaggle/working/images\",\n    \"zip\",\n    \"../images\"\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-01-20T08:52:47.441082Z","iopub.execute_input":"2026-01-20T08:52:47.441368Z","iopub.status.idle":"2026-01-20T08:52:55.480238Z","shell.execute_reply.started":"2026-01-20T08:52:47.441345Z","shell.execute_reply":"2026-01-20T08:52:55.479419Z"}},"outputs":[],"execution_count":null}]}