{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\n# os.makedirs('/kaggle/working/weights')\n# os.makedirs('/kaggle/working/models')","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:09.505168Z","iopub.execute_input":"2023-03-04T13:56:09.505644Z","iopub.status.idle":"2023-03-04T13:56:09.510596Z","shell.execute_reply.started":"2023-03-04T13:56:09.505607Z","shell.execute_reply":"2023-03-04T13:56:09.509454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('hello world')","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:15:19.440279Z","iopub.execute_input":"2023-03-05T08:15:19.44096Z","iopub.status.idle":"2023-03-05T08:15:19.469562Z","shell.execute_reply.started":"2023-03-05T08:15:19.440919Z","shell.execute_reply":"2023-03-05T08:15:19.468683Z"},"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\n\n# 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)\n# except:\nstrategy = tf.distribute.get_strategy()\nprint(\"Number of replicas:\", strategy.num_replicas_in_sync)\n    \nAUTOTUNE = tf.data.experimental.AUTOTUNE\nprint(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:17:18.783828Z","iopub.execute_input":"2023-03-05T08:17:18.784419Z","iopub.status.idle":"2023-03-05T08:17:28.519753Z","shell.execute_reply.started":"2023-03-05T08:17:18.784368Z","shell.execute_reply":"2023-03-05T08:17:28.518462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:17:28.522028Z","iopub.execute_input":"2023-03-05T08:17:28.523366Z","iopub.status.idle":"2023-03-05T08:17:28.529392Z","shell.execute_reply.started":"2023-03-05T08:17:28.523318Z","shell.execute_reply":"2023-03-05T08:17:28.527973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:17:28.531525Z","iopub.execute_input":"2023-03-05T08:17:28.53198Z","iopub.status.idle":"2023-03-05T08:17:29.07454Z","shell.execute_reply.started":"2023-03-05T08:17:28.531937Z","shell.execute_reply":"2023-03-05T08:17:29.073518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-05T08:17:29.806073Z","iopub.execute_input":"2023-03-05T08:17:29.80672Z","iopub.status.idle":"2023-03-05T08:17:30.3774Z","shell.execute_reply.started":"2023-03-05T08:17:29.806686Z","shell.execute_reply":"2023-03-05T08:17:30.376193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]) # tf.reshape(image, [256, 256, 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\n\ndef 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":{"execution":{"iopub.status.busy":"2023-03-05T08:17:32.350954Z","iopub.execute_input":"2023-03-05T08:17:32.351715Z","iopub.status.idle":"2023-03-05T08:17:32.359902Z","shell.execute_reply.started":"2023-03-05T08:17:32.351674Z","shell.execute_reply":"2023-03-05T08:17:32.359028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-05T08:18:43.72436Z","iopub.execute_input":"2023-03-05T08:18:43.724767Z","iopub.status.idle":"2023-03-05T08:18:43.787602Z","shell.execute_reply.started":"2023-03-05T08:18:43.724731Z","shell.execute_reply":"2023-03-05T08:18:43.786338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:18:49.208126Z","iopub.execute_input":"2023-03-05T08:18:49.208527Z","iopub.status.idle":"2023-03-05T08:18:50.455427Z","shell.execute_reply.started":"2023-03-05T08:18:49.208489Z","shell.execute_reply":"2023-03-05T08:18:50.454398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i,img in enumerate(photo_ds.take(1)):\n#     img = (img[0] * 127.5 + 127.5).numpy().astype(np.uint8)\n    print(img)","metadata":{"execution":{"iopub.status.busy":"2023-03-05T08:39:11.894846Z","iopub.execute_input":"2023-03-05T08:39:11.895343Z","iopub.status.idle":"2023-03-05T08:39:12.474306Z","shell.execute_reply.started":"2023-03-05T08:39:11.895304Z","shell.execute_reply":"2023-03-05T08:39:12.472952Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-03-05T08:17:48.142343Z","iopub.execute_input":"2023-03-05T08:17:48.142763Z","iopub.status.idle":"2023-03-05T08:17:48.600904Z","shell.execute_reply.started":"2023-03-05T08:17:48.142726Z","shell.execute_reply":"2023-03-05T08:17:48.599935Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    result.add(layers.LeakyReLU())\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:25.683288Z","iopub.execute_input":"2023-03-04T13:56:25.683633Z","iopub.status.idle":"2023-03-04T13:56:25.693994Z","shell.execute_reply.started":"2023-03-04T13:56:25.68359Z","shell.execute_reply":"2023-03-04T13:56:25.692832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n    \n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n    result.add(layers.ReLU())\n    return result","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:25.695936Z","iopub.execute_input":"2023-03-04T13:56:25.69635Z","iopub.status.idle":"2023-03-04T13:56:25.704159Z","shell.execute_reply.started":"2023-03-04T13:56:25.696253Z","shell.execute_reply":"2023-03-04T13:56:25.702863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[256, 256, 3])\n    \n    down_stack = [\n        # Same padding makes input size and output size at the same\n        # only if strides was 1 ... (I-1)/S + 1\n        # Same padding P is (K-1)/2\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),\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,\n                                 strides=2,\n                                 padding='same',\n                                 kernel_initializer=initializer,\n                                 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 keras.Model(inputs=inputs, outputs=x)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:25.706155Z","iopub.execute_input":"2023-03-04T13:56:25.707108Z","iopub.status.idle":"2023-03-04T13:56:25.718144Z","shell.execute_reply.started":"2023-03-04T13:56:25.707059Z","shell.execute_reply":"2023-03-04T13:56:25.717358Z"},"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    inputs = layers.Input(shape=[256, 256, 3], name='input_image')\n    \n    x = inputs\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    conv = layers.Conv2D(512, 4, strides=1,\n                        kernel_initializer=initializer,\n                        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=inputs, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:25.723396Z","iopub.execute_input":"2023-03-04T13:56:25.723693Z","iopub.status.idle":"2023-03-04T13:56:25.732394Z","shell.execute_reply.started":"2023-03-04T13:56:25.723666Z","shell.execute_reply":"2023-03-04T13:56:25.731342Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator()\n    photo_generator = Generator()\n    \n    monet_discriminator = Discriminator()\n    photo_discriminator = Discriminator()","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:25.733988Z","iopub.execute_input":"2023-03-04T13:56:25.734566Z","iopub.status.idle":"2023-03-04T13:56:28.732596Z","shell.execute_reply.started":"2023-03-04T13:56:25.73453Z","shell.execute_reply":"2023-03-04T13:56:28.731462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"to_monet = monet_generator(example_photo)\n\nplt.subplot(121)\nplt.title(\"Original Photo\")\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(122)\nplt.title(\"Monet-esque Photo\")\nplt.imshow(to_monet[0] * 0.5 + 0.5)\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:28.73437Z","iopub.execute_input":"2023-03-04T13:56:28.73476Z","iopub.status.idle":"2023-03-04T13:56:33.643736Z","shell.execute_reply.started":"2023-03-04T13:56:28.734721Z","shell.execute_reply":"2023-03-04T13:56:33.642705Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(keras.Model):\n    def __init__(\n        self,\n        monet_generator,\n        photo_generator,\n        monet_discriminator,\n        photo_discriminator,\n        lambda_cycle=10,\n    ):\n        super(CycleGan, self).__init__()\n        self.m_gen = monet_generator\n        self.p_gen = photo_generator\n        self.m_disc = monet_discriminator\n        self.p_disc = photo_discriminator\n        self.lambda_cycle = lambda_cycle\n        \n    def compile(\n        self,\n        m_gen_optimizer,\n        p_gen_optimizer,\n        m_disc_optimizer,\n        p_disc_optimizer,\n        gen_loss_fn,\n        disc_loss_fn,\n        cycle_loss_fn,\n        identity_loss_fn,\n    ):\n        super(CycleGan, self).compile()\n        self.m_gen_optimizer = m_gen_optimizer\n        self.p_gen_optimizer = p_gen_optimizer\n        self.m_disc_optimizer = m_disc_optimizer\n        self.p_disc_optimizer = p_disc_optimizer\n        self.gen_loss_fn = gen_loss_fn\n        self.disc_loss_fn = disc_loss_fn\n        self.cycle_loss_fn = cycle_loss_fn\n        self.identity_loss_fn = identity_loss_fn\n        \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        \n        with tf.GradientTape(persistent=True) as tape:\n            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            disc_real_monet = self.m_disc(real_monet, training=True)\n            disc_real_photo = self.p_disc(real_photo, training=True)\n            \n            disc_fake_monet = self.m_disc(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 =\\\n                self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle) +\\\n                self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle)\n            \n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss +\\\n                self.identity_loss_fn(real_monet, same_monet, self.lambda_cycle)\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss +\\\n                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#             self.m_gen.save_weights('/kaggle/working/weights/m_gen.hdf5')\n#             self.p_gen.save_weights('/kaggle/working/weights/p_gen.hdf5')\n#             self.m_disc.save_weights('/kaggle/working/weights/m_disc.hdf5')\n#             self.p_disc.save_weights('/kaggle/working/weights/m_disc.hdf5')\n            \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        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients,\n                                                self.m_gen.trainable_variables))\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        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients,\n                                                 self.p_disc.trainable_variables))\n\n        return {\n            \"monet_gen_loss\": total_monet_gen_loss,\n            \"photo_gen_loss\": total_photo_gen_loss,\n            \"monet_disc_loss\": monet_disc_loss,\n            \"photo_disc_loss\": photo_disc_loss\n        }","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.645566Z","iopub.execute_input":"2023-03-04T13:56:33.64628Z","iopub.status.idle":"2023-03-04T13:56:33.663627Z","shell.execute_reply.started":"2023-03-04T13:56:33.646245Z","shell.execute_reply":"2023-03-04T13:56:33.66239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def discriminator_loss(real, generated):\n        real_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True,\n                                                      reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(real), real)\n        generated_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True,\n                                                           reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(generated), generated)\n        total_disc_loss = real_loss + generated_loss\n        \n        return total_disc_loss * 0.5","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.6655Z","iopub.execute_input":"2023-03-04T13:56:33.665983Z","iopub.status.idle":"2023-03-04T13:56:33.677867Z","shell.execute_reply.started":"2023-03-04T13:56:33.665945Z","shell.execute_reply":"2023-03-04T13:56:33.676827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def generator_loss(generated):\n        return tf.keras.losses.BinaryCrossentropy(from_logits=True,\n                                                 reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(generated), generated)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.679584Z","iopub.execute_input":"2023-03-04T13:56:33.679953Z","iopub.status.idle":"2023-03-04T13:56:33.69023Z","shell.execute_reply.started":"2023-03-04T13:56:33.679918Z","shell.execute_reply":"2023-03-04T13:56:33.689219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def calc_cycle_loss(real_image, cycled_image, LAMBDA):\n        loss = tf.reduce_mean(tf.abs(real_image - cycled_image))\n        \n        return LAMBDA * loss","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.691579Z","iopub.execute_input":"2023-03-04T13:56:33.692003Z","iopub.status.idle":"2023-03-04T13:56:33.699737Z","shell.execute_reply.started":"2023-03-04T13:56:33.691957Z","shell.execute_reply":"2023-03-04T13:56:33.698763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.702467Z","iopub.execute_input":"2023-03-04T13:56:33.702728Z","iopub.status.idle":"2023-03-04T13:56:33.710333Z","shell.execute_reply.started":"2023-03-04T13:56:33.702704Z","shell.execute_reply":"2023-03-04T13:56:33.709318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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    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-03-04T13:56:33.712109Z","iopub.execute_input":"2023-03-04T13:56:33.712634Z","iopub.status.idle":"2023-03-04T13:56:33.728136Z","shell.execute_reply.started":"2023-03-04T13:56:33.712597Z","shell.execute_reply":"2023-03-04T13:56:33.727256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, monet_discriminator, photo_discriminator\n    )\n    \n    cycle_gan_model.compile(\n        m_gen_optimizer = monet_generator_optimizer,\n        p_gen_optimizer = photo_generator_optimizer,\n        m_disc_optimizer = monet_discriminator_optimizer,\n        p_disc_optimizer = photo_discriminator_optimizer,\n        gen_loss_fn = generator_loss,\n        disc_loss_fn = discriminator_loss,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss\n    )","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.729368Z","iopub.execute_input":"2023-03-04T13:56:33.729779Z","iopub.status.idle":"2023-03-04T13:56:33.751377Z","shell.execute_reply.started":"2023-03-04T13:56:33.729744Z","shell.execute_reply":"2023-03-04T13:56:33.75051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cycle_gan_model.fit(\n    tf.data.Dataset.zip((monet_ds, photo_ds)),\n    epochs=100\n)","metadata":{"execution":{"iopub.status.busy":"2023-03-04T13:56:33.752823Z","iopub.execute_input":"2023-03-04T13:56:33.753527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"_, ax = plt.subplots(5, 2, figsize=(12, 12))\nfor i, img in enumerate(photo_ds.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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = 1\nfor img in photo_ds:\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},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_generator.save_weights('/kaggle/working/weights/m_gen.hdf5')\nphoto_generator.save_weights('/kaggle/working/weights/p_gen.hdf5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_generator.save('/kaggle/working/models/m_gen_model')","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}