{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.8.17","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"BATCH_SIZE = 32\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow_addons as tfa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\ntry:\n    from kaggle_datasets import KaggleDatasets\nexcept:\n    pass","metadata":{}},{"cell_type":"code","source":"BATCH_SIZE = 32\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.optimizers.legacy import Adam\nimport tensorflow_addons as tfa\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport re\ntry:\n    from kaggle_datasets import KaggleDatasets\nexcept:\n    pass","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:00:29.803448Z","iopub.execute_input":"2023-09-03T16:00:29.803784Z","iopub.status.idle":"2023-09-03T16:01:11.165469Z","shell.execute_reply.started":"2023-09-03T16:00:29.803755Z","shell.execute_reply":"2023-09-03T16:01:11.164241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)\n    #strategy = tf.distribute.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-09-03T16:01:11.167339Z","iopub.execute_input":"2023-09-03T16:01:11.168029Z","iopub.status.idle":"2023-09-03T16:01:19.104629Z","shell.execute_reply.started":"2023-09-03T16:01:11.167995Z","shell.execute_reply":"2023-09-03T16:01:19.103570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datafolder = KaggleDatasets().get_gcs_path(\"gan-getting-started\")\n\nMONET_FILENAMES = tf.io.gfile.glob(str(datafolder + '/monet_tfrec/*.tfrec'))\nPHOTO_FILENAMES = tf.io.gfile.glob(str(datafolder + '/photo_tfrec/*.tfrec'))\nIMAGE_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\": 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":{"execution":{"iopub.status.busy":"2023-09-03T16:01:19.105915Z","iopub.execute_input":"2023-09-03T16:01:19.106222Z","iopub.status.idle":"2023-09-03T16:01:19.127893Z","shell.execute_reply.started":"2023-09-03T16:01:19.106197Z","shell.execute_reply":"2023-09-03T16:01:19.126971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filenames):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset\n\nmonet_ds = load_dataset(MONET_FILENAMES).batch(1)\nphoto_ds = load_dataset(PHOTO_FILENAMES).batch(1)\n\n\nfast_photo_ds = load_dataset(PHOTO_FILENAMES).batch(32*strategy.num_replicas_in_sync).prefetch(32)\nfid_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":{"execution":{"iopub.status.busy":"2023-09-03T16:01:19.130360Z","iopub.execute_input":"2023-09-03T16:01:19.130748Z","iopub.status.idle":"2023-09-03T16:01:19.383834Z","shell.execute_reply.started":"2023-09-03T16:01:19.130718Z","shell.execute_reply":"2023-09-03T16:01:19.382877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_gan_dataset(monet_files, photo_files, augment=None, repeat=True, shuffle=True, batch_size=1):\n\n    monet_ds = load_dataset(monet_files)\n    photo_ds = load_dataset(photo_files)\n    \n    if augment:\n        monet_ds = monet_ds.map(augment, num_parallel_calls=AUTOTUNE)\n        photo_ds = photo_ds.map(augment, num_parallel_calls=AUTOTUNE)\n\n    if repeat:\n        monet_ds = monet_ds.repeat()\n        photo_ds = photo_ds.repeat()\n        \n#     if shuffle:\n#         monet_ds = monet_ds.shuffle(2048)\n#         photo_ds = photo_ds.shuffle(2048)\n        \n    monet_ds = monet_ds.batch(batch_size, drop_remainder=True)\n    photo_ds = photo_ds.batch(batch_size, drop_remainder=True)\n#     monet_ds = monet_ds.cache()\n#     photo_ds = photo_ds.cache()\n    monet_ds = monet_ds.prefetch(AUTOTUNE)\n    photo_ds = photo_ds.prefetch(AUTOTUNE)\n    \n    gan_ds = tf.data.Dataset.zip((monet_ds, photo_ds))\n    \n    return gan_ds","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:01:19.385081Z","iopub.execute_input":"2023-09-03T16:01:19.385395Z","iopub.status.idle":"2023-09-03T16:01:19.393563Z","shell.execute_reply.started":"2023-09-03T16:01:19.385367Z","shell.execute_reply":"2023-09-03T16:01:19.392740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"final_dataset = get_gan_dataset(MONET_FILENAMES, PHOTO_FILENAMES, augment=None, repeat=True, shuffle=True, batch_size=BATCH_SIZE)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:01:19.394722Z","iopub.execute_input":"2023-09-03T16:01:19.395045Z","iopub.status.idle":"2023-09-03T16:01:19.454617Z","shell.execute_reply.started":"2023-09-03T16:01:19.395017Z","shell.execute_reply":"2023-09-03T16:01:19.453713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2023-09-03T16:01:19.455758Z","iopub.execute_input":"2023-09-03T16:01:19.456067Z","iopub.status.idle":"2023-09-03T16:02:15.956063Z","shell.execute_reply.started":"2023-09-03T16:01:19.456040Z","shell.execute_reply":"2023-09-03T16:02:15.954822Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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#         isgood=tf.cast(tf.math.is_finite(covmean), tf.int32)\n#         if tf.size(isgood)!=tf.math.reduce_sum(isgood):\n#             return 0\n\n        covmean = tf.cast(tf.math.real(covmean),tf.float32)\n  \n        tr_covmean = tf.linalg.trace(covmean)\n\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    \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":{"execution":{"iopub.status.busy":"2023-09-03T16:02:15.957308Z","iopub.execute_input":"2023-09-03T16:02:15.957634Z","iopub.status.idle":"2023-09-03T16:02:15.969613Z","shell.execute_reply.started":"2023-09-03T16:02:15.957605Z","shell.execute_reply":"2023-09-03T16:02:15.968610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"OUTPUT_CHANNELS = 3\n\ndef down_sample(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    layer = keras.Sequential()\n    layer.add(layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer, use_bias=False))\n\n    if apply_instancenorm:\n        layer.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    layer.add(layers.LeakyReLU())\n\n    return layer","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:15.970930Z","iopub.execute_input":"2023-09-03T16:02:15.971264Z","iopub.status.idle":"2023-09-03T16:02:15.991000Z","shell.execute_reply.started":"2023-09-03T16:02:15.971234Z","shell.execute_reply":"2023-09-03T16:02:15.989965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def up_sample(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    layer = keras.Sequential()\n    layer.add(layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer,use_bias=False))\n    layer.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    if apply_dropout:\n        layer.add(layers.Dropout(0.5))\n\n    layer.add(layers.ReLU())\n\n    return layer","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:15.994933Z","iopub.execute_input":"2023-09-03T16:02:15.995229Z","iopub.status.idle":"2023-09-03T16:02:16.003483Z","shell.execute_reply.started":"2023-09-03T16:02:15.995202Z","shell.execute_reply":"2023-09-03T16:02:16.002613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[256,256,3])\n    down_stack = [\n        down_sample(64, 4, apply_instancenorm=False),\n        down_sample(128, 4),                        \n        down_sample(256, 4),                        \n        down_sample(512, 4),                        \n        down_sample(512, 4),                      \n        down_sample(512, 4),                      \n        down_sample(512, 4),                      \n        down_sample(512, 4),                      \n    ]\n\n    up_stack = [\n        up_sample(512, 4, apply_dropout=True),    \n        up_sample(512, 4, apply_dropout=True),    \n        up_sample(512, 4, apply_dropout=True),    \n        up_sample(512, 4),                          \n        up_sample(256, 4),                         \n        up_sample(128, 4),                           \n        up_sample(64, 4),                           \n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = layers.Conv2DTranspose(3, 4, strides=2, padding='same', kernel_initializer=initializer, activation='tanh') \n   \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-09-03T16:02:16.004594Z","iopub.execute_input":"2023-09-03T16:02:16.004864Z","iopub.status.idle":"2023-09-03T16:02:16.019558Z","shell.execute_reply.started":"2023-09-03T16:02:16.004825Z","shell.execute_reply":"2023-09-03T16:02:16.018601Z"},"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    x = inp\n    \n    down1 = down_sample(64, 4, False)(x)       \n    down2 = down_sample(128, 4)(down1)        \n    down3 = down_sample(256, 4)(down2)        \n\n    zero_pad1 = layers.ZeroPadding2D()(down3)\n    conv = layers.Conv2D(512, 4, strides=1, kernel_initializer=initializer, use_bias=False)(zero_pad1)\n\n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n    leaky_relu = layers.LeakyReLU()(norm1)\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu)\n\n    return tf.keras.Model(inputs=inp, outputs=zero_pad2)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:16.020727Z","iopub.execute_input":"2023-09-03T16:02:16.021067Z","iopub.status.idle":"2023-09-03T16:02:16.036736Z","shell.execute_reply.started":"2023-09-03T16:02:16.021038Z","shell.execute_reply":"2023-09-03T16:02:16.035708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def DHead():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    \n    inp = layers.Input(shape=[33, 33, 512], name='input_image')\n    x = inp\n    \n    last = layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(x) # (size, 30, 30, 1)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:16.037956Z","iopub.execute_input":"2023-09-03T16:02:16.038280Z","iopub.status.idle":"2023-09-03T16:02:16.051954Z","shell.execute_reply.started":"2023-09-03T16:02:16.038251Z","shell.execute_reply":"2023-09-03T16:02:16.050987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def DiscriminatorP():\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    x = inp\n    \n    down1 = down_sample(64, 4, False)(x)       \n    down2 = down_sample(128, 4)(down1)        \n    down3 = down_sample(256, 4)(down2)        \n\n    zero_pad1 = layers.ZeroPadding2D()(down3)\n    conv = layers.Conv2D(512, 4, strides=1, kernel_initializer=initializer, use_bias=False)(zero_pad1)\n\n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n    leaky_relu = layers.LeakyReLU()(norm1)\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu)\n    last = layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(zero_pad2)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:16.053151Z","iopub.execute_input":"2023-09-03T16:02:16.053476Z","iopub.status.idle":"2023-09-03T16:02:16.063830Z","shell.execute_reply.started":"2023-09-03T16:02:16.053447Z","shell.execute_reply":"2023-09-03T16:02:16.062869Z"},"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 = DiscriminatorP() # differentiates real photos and generated photos\n    dHead1 = DHead() # Head for BCE\n    dHead2 = DHead() # Head for hinge loss","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:16.065050Z","iopub.execute_input":"2023-09-03T16:02:16.065371Z","iopub.status.idle":"2023-09-03T16:02:29.278609Z","shell.execute_reply.started":"2023-09-03T16:02:16.065342Z","shell.execute_reply":"2023-09-03T16:02:29.277396Z"},"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        dhead1,        \n        dhead2,        \n        lambda_cycle=3,\n        lambda_id=3,\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        self.lambda_id = lambda_id\n        self.dhead1 = dhead1\n        self.dhead2 = dhead2\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_fn1,\n        gen_loss_fn2,\n        disc_loss_fn1,\n        disc_loss_fn2,\n        cycle_loss_fn,\n        identity_loss_fn,\n        aug_fn,\n\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_fn1 = gen_loss_fn1\n        self.gen_loss_fn2 = gen_loss_fn2\n        self.disc_loss_fn1 = disc_loss_fn1\n        self.disc_loss_fn2 = disc_loss_fn2\n        self.cycle_loss_fn = cycle_loss_fn\n        self.identity_loss_fn = identity_loss_fn\n        self.aug_fn = aug_fn\n\n        self.step_num = 0\n        \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        batch_size = tf.shape(real_monet)[0]\n        with tf.GradientTape(persistent=True) as tape:\n        \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            \n            \n            # Diffaugment\n            both_monet = tf.concat([real_monet, fake_monet], axis=0)            \n            \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            \n            # two-objective discriminator\n            disc_fake_monet1 = self.dhead1(self.m_disc(aug_fake_monet, training=True), training=True)\n            disc_real_monet1 = self.dhead1(self.m_disc(aug_real_monet, training=True), training=True)\n            disc_fake_monet2 = self.dhead2(self.m_disc(aug_fake_monet, training=True), training=True)\n            disc_real_monet2 = self.dhead2(self.m_disc(aug_real_monet, training=True), training=True)\n\n            monet_gen_loss1 = self.gen_loss_fn1(disc_fake_monet1) \n            monet_head_loss1 = self.disc_loss_fn1(disc_real_monet1, disc_fake_monet1)\n            monet_gen_loss2 = self.gen_loss_fn2(disc_fake_monet2)\n            monet_head_loss2 = self.disc_loss_fn2(disc_real_monet2, disc_fake_monet2)\n\n\n\n            monet_gen_loss = (monet_gen_loss1 + monet_gen_loss2) * 0.4\n            monet_disc_loss = monet_head_loss1 + monet_head_loss2\n\n\n           \n            \n            # discriminator used to check, inputing real images\n\n            disc_real_photo = self.p_disc(real_photo, training=True)\n            # discriminator used to check, inputing fake images\n\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n\n            # evaluates generator loss\n\n            photo_gen_loss = self.gen_loss_fn1(disc_fake_photo)\n            \n            # evaluates discriminator loss\n\n            photo_disc_loss = self.disc_loss_fn1(disc_real_photo, disc_fake_photo)\n\n\n            # evaluates total generator loss\n            total_cycle_loss = self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle/ tf.cast(batch_size,tf.float32)) + self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle/ tf.cast(batch_size,tf.float32))\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_id / tf.cast(batch_size,tf.float32))\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + self.identity_loss_fn(real_photo, same_photo, self.lambda_id/ tf.cast(batch_size,tf.float32))\n\n\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss,\n                                                  self.m_gen.trainable_variables)\n        photo_generator_gradients = tape.gradient(total_photo_gen_loss,\n                                                  self.p_gen.trainable_variables)\n\n        monet_discriminator_gradients = tape.gradient(monet_disc_loss,\n                                                      self.m_disc.trainable_variables)\n        photo_discriminator_gradients = tape.gradient(photo_disc_loss,\n                                                      self.p_disc.trainable_variables)\n        \n\n        # Heads gradients\n        monet_head_gradients = tape.gradient(monet_head_loss1,\n                                                      self.dhead1.trainable_variables)\n        \n        self.m_disc_optimizer.apply_gradients(zip(monet_head_gradients,\n                                                  self.dhead1.trainable_variables))       \n        \n        monet_head_gradients = tape.gradient(monet_head_loss2,\n                                                      self.dhead2.trainable_variables)\n\n        self.m_disc_optimizer.apply_gradients(zip(monet_head_gradients,\n                                                  self.dhead2.trainable_variables))     \n        \n        \n        # Apply the gradients to the optimizer\n\n        \n        self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients,\n                                                self.m_gen.trainable_variables))\n\n        self.p_gen_optimizer.apply_gradients(zip(photo_generator_gradients,\n                                                self.p_gen.trainable_variables))\n        \n        self.m_disc_optimizer.apply_gradients(zip(monet_discriminator_gradients,\n                                                 self.m_disc.trainable_variables))\n\n        self.p_disc_optimizer.apply_gradients(zip(photo_discriminator_gradients,\n                                                 self.p_disc.trainable_variables))\n        \n        return {\n            \"monet_head_loss1\": monet_head_loss1, \n            \"monet_head_loss2\": monet_head_loss2, \n            \"disc_real_monet\": disc_real_monet1, \n            \"disc_fake_monet\": disc_fake_monet1, \n            \"disc_real_monet2\": disc_real_monet2, \n            \"disc_fake_monet2\": disc_fake_monet2, \n            \"monet_gen_loss\": monet_gen_loss, \n            \"photo_disc_loss\": photo_disc_loss, \n            }","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.279984Z","iopub.execute_input":"2023-09-03T16:02:29.280274Z","iopub.status.idle":"2023-09-03T16:02:29.314738Z","shell.execute_reply.started":"2023-09-03T16:02:29.280249Z","shell.execute_reply":"2023-09-03T16:02:29.313840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope(): # for TPU\n\n    def discriminator_loss1(real, generated):\n        real_loss = tf.math.minimum(tf.zeros_like(real), real-tf.ones_like(real))\n\n        generated_loss = tf.math.minimum(tf.zeros_like(generated), -generated-tf.ones_like(generated))\n\n        total_disc_loss = real_loss + generated_loss\n\n        return tf.reduce_mean(-total_disc_loss * 0.5)\n\n    def discriminator_loss2(real, generated):\n        generated_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(generated), generated)\n        real_loss = tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(real), real)\n        total_disc_loss = real_loss + generated_loss\n\n        return tf.reduce_mean(total_disc_loss * 0.5)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.315775Z","iopub.execute_input":"2023-09-03T16:02:29.316045Z","iopub.status.idle":"2023-09-03T16:02:29.335155Z","shell.execute_reply.started":"2023-09-03T16:02:29.316021Z","shell.execute_reply":"2023-09-03T16:02:29.334313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def generator_loss1(generated):\n        return  tf.reduce_mean(-generated)\n\n    def generator_loss2(generated):\n        return tf.reduce_mean(tf.keras.losses.BinaryCrossentropy(from_logits=True, reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(generated), generated))","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.336229Z","iopub.execute_input":"2023-09-03T16:02:29.336501Z","iopub.status.idle":"2023-09-03T16:02:29.348361Z","shell.execute_reply.started":"2023-09-03T16:02:29.336477Z","shell.execute_reply":"2023-09-03T16:02:29.347520Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    def calc_cycle_loss(real_image, cycled_image, LAMBDA):\n        loss1 = tf.reduce_sum(tf.abs(real_image - cycled_image))\n\n        return LAMBDA * loss1 * 0.0000152587890625","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.349464Z","iopub.execute_input":"2023-09-03T16:02:29.349763Z","iopub.status.idle":"2023-09-03T16:02:29.358379Z","shell.execute_reply.started":"2023-09-03T16:02:29.349737Z","shell.execute_reply":"2023-09-03T16:02:29.357548Z"},"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_sum(tf.abs(real_image - same_image))\n        return LAMBDA * 0.5 * loss * 0.0000152587890625","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.359436Z","iopub.execute_input":"2023-09-03T16:02:29.359716Z","iopub.status.idle":"2023-09-03T16:02:29.368210Z","shell.execute_reply.started":"2023-09-03T16:02:29.359692Z","shell.execute_reply":"2023-09-03T16:02:29.367321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\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\")","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.369383Z","iopub.execute_input":"2023-09-03T16:02:29.369738Z","iopub.status.idle":"2023-09-03T16:02:29.402332Z","shell.execute_reply.started":"2023-09-03T16:02:29.369712Z","shell.execute_reply":"2023-09-03T16:02:29.401401Z"},"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    monet_generator_optimizer = tf.keras.optimizers.legacy.Adam(2e-4, beta_1=0.5)\n    #photo_generator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.legacy.Adam(2e-4, beta_1=0.5)\n\n    #monet_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    monet_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(2e-4, beta_1=0.5)\n    #photo_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(2e-4, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.403503Z","iopub.execute_input":"2023-09-03T16:02:29.403800Z","iopub.status.idle":"2023-09-03T16:02:29.417879Z","shell.execute_reply.started":"2023-09-03T16:02:29.403774Z","shell.execute_reply":"2023-09-03T16:02:29.417031Z"},"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, dHead1,  dHead2\n    )","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.419220Z","iopub.execute_input":"2023-09-03T16:02:29.419523Z","iopub.status.idle":"2023-09-03T16:02:29.448768Z","shell.execute_reply.started":"2023-09-03T16:02:29.419496Z","shell.execute_reply":"2023-09-03T16:02:29.447584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\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_fn1 = generator_loss1,\n        gen_loss_fn2 = generator_loss2,\n        disc_loss_fn1 = discriminator_loss1,\n        disc_loss_fn2 = discriminator_loss2,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        aug_fn = aug_fn ,\n\n\n    )\n    \n    cycle_gan_model.fit(final_dataset,steps_per_epoch=1407, epochs=10)  # steps_per_epoch=1407, epochs=15\nFID(fid_photo_ds,monet_generator) ","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:02:29.450254Z","iopub.execute_input":"2023-09-03T16:02:29.450586Z","iopub.status.idle":"2023-09-03T16:50:16.445046Z","shell.execute_reply.started":"2023-09-03T16:02:29.450557Z","shell.execute_reply":"2023-09-03T16:50:16.443247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    #monet_generator_optimizer = tf.keras.optimizers.Adam(1e-4, beta_1=0.5)\n    monet_generator_optimizer = tf.keras.optimizers.legacy.Adam(1e-4, beta_1=0.5)\n    #photo_generator_optimizer = tf.keras.optimizers.Adam(1e-4, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.legacy.Adam(1e-4, beta_1=0.5)\n\n    #monet_discriminator_optimizer = tf.keras.optimizers.Adam(1e-4, beta_1=0.5)\n    monet_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(1e-4, beta_1=0.5)\n    #photo_discriminator_optimizer = tf.keras.optimizers.Adam(1e-4, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(1e-4, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:50:16.446574Z","iopub.execute_input":"2023-09-03T16:50:16.446943Z","iopub.status.idle":"2023-09-03T16:50:16.455861Z","shell.execute_reply.started":"2023-09-03T16:50:16.446911Z","shell.execute_reply":"2023-09-03T16:50:16.454555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\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_fn1 = generator_loss1,\n        gen_loss_fn2 = generator_loss2,\n        disc_loss_fn1 = discriminator_loss1,\n        disc_loss_fn2 = discriminator_loss2,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        aug_fn = aug_fn ,\n    )\n    \ncycle_gan_model.fit(final_dataset,steps_per_epoch=2021, epochs=12)  # steps_per_epoch=1407, epochs=18\nFID(fid_photo_ds,monet_generator) ","metadata":{"execution":{"iopub.status.busy":"2023-09-03T16:50:16.457103Z","iopub.execute_input":"2023-09-03T16:50:16.457433Z","iopub.status.idle":"2023-09-03T18:08:17.145300Z","shell.execute_reply.started":"2023-09-03T16:50:16.457406Z","shell.execute_reply":"2023-09-03T18:08:17.143237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    #monet_generator_optimizer = tf.keras.optimizers.Adam(1e-5, beta_1=0.5)\n    monet_generator_optimizer = tf.keras.optimizers.legacy.Adam(1e-5, beta_1=0.5)\n    #photo_generator_optimizer = tf.keras.optimizers.Adam(1e-5, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.legacy.Adam(1e-5, beta_1=0.5)\n\n    #monet_discriminator_optimizer = tf.keras.optimizers.Adam(1e-5, beta_1=0.5)\n    monet_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(1e-5, beta_1=0.5)\n    #photo_discriminator_optimizer = tf.keras.optimizers.Adam(1e-5, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.legacy.Adam(1e-5, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:08:17.146927Z","iopub.execute_input":"2023-09-03T18:08:17.147245Z","iopub.status.idle":"2023-09-03T18:08:17.155541Z","shell.execute_reply.started":"2023-09-03T18:08:17.147218Z","shell.execute_reply":"2023-09-03T18:08:17.154297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\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_fn1 = generator_loss1,\n        gen_loss_fn2 = generator_loss2,\n        disc_loss_fn1 = discriminator_loss1,\n        disc_loss_fn2 = discriminator_loss2,\n        cycle_loss_fn = calc_cycle_loss,\n        identity_loss_fn = identity_loss,\n        aug_fn = aug_fn ,\n    )\ncycle_gan_model.fit(final_dataset,steps_per_epoch=1407, epochs=8) # steps_per_epoch=1407, epochs=12\nFID(fid_photo_ds,monet_generator)   \n\n    ","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:08:17.160749Z","iopub.execute_input":"2023-09-03T18:08:17.161043Z","iopub.status.idle":"2023-09-03T18:47:17.283753Z","shell.execute_reply.started":"2023-09-03T18:08:17.161019Z","shell.execute_reply":"2023-09-03T18:47:17.281860Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(photo_ds)\nfor n_sample in range(10):\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":{"execution":{"iopub.status.busy":"2023-09-03T18:47:17.285296Z","iopub.execute_input":"2023-09-03T18:47:17.285639Z","iopub.status.idle":"2023-09-03T18:47:26.092527Z","shell.execute_reply.started":"2023-09-03T18:47:17.285602Z","shell.execute_reply":"2023-09-03T18:47:26.090684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(monet_ds)\nfor n_sample in range(10):\n\n        example_sample = next(ds_iter)\n        generated_sample = photo_generator(example_sample)\n        \n        f = plt.figure(figsize=(24, 24))\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":{"execution":{"iopub.status.busy":"2023-09-03T18:47:26.093992Z","iopub.execute_input":"2023-09-03T18:47:26.094332Z","iopub.status.idle":"2023-09-03T18:47:32.945867Z","shell.execute_reply.started":"2023-09-03T18:47:26.094303Z","shell.execute_reply":"2023-09-03T18:47:32.944048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import PIL\n! mkdir ../images","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:47:32.947386Z","iopub.execute_input":"2023-09-03T18:47:32.947737Z","iopub.status.idle":"2023-09-03T18:47:34.815706Z","shell.execute_reply.started":"2023-09-03T18:47:32.947706Z","shell.execute_reply":"2023-09-03T18:47:34.813432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ni = 1\nfor img in fast_photo_ds:\n    prediction = monet_generator(img, training=False).numpy()\n    prediction = (prediction * 127.5 + 127.5).astype(np.uint8)\n    for pred in prediction:\n        im = PIL.Image.fromarray(pred)\n        im.save(\"../images/\" + str(i) + \".jpg\")\n        i += 1","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:47:34.817645Z","iopub.execute_input":"2023-09-03T18:47:34.818017Z","iopub.status.idle":"2023-09-03T18:53:43.041392Z","shell.execute_reply.started":"2023-09-03T18:47:34.817982Z","shell.execute_reply":"2023-09-03T18:53:43.040037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nshutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:53:43.042996Z","iopub.execute_input":"2023-09-03T18:53:43.043352Z","iopub.status.idle":"2023-09-03T18:53:48.370425Z","shell.execute_reply.started":"2023-09-03T18:53:43.043318Z","shell.execute_reply":"2023-09-03T18:53:48.368743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cycle_gan_model.p_gen.save_weights(\"p_gen_weights.h5\")\nmonet_generator.save_weights(\"monet_generator.h5\")\n\ncycle_gan_model.p_disc.save_weights(\"p_disc_weights.h5\")\ncycle_gan_model.m_disc.save_weights(\"m_disc_weights.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-09-03T18:53:48.371946Z","iopub.execute_input":"2023-09-03T18:53:48.372294Z","iopub.status.idle":"2023-09-03T18:53:49.294395Z","shell.execute_reply.started":"2023-09-03T18:53:48.372264Z","shell.execute_reply":"2023-09-03T18:53:49.292728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"import numpy as np\nfrom PIL import Image\ninput_img = Image.open(\"../input/mone-pics/20201001_170706059_iOS.jpg\") # sakura\n#input_img = Image.open(\"../input/mone-pics/20180521_094825674_iOS.jpg\") # flower\n#input_img = Image.open(\"../input/mone-pics/20180428_040521662_iOS.jpg\") # trees\n#input_img = Image.open(\"../input/mone-pics/20180126_220901435_iOS.jpg\") # snow\n#input_img = Image.open(\"../input/mone-pics/20171202_022917555_iOS.jpg\") # sky\n#input_img = Image.open(\"../input/mone-pics/20171103_082231468_iOS.jpg\") # church\n#input_img = Image.open(\"../input/mone-pics/OO.jpg\") # myself\n\n#input_img = Image.open(\"../input/mone-pics/CorIsOtVYAALS83.jfif\")\ninput_img = input_img.resize((256, 256))\ninput_imgArray = np.asarray(input_img)\ninput_imgArray = (input_imgArray / 127.5) - 1\ninput_imgArray = input_imgArray.reshape(1, 256,256,3)\n\noutput_imgArray = monet_generator(input_imgArray, training=False).numpy()\n#output_imgArray = monet_generator(output_imgArray, training=False).numpy()\n\n#output_imgArray = (output_imgArray * 127.5 + 127.5).astype(np.uint8)\n#output_imgArray = output_imgArray.reshape(256,256,3)\n#im = PIL.Image.fromarray(prediction)\n#im.save(\"./moneko.jpg\")\n\nf = plt.figure(figsize=(30, 30))\nplt.subplot(121)\nplt.title('Input image')\nplt.imshow(input_imgArray[0] * 0.5 + 0.5)\nplt.axis('off')\n        \nplt.subplot(122)\nplt.title('Generated image')\nplt.imshow(output_imgArray[0] * 0.5 + 0.5)\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-03T19:16:17.212695Z","iopub.execute_input":"2023-09-03T19:16:17.213114Z","iopub.status.idle":"2023-09-03T19:16:18.309896Z","shell.execute_reply.started":"2023-09-03T19:16:17.213081Z","shell.execute_reply":"2023-09-03T19:16:18.308160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Run\n14697.1s - TPU v3-8\n\nPublic Score\n35.10897","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}],"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"}}