{"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 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\nimport os\nimport re\n\nBATCH_SIZE = 32\n\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\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()\n    \nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\nGCS_PATH = KaggleDatasets().get_gcs_path()\nMONET_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/monet_tfrec/*.tfrec'))\nPHOTO_FILENAMES = tf.io.gfile.glob(str(GCS_PATH + '/photo_tfrec/*.tfrec'))\n\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_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):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-05-24T17:16:32.412865Z","iopub.execute_input":"2021-05-24T17:16:32.413364Z","iopub.status.idle":"2021-05-24T17:16:40.611022Z","shell.execute_reply.started":"2021-05-24T17:16:32.413330Z","shell.execute_reply":"2021-05-24T17:16:40.609929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_ds = load_dataset(MONET_FILENAMES).batch(1)\nphoto_ds = load_dataset(PHOTO_FILENAMES).batch(1)\nexample_monet = next(iter(monet_ds))\nexample_photo = next(iter(photo_ds))\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":"2021-05-24T17:16:40.612348Z","iopub.execute_input":"2021-05-24T17:16:40.612639Z","iopub.status.idle":"2021-05-24T17:16:40.867644Z","shell.execute_reply.started":"2021-05-24T17:16:40.612611Z","shell.execute_reply":"2021-05-24T17:16:40.866651Z"},"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    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.prefetch(AUTOTUNE)\n    photo_ds = photo_ds.prefetch(AUTOTUNE)\n    gan_ds = tf.data.Dataset.zip((monet_ds, photo_ds))\n    return gan_ds\n\nfinal_dataset = get_gan_dataset(MONET_FILENAMES, PHOTO_FILENAMES, augment=None, repeat=True, shuffle=True, batch_size=BATCH_SIZE)\n\nwith strategy.scope():\n    inception_model = tf.keras.applications.InceptionV3(input_shape=(256,256,3),pooling=\"avg\",include_top=False)\n    mix3  = inception_model.get_layer(\"mixed9\").output\n    f0 = tf.keras.layers.GlobalAveragePooling2D()(mix3)\n    inception_model = tf.keras.Model(inputs=inception_model.input, outputs=f0)\n    inception_model.trainable = False\n    \n    def calculate_activation_statistics_mod(images,fid_model):\n            act=tf.cast(fid_model.predict(images), tf.float32)\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":"2021-05-24T17:16:40.869747Z","iopub.execute_input":"2021-05-24T17:16:40.870029Z","iopub.status.idle":"2021-05-24T17:17:04.367686Z","shell.execute_reply.started":"2021-05-24T17:16:40.870002Z","shell.execute_reply":"2021-05-24T17:17:04.366488Z"},"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        covmean = tf.linalg.sqrtm(tf.cast(tf.matmul(sigma1,sigma2),tf.complex64))\n        covmean = tf.cast(tf.math.real(covmean),tf.float32)\n        tr_covmean = tf.linalg.trace(covmean)\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    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                mu1, sigma1= calculate_activation_statistics_mod(images,fid_model)\n                fid_value = calculate_frechet_distance(mu1, sigma1,myFID_mu2, myFID_sigma2)\n                return fid_value\n","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:04.369311Z","iopub.execute_input":"2021-05-24T17:17:04.369767Z","iopub.status.idle":"2021-05-24T17:17:04.379773Z","shell.execute_reply.started":"2021-05-24T17:17:04.369668Z","shell.execute_reply":"2021-05-24T17:17:04.378740Z"},"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    result = keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n    if apply_instancenorm:\n        result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n    result.add(layers.LeakyReLU())\n    return result\n\n\n\n\ndef 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    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    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n    result.add(layers.ReLU())\n    return result\n\n\n\n\ndef Generator():\n    inputs = layers.Input(shape=[256,256,3])\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    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    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    x = inputs\n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n    skips = reversed(skips[:-1])\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = layers.Concatenate()([x, skip])\n    x = last(x)\n    return keras.Model(inputs=inputs, outputs=x)\n\n\ndef DHead():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    inp = layers.Input(shape=[33, 33, 512], name='input_image')\n    x = inp\n    last = layers.Conv2D(1, 4, strides=1, kernel_initializer=initializer)(x) # (size, 30, 30, 1)\n    return tf.keras.Model(inputs=inp, outputs=last)\n\n\ndef DiscriminatorM():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    inp = layers.Input(shape=[256, 256, 3], name='input_image')\n    x = inp\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    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    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n    leaky_relu = layers.LeakyReLU()(norm1)\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n    return tf.keras.Model(inputs=inp, outputs=zero_pad2)\n\n\ndef Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    inp = layers.Input(shape=[256, 256, 3], name='input_image')\n    x = inp\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    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    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n    leaky_relu = layers.LeakyReLU()(norm1)\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n    last = layers.Conv2D(1, 4, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:04.381166Z","iopub.execute_input":"2021-05-24T17:17:04.381460Z","iopub.status.idle":"2021-05-24T17:17:04.413468Z","shell.execute_reply.started":"2021-05-24T17:17:04.381429Z","shell.execute_reply":"2021-05-24T17:17:04.412488Z"},"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    monet_discriminator = DiscriminatorM() # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator() # differentiates real photos and generated photos\n    dhead1 = DHead()\n    dhead2 = DHead()","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:04.414816Z","iopub.execute_input":"2021-05-24T17:17:04.415342Z","iopub.status.idle":"2021-05-24T17:17:09.173006Z","shell.execute_reply.started":"2021-05-24T17:17:04.415310Z","shell.execute_reply":"2021-05-24T17:17:09.171971Z"},"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        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        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        \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            fake_photo = self.p_gen(real_monet, training=True)\n            cycled_monet = self.m_gen(fake_photo, training=True)\n            same_monet = self.m_gen(real_monet, training=True)\n            same_photo = self.p_gen(real_photo, training=True)\n            both_monet = tf.concat([real_monet, fake_monet], axis=0)            \n            aug_monet = self.aug_fn(both_monet)\n            aug_real_monet = aug_monet[:batch_size]\n            aug_fake_monet = aug_monet[batch_size:]\n\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            monet_gen_loss = (monet_gen_loss1 + monet_gen_loss2) * 0.4\n            monet_disc_loss = monet_head_loss1 + monet_head_loss2\n            disc_real_photo = self.p_disc(real_photo, training=True)\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n            photo_gen_loss = self.gen_loss_fn1(disc_fake_photo)\n            photo_disc_loss = self.disc_loss_fn1(disc_real_photo, disc_fake_photo)\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            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            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            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            monet_head_gradients = tape.gradient(monet_head_loss1,\n                                                      self.dhead1.trainable_variables)\n            self.m_disc_optimizer.apply_gradients(zip(monet_head_gradients,\n                                                  self.dhead1.trainable_variables))       \n            monet_head_gradients = tape.gradient(monet_head_loss2,\n                                                      self.dhead2.trainable_variables)\n            self.m_disc_optimizer.apply_gradients(zip(monet_head_gradients,\n                                                  self.dhead2.trainable_variables))     \n            self.m_gen_optimizer.apply_gradients(zip(monet_generator_gradients,\n                                                 self.m_gen.trainable_variables))\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\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            }\n","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:09.174483Z","iopub.execute_input":"2021-05-24T17:17:09.174795Z","iopub.status.idle":"2021-05-24T17:17:09.205200Z","shell.execute_reply.started":"2021-05-24T17:17:09.174764Z","shell.execute_reply":"2021-05-24T17:17:09.204004Z"},"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)\n\nwith 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))\n    \nwith 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\n    \nwith 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":"2021-05-24T17:17:09.207508Z","iopub.execute_input":"2021-05-24T17:17:09.207861Z","iopub.status.idle":"2021-05-24T17:17:09.222044Z","shell.execute_reply.started":"2021-05-24T17:17:09.207828Z","shell.execute_reply":"2021-05-24T17:17:09.221012Z"},"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":"2021-05-24T17:17:09.223680Z","iopub.execute_input":"2021-05-24T17:17:09.223967Z","iopub.status.idle":"2021-05-24T17:17:09.252719Z","shell.execute_reply.started":"2021-05-24T17:17:09.223937Z","shell.execute_reply":"2021-05-24T17:17:09.251100Z"},"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\n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(2e-4, beta_1=0.5)\n    \nwith strategy.scope():\n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, monet_discriminator, photo_discriminator, dhead1, dhead2\n    )\n\nwith strategy.scope():\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    \nwith 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    )","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:09.254136Z","iopub.execute_input":"2021-05-24T17:17:09.254460Z","iopub.status.idle":"2021-05-24T17:17:09.345980Z","shell.execute_reply.started":"2021-05-24T17:17:09.254428Z","shell.execute_reply":"2021-05-24T17:17:09.344857Z"},"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=30)","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:17:09.347609Z","iopub.execute_input":"2021-05-24T17:17:09.348024Z","iopub.status.idle":"2021-05-24T17:18:58.305732Z","shell.execute_reply.started":"2021-05-24T17:17:09.347975Z","shell.execute_reply":"2021-05-24T17:18:58.303546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(photo_ds)\nfor n_sample in range(8):\n        example_sample = next(ds_iter)\n        generated_sample = monet_generator(example_sample)\n        \n        f = plt.figure(figsize=(32, 32))\n        \n        plt.subplot(121)\n        plt.title('Input image')\n        plt.imshow(example_sample[0] * 0.5 + 0.5)\n        plt.axis('off')\n        \n        plt.subplot(122)\n        plt.title('Generated image')\n        plt.imshow(generated_sample[0] * 0.5 + 0.5)\n        plt.axis('off')\n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:18:58.306647Z","iopub.status.idle":"2021-05-24T17:18:58.307062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(monet_ds)\nfor n_sample in range(8):\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":"2021-05-24T17:18:58.308392Z","iopub.status.idle":"2021-05-24T17:18:58.309043Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import PIL\n! mkdir ../images\ni = 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\nimport shutil\nshutil.make_archive(\"/kaggle/working/images\", 'zip', \"/kaggle/images\")\n\n\n# First of all, most of the code is taken from the tutorial notebooks provided by the competition. I wrote a small percentage of the code, so don't be\n# too impressed. I'm currently trying to overcome a few weird errors that have arisen in trying to run the code. Every change I've made so far has caused\n# a lower score. but I believe the current code will be able to finally lower it once I get the errors out. The errors also seem to be the product of the\n# dataset, which is weird and hard to figure out, but being able to finally run it and see how the score has changed will be my next goal. From there,\n# I will work to lower it even further up until the deadline. Enjoy your weekend (our whenever it is) and I am sorry I couldn't give you a model that runs. \n\n","metadata":{"execution":{"iopub.status.busy":"2021-05-24T17:18:58.310033Z","iopub.status.idle":"2021-05-24T17:18:58.310677Z"},"trusted":true},"execution_count":null,"outputs":[]}]}