{"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":"# 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\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-02T19:26:18.512707Z","iopub.execute_input":"2023-05-02T19:26:18.513778Z","iopub.status.idle":"2023-05-02T19:26:19.944691Z","shell.execute_reply.started":"2023-05-02T19:26:18.513734Z","shell.execute_reply":"2023-05-02T19:26:19.943676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os, random, json, PIL, shutil, re , glob\nimport numpy as np\n\nimport cv2\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\nimport math\n# import imageio.v3 as iio","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:19.946905Z","iopub.execute_input":"2023-05-02T19:26:19.947733Z","iopub.status.idle":"2023-05-02T19:26:30.805954Z","shell.execute_reply.started":"2023-05-02T19:26:19.947691Z","shell.execute_reply":"2023-05-02T19:26:30.804725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow_addons as tfa\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":{"execution":{"iopub.status.busy":"2023-05-02T19:26:30.811093Z","iopub.execute_input":"2023-05-02T19:26:30.813943Z","iopub.status.idle":"2023-05-02T19:26:30.837049Z","shell.execute_reply.started":"2023-05-02T19:26:30.813898Z","shell.execute_reply":"2023-05-02T19:26:30.835869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"HEIGHT = 256\nWIDTH = 256\nCHANNELS = 3\nEPOCHS = 50\nBATCH_SIZE = 1","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:30.842446Z","iopub.execute_input":"2023-05-02T19:26:30.845262Z","iopub.status.idle":"2023-05-02T19:26:30.852200Z","shell.execute_reply.started":"2023-05-02T19:26:30.845223Z","shell.execute_reply":"2023-05-02T19:26:30.851103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Import Dataset","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [256, 256]\ndef count_data_files(names):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(name).group(1)) for name in names]\n    return np.sum(n)\ndef get_normalized(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\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 = get_normalized(example['image'])\n    return image\n    \ndef load_dataset(files, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(files)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:30.857574Z","iopub.execute_input":"2023-05-02T19:26:30.860162Z","iopub.status.idle":"2023-05-02T19:26:30.872505Z","shell.execute_reply.started":"2023-05-02T19:26:30.860124Z","shell.execute_reply":"2023-05-02T19:26:30.871294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = KaggleDatasets().get_gcs_path()\nmonet_files = tf.io.gfile.glob(str( path + '/monet_tfrec/*.tfrec'))\nphoto_files = tf.io.gfile.glob(str(path + '/photo_tfrec/*.tfrec'))\nmonet_images = load_dataset(monet_files, labeled=True).batch(1)\nphoto_images = load_dataset(photo_files, labeled=True).batch(1)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:30.878257Z","iopub.execute_input":"2023-05-02T19:26:30.881011Z","iopub.status.idle":"2023-05-02T19:26:36.160611Z","shell.execute_reply.started":"2023-05-02T19:26:30.880944Z","shell.execute_reply":"2023-05-02T19:26:36.159505Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_monet_samples = count_data_files(monet_files)\nn_photo_samples = count_data_files(photo_files)\nprint(f'Monet images: {n_monet_samples}')\nprint(f'Photo images: {n_photo_samples}')","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:36.162525Z","iopub.execute_input":"2023-05-02T19:26:36.163266Z","iopub.status.idle":"2023-05-02T19:26:36.171251Z","shell.execute_reply.started":"2023-05-02T19:26:36.163226Z","shell.execute_reply":"2023-05-02T19:26:36.170055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualization","metadata":{}},{"cell_type":"code","source":"def visualize_images(ds, title, samples=5):\n    num_cols = min(samples, 5)\n    num_rows = (samples + num_cols - 1) // num_cols\n    plt.figure(figsize=(4*num_cols, 4*num_rows))\n    for i, img in enumerate(ds.take(samples)):\n        plt.subplot(num_rows, num_cols, i+1)\n        plt.title(f'{title} {i+1}')\n        plt.imshow(img[0] * 0.5 + 0.5)\n        plt.axis('off')\n    plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:36.173554Z","iopub.execute_input":"2023-05-02T19:26:36.175614Z","iopub.status.idle":"2023-05-02T19:26:36.190234Z","shell.execute_reply.started":"2023-05-02T19:26:36.175557Z","shell.execute_reply":"2023-05-02T19:26:36.189032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualize_images(monet_images,'Monet',10)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:36.192154Z","iopub.execute_input":"2023-05-02T19:26:36.192916Z","iopub.status.idle":"2023-05-02T19:26:37.947178Z","shell.execute_reply.started":"2023-05-02T19:26:36.192879Z","shell.execute_reply":"2023-05-02T19:26:37.944715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualize_images(photo_images,'Photos',8)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:37.951149Z","iopub.execute_input":"2023-05-02T19:26:37.951817Z","iopub.status.idle":"2023-05-02T19:26:38.882957Z","shell.execute_reply.started":"2023-05-02T19:26:37.951777Z","shell.execute_reply":"2023-05-02T19:26:38.881980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Generator","metadata":{}},{"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 = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n\n    if apply_instancenorm:\n        result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    result.add(layers.LeakyReLU())\n\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:38.884327Z","iopub.execute_input":"2023-05-02T19:26:38.885874Z","iopub.status.idle":"2023-05-02T19:26:38.893815Z","shell.execute_reply.started":"2023-05-02T19:26:38.885836Z","shell.execute_reply":"2023-05-02T19:26:38.892675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[256,256,3])\n\n    # bs = batch size\n    down_stack = [\n        downsample(64, 4, apply_instancenorm=False), # (bs, 128, 128, 64)\n        downsample(128, 4), # (bs, 64, 64, 128)\n        downsample(256, 4), # (bs, 32, 32, 256)\n        downsample(512, 4), # (bs, 16, 16, 512)\n        downsample(512, 4), # (bs, 8, 8, 512)\n        downsample(512, 4), # (bs, 4, 4, 512)\n        downsample(512, 4), # (bs, 2, 2, 512)\n        downsample(512, 4), # (bs, 1, 1, 512)\n    ]\n\n    up_stack = [\n        upsample(512, 4, apply_dropout=True), # (bs, 2, 2, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)\n        upsample(512, 4), # (bs, 16, 16, 1024)\n        upsample(256, 4), # (bs, 32, 32, 512)\n        upsample(128, 4), # (bs, 64, 64, 256)\n        upsample(64, 4), # (bs, 128, 128, 128)\n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,\n                                  strides=2,\n                                  padding='same',\n                                  kernel_initializer=initializer,\n                                  activation='tanh') # (bs, 256, 256, 3)\n\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down in down_stack:\n        x = down(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 = layers.Concatenate()([x, skip])\n\n    x = last(x)\n\n    return keras.Model(inputs=inputs, outputs=x)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:38.896471Z","iopub.execute_input":"2023-05-02T19:26:38.897646Z","iopub.status.idle":"2023-05-02T19:26:38.910425Z","shell.execute_reply.started":"2023-05-02T19:26:38.897589Z","shell.execute_reply":"2023-05-02T19:26:38.909543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Discrimeter\n","metadata":{}},{"cell_type":"code","source":"def upsample(filters, size, apply_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    result = keras.Sequential()\n    result.add(layers.Conv2DTranspose(filters, size, strides=2,\n                                      padding='same',\n                                      kernel_initializer=initializer,\n                                      use_bias=False))\n\n    result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n\n    result.add(layers.ReLU())\n\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:38.912594Z","iopub.execute_input":"2023-05-02T19:26:38.913605Z","iopub.status.idle":"2023-05-02T19:26:38.926806Z","shell.execute_reply.started":"2023-05-02T19:26:38.913558Z","shell.execute_reply":"2023-05-02T19:26:38.925558Z"},"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    inp = layers.Input(shape=[256, 256, 3], name='input_image')\n\n    x = inp\n\n    down1 = downsample(64, 4, False)(x) # (bs, 128, 128, 64)\n    down2 = downsample(128, 4)(down1) # (bs, 64, 64, 128)\n    down3 = downsample(256, 4)(down2) # (bs, 32, 32, 256)\n\n    zero_pad1 = layers.ZeroPadding2D()(down3) # (bs, 34, 34, 256)\n    conv = layers.Conv2D(512, 4, strides=1,\n                         kernel_initializer=initializer,\n                         use_bias=False)(zero_pad1) # (bs, 31, 31, 512)\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) # (bs, 33, 33, 512)\n\n    last = layers.Conv2D(1, 4, strides=1,  kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:38.928766Z","iopub.execute_input":"2023-05-02T19:26:38.929685Z","iopub.status.idle":"2023-05-02T19:26:38.940994Z","shell.execute_reply.started":"2023-05-02T19:26:38.929645Z","shell.execute_reply":"2023-05-02T19:26:38.939812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() # transforms photos to Monet-esque paintings\n    photo_generator = Generator() # transforms Monet paintings to be more like photos\n\n    monet_discriminator = Discriminator() # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator() # differentiates real photos and generated photos","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:28:19.477941Z","iopub.execute_input":"2023-05-02T19:28:19.478901Z","iopub.status.idle":"2023-05-02T19:28:22.359641Z","shell.execute_reply.started":"2023-05-02T19:28:19.478842Z","shell.execute_reply":"2023-05-02T19:28:22.358459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Build CycleGan","metadata":{}},{"cell_type":"code","source":"class CycleGan(keras.Model):\n    def __init__(\n        self,monet_generator,photo_generator,monet_discriminator,photo_discriminator,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(self,m_gen_optimizer,p_gen_optimizer,m_disc_optimizer,p_disc_optimizer,gen_loss_fn,disc_loss_fn,cycle_loss_fn, identity_loss_fn ):\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,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        # Apply the gradients to the optimizer\n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients, self.m_gen.trainable_variables))\n\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients,self.p_gen.trainable_variables))\n\n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients,self.m_disc.trainable_variables))\n\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":{"execution":{"iopub.status.busy":"2023-05-02T19:28:22.365028Z","iopub.execute_input":"2023-05-02T19:28:22.365759Z","iopub.status.idle":"2023-05-02T19:28:22.381972Z","shell.execute_reply.started":"2023-05-02T19:28:22.365716Z","shell.execute_reply":"2023-05-02T19:28:22.380764Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() # transforms photos to Monet-esque paintings\n    photo_generator = Generator() # transforms Monet paintings to be more like photos\n","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:28:26.491764Z","iopub.execute_input":"2023-05-02T19:28:26.492145Z","iopub.status.idle":"2023-05-02T19:28:28.644195Z","shell.execute_reply.started":"2023-05-02T19:28:26.492109Z","shell.execute_reply":"2023-05-02T19:28:28.643102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loss Functions","metadata":{}},{"cell_type":"markdown","source":"## Discriminator Loss","metadata":{}},{"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        generated_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(generated), generated)\n\n        total_disc_loss = real_loss + generated_loss\n\n        return total_disc_loss * 0.5","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:43.623339Z","iopub.execute_input":"2023-05-02T19:26:43.623736Z","iopub.status.idle":"2023-05-02T19:26:43.632706Z","shell.execute_reply.started":"2023-05-02T19:26:43.623694Z","shell.execute_reply":"2023-05-02T19:26:43.631503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Generator Loss","metadata":{}},{"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":{"execution":{"iopub.status.busy":"2023-05-02T19:26:43.634707Z","iopub.execute_input":"2023-05-02T19:26:43.635349Z","iopub.status.idle":"2023-05-02T19:26:43.641721Z","shell.execute_reply.started":"2023-05-02T19:26:43.635313Z","shell.execute_reply":"2023-05-02T19:26:43.640614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Cycle Loss","metadata":{}},{"cell_type":"code","source":"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","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:43.643211Z","iopub.execute_input":"2023-05-02T19:26:43.643595Z","iopub.status.idle":"2023-05-02T19:26:43.651756Z","shell.execute_reply.started":"2023-05-02T19:26:43.643547Z","shell.execute_reply":"2023-05-02T19:26:43.650823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Identitiy Loss","metadata":{}},{"cell_type":"code","source":"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\n","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:26:43.653357Z","iopub.execute_input":"2023-05-02T19:26:43.653798Z","iopub.status.idle":"2023-05-02T19:26:43.662647Z","shell.execute_reply.started":"2023-05-02T19:26:43.653758Z","shell.execute_reply":"2023-05-02T19:26:43.661672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:29:52.225569Z","iopub.execute_input":"2023-05-02T19:29:52.226422Z","iopub.status.idle":"2023-05-02T19:29:52.240534Z","shell.execute_reply.started":"2023-05-02T19:29:52.226383Z","shell.execute_reply":"2023-05-02T19:29:52.239380Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 = calc_cycle_loss,\n        identity_loss_fn = identity_loss\n    )","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:29:53.426282Z","iopub.execute_input":"2023-05-02T19:29:53.426944Z","iopub.status.idle":"2023-05-02T19:29:53.450967Z","shell.execute_reply.started":"2023-05-02T19:29:53.426905Z","shell.execute_reply":"2023-05-02T19:29:53.449934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hist=cycle_gan_model.fit(\n    tf.data.Dataset.zip((monet_images, photo_images)),\n    epochs=30\n)","metadata":{"execution":{"iopub.status.busy":"2023-05-02T19:29:55.644295Z","iopub.execute_input":"2023-05-02T19:29:55.645409Z","iopub.status.idle":"2023-05-02T20:41:05.269089Z","shell.execute_reply.started":"2023-05-02T19:29:55.645365Z","shell.execute_reply":"2023-05-02T20:41:05.268035Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_gen_loss_values = np.mean(hist.history['monet_gen_loss'], axis=(1, 2, 3))\nphoto_gen_loss_values = np.mean(hist.history['photo_gen_loss'], axis=(1, 2, 3))\n\n\nplt.plot(monet_gen_loss_values)\nplt.plot(photo_gen_loss_values)\n\nplt.legend([\"Monet Generator Loss\",\"Photo Generator Loss\"])\n\nplt.title(\"Generator Loss\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-02T21:00:28.200966Z","iopub.execute_input":"2023-05-02T21:00:28.201861Z","iopub.status.idle":"2023-05-02T21:00:28.422573Z","shell.execute_reply.started":"2023-05-02T21:00:28.201822Z","shell.execute_reply":"2023-05-02T21:00:28.421603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_disc_loss_values = np.mean(hist.history['monet_disc_loss'], axis=(1, 2, 3))\nphoto_disc_loss_values = np.mean(hist.history['photo_disc_loss'], axis=(1, 2, 3))\nplt.plot(monet_disc_loss_values)\nplt.plot(photo_disc_loss_values)\nplt.title(\"Discreminator Loss\")\nplt.legend([\"Monet Discriminator Loss\",\"Photo Discriminator Loss\"])\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-05-02T21:00:34.792013Z","iopub.execute_input":"2023-05-02T21:00:34.792756Z","iopub.status.idle":"2023-05-02T21:00:35.018284Z","shell.execute_reply.started":"2023-05-02T21:00:34.792717Z","shell.execute_reply":"2023-05-02T21:00:35.017323Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Visualize Monet Photos","metadata":{}},{"cell_type":"code","source":"_, ax = plt.subplots(5, 2, figsize=(12, 12))\nfor i, img in enumerate(photo_images.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-05-02T21:05:04.890213Z","iopub.execute_input":"2023-05-02T21:05:04.891178Z","iopub.status.idle":"2023-05-02T21:05:06.080146Z","shell.execute_reply.started":"2023-05-02T21:05:04.891136Z","shell.execute_reply":"2023-05-02T21:05:06.078678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import requests\nfrom io import BytesIO\nfrom PIL import Image\n\n# Download and resize the image\nresponse = requests.get(\"https://media.istockphoto.com/id/1137578281/photo/fuji-mountain-and-cherry-blossoms-in-spring-japan.jpg?s=612x612&w=0&k=20&c=H4T0916_yYJTjeKAaaLmYoQY3OMmaFShks6RfpYYVf4=\")\nimg = Image.open(BytesIO(response.content))\nimg = img.resize((256, 256))\n\n# Convert the image to a numpy array and normalize\nimg = np.array(img)\nimg = (img / 127.5) - 1\n\n# Generate the Monet-esque version\nprediction = monet_generator(np.expand_dims(img, axis=0), training=False)[0].numpy()\nprediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n\n# Display the input and output images\nfig, ax = plt.subplots(1, 2, figsize=(8, 4))\nax[0].imshow(img)\nax[1].imshow(prediction)\nax[0].set_title(\"Input Photo\")\nax[1].set_title(\"Monet-esque\")\nax[0].axis(\"off\")\nax[1].axis(\"off\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-02T21:07:15.661045Z","iopub.execute_input":"2023-05-02T21:07:15.661600Z","iopub.status.idle":"2023-05-02T21:07:16.118430Z","shell.execute_reply.started":"2023-05-02T21:07:15.661557Z","shell.execute_reply":"2023-05-02T21:07:16.117571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Save Weights","metadata":{}},{"cell_type":"code","source":"cycle_gan_model.save_weights('cycle_gan_model_weights.h5')\n","metadata":{"execution":{"iopub.status.busy":"2023-05-02T20:45:17.428154Z","iopub.execute_input":"2023-05-02T20:45:17.428545Z","iopub.status.idle":"2023-05-02T20:45:18.293320Z","shell.execute_reply.started":"2023-05-02T20:45:17.428502Z","shell.execute_reply":"2023-05-02T20:45:18.292163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}}]}