{"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":"markdown","source":"# I’m Something of a Painter Myself\n## Use GANs to create art - will you be the next Monet?\n\nhttps://www.kaggle.com/competitions/gan-getting-started\n\n### The Challenge:\nA GAN consists of at least two neural networks: a generator model and a discriminator model. The generator is a neural network that creates the images. For our competition, you should generate images in the style of Monet. This generator is trained using a discriminator.\n\nThe two models will work against each other, with the generator trying to trick the discriminator, and the discriminator trying to accurately classify the real vs. generated images.\n\nYour task is to build a GAN that generates 7,000 to 10,000 Monet-style images.\n\n### Ressources:\n- https://arxiv.org/pdf/1703.10593.pdf\n- https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix\n- https://www.tensorflow.org/tutorials/generative/cyclegan\n- https://www.kaggle.com/code/amyjang/monet-cyclegan-tutorial\n- https://www.kaggle.com/code/dimitreoliveira/introduction-to-cyclegan-monet-paintings\n- https://www.kaggle.com/code/dimitreoliveira/improving-cyclegan-monet-paintings\n- https://www.kaggle.com/code/unfriendlyai/diffaugment-is-all-you-need\n- https://github.com/mit-han-lab/data-efficient-gans","metadata":{}},{"cell_type":"markdown","source":"## Imports","metadata":{}},{"cell_type":"code","source":"import re\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport tensorflow_addons as tfa\nfrom tensorflow.keras.layers import Layer\n\nfrom kaggle_datasets import KaggleDatasets\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-06-01T14:45:31.903410Z","iopub.execute_input":"2022-06-01T14:45:31.903943Z","iopub.status.idle":"2022-06-01T14:45:38.922552Z","shell.execute_reply.started":"2022-06-01T14:45:31.903829Z","shell.execute_reply":"2022-06-01T14:45:38.921758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Connecting to TPU","metadata":{}},{"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)\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":"2022-06-01T14:45:38.924023Z","iopub.execute_input":"2022-06-01T14:45:38.924277Z","iopub.status.idle":"2022-06-01T14:45:45.030106Z","shell.execute_reply.started":"2022-06-01T14:45:38.924237Z","shell.execute_reply":"2022-06-01T14:45:45.029229Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Loading and Preprocessing Data","metadata":{}},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()\nEPOCHS = 100\nSIZE = 256\nSIZE_RESIZE = 128\nBATCH_SIZE = 16","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.031451Z","iopub.execute_input":"2022-06-01T14:45:45.031724Z","iopub.status.idle":"2022-06-01T14:45:45.564096Z","shell.execute_reply.started":"2022-06-01T14:45:45.031695Z","shell.execute_reply":"2022-06-01T14:45:45.563258Z"},"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":"2022-06-01T14:45:45.565986Z","iopub.execute_input":"2022-06-01T14:45:45.566568Z","iopub.status.idle":"2022-06-01T14:45:45.740679Z","shell.execute_reply.started":"2022-06-01T14:45:45.566536Z","shell.execute_reply":"2022-06-01T14:45:45.739881Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def random_crop(image):\n    cropped_image = tf.image.random_crop(image, size=[SIZE_RESIZE, SIZE_RESIZE, 3])\n\n    return cropped_image","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.742011Z","iopub.execute_input":"2022-06-01T14:45:45.742224Z","iopub.status.idle":"2022-06-01T14:45:45.747167Z","shell.execute_reply.started":"2022-06-01T14:45:45.742200Z","shell.execute_reply":"2022-06-01T14:45:45.746262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image):\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    \n    if p_rotate > .8:\n        image = tf.image.rot90(image, k=3) \n    elif p_rotate > .6:\n        image = tf.image.rot90(image, k=2) \n    elif p_rotate > .4:\n        image = tf.image.rot90(image, k=1)\n        \n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    if p_spatial > .75:\n        image = tf.image.transpose(image)\n        \n    image = tf.image.random_crop(image, size=[SIZE_RESIZE, SIZE_RESIZE, 3])\n        \n    return image","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.748447Z","iopub.execute_input":"2022-06-01T14:45:45.748948Z","iopub.status.idle":"2022-06-01T14:45:45.762277Z","shell.execute_reply.started":"2022-06-01T14:45:45.748917Z","shell.execute_reply":"2022-06-01T14:45:45.761607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [SIZE, SIZE]\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    \n    return image","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.763619Z","iopub.execute_input":"2022-06-01T14:45:45.764114Z","iopub.status.idle":"2022-06-01T14:45:45.776345Z","shell.execute_reply.started":"2022-06-01T14:45:45.764082Z","shell.execute_reply":"2022-06-01T14:45:45.775403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filenames, apply_jitter=False, repeat=True, shuffle=True, batch_size=BATCH_SIZE):\n    dataset = tf.data.TFRecordDataset(filenames)\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    \n    if apply_jitter:\n        dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)\n            \n    if repeat:\n        dataset = dataset.repeat()\n    if shuffle:\n        dataset = dataset.shuffle(512)\n        \n    dataset = dataset.batch(batch_size)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    \n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.777672Z","iopub.execute_input":"2022-06-01T14:45:45.778355Z","iopub.status.idle":"2022-06-01T14:45:45.794140Z","shell.execute_reply.started":"2022-06-01T14:45:45.778312Z","shell.execute_reply":"2022-06-01T14:45:45.793563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nn_monet_samples = count_data_items(MONET_FILENAMES)\nn_photo_samples = count_data_items(PHOTO_FILENAMES)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.795388Z","iopub.execute_input":"2022-06-01T14:45:45.796159Z","iopub.status.idle":"2022-06-01T14:45:45.810042Z","shell.execute_reply.started":"2022-06-01T14:45:45.796118Z","shell.execute_reply":"2022-06-01T14:45:45.808994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"monet_ds = load_dataset(MONET_FILENAMES, apply_jitter=True)\nphoto_ds = load_dataset(PHOTO_FILENAMES, apply_jitter=True)\n\nphoto_ds_test = load_dataset(PHOTO_FILENAMES, repeat=False, shuffle=False, batch_size=1)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:45.813230Z","iopub.execute_input":"2022-06-01T14:45:45.813558Z","iopub.status.idle":"2022-06-01T14:45:46.658837Z","shell.execute_reply.started":"2022-06-01T14:45:45.813521Z","shell.execute_reply":"2022-06-01T14:45:46.658017Z"},"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":"2022-06-01T14:45:46.659839Z","iopub.execute_input":"2022-06-01T14:45:46.660064Z","iopub.status.idle":"2022-06-01T14:45:49.430535Z","shell.execute_reply.started":"2022-06-01T14:45:46.660039Z","shell.execute_reply":"2022-06-01T14:45:49.429599Z"},"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":"2022-06-01T14:45:49.431795Z","iopub.execute_input":"2022-06-01T14:45:49.432028Z","iopub.status.idle":"2022-06-01T14:45:49.847166Z","shell.execute_reply.started":"2022-06-01T14:45:49.432003Z","shell.execute_reply":"2022-06-01T14:45:49.846320Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Diff Augmentation","metadata":{}},{"cell_type":"code","source":"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\ndef 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\ndef rand_saturation(x):\n    magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) * 2\n    x_mean = tf.reduce_mean(x, axis=3, keepdims=True)\n    x = (x - x_mean) * magnitude + x_mean\n    return x\n\n\ndef rand_contrast(x):\n    magnitude = tf.random.uniform([tf.shape(x)[0], 1, 1, 1]) + 0.5\n    x_mean = tf.reduce_mean(x, axis=[1, 2, 3], keepdims=True)\n    x = (x - x_mean) * magnitude + x_mean\n    return x\n\n\ndef 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\ndef 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\nAUGMENT_FNS = {\n    'color': [rand_brightness, rand_saturation, rand_contrast],\n    'translation': [rand_translation],\n    'cutout': [rand_cutout],\n}\n\ndef aug_fn(image):\n        return DiffAugment(image,\"translation,cutout\")","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:49.848614Z","iopub.execute_input":"2022-06-01T14:45:49.849443Z","iopub.status.idle":"2022-06-01T14:45:50.049393Z","shell.execute_reply.started":"2022-06-01T14:45:49.849402Z","shell.execute_reply":"2022-06-01T14:45:50.048365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"both_images = tf.concat([example_monet, example_photo], axis=0)       \naug_images = aug_fn(both_images)\naug_monet, aug_photo = tf.split(aug_images, num_or_size_splits=2, axis=0)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.050772Z","iopub.execute_input":"2022-06-01T14:45:50.051014Z","iopub.status.idle":"2022-06-01T14:45:50.136976Z","shell.execute_reply.started":"2022-06-01T14:45:50.050988Z","shell.execute_reply":"2022-06-01T14:45:50.135973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.subplot(121)\nplt.title('Photo')\nplt.imshow(aug_photo[0] * 0.5 + 0.5)\n\nplt.subplot(122)\nplt.title('Monet')\nplt.imshow(aug_monet[0] * 0.5 + 0.5)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.138394Z","iopub.execute_input":"2022-06-01T14:45:50.138651Z","iopub.status.idle":"2022-06-01T14:45:50.498987Z","shell.execute_reply.started":"2022-06-01T14:45:50.138623Z","shell.execute_reply":"2022-06-01T14:45:50.498087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## ResNet Generator","metadata":{}},{"cell_type":"code","source":"def Downsample(X, filter_count, kernel_size, padding, stride, apply_norm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    \n    X = tf.keras.layers.ZeroPadding2D((padding,padding))(X)\n    X = tf.keras.layers.Conv2D(filter_count, (kernel_size,kernel_size), padding='valid', strides=(stride,stride), \n                                      kernel_initializer=initializer, use_bias=False)(X)\n    \n    if apply_norm:\n        X = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(X)\n    \n    X = tf.keras.layers.LeakyReLU()(X)\n    \n    return X","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.500201Z","iopub.execute_input":"2022-06-01T14:45:50.500433Z","iopub.status.idle":"2022-06-01T14:45:50.508070Z","shell.execute_reply.started":"2022-06-01T14:45:50.500401Z","shell.execute_reply":"2022-06-01T14:45:50.507061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Upsample(X, filter_count, kernel_size, stride, activation='relu', apply_norm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    X = tf.keras.layers.Conv2DTranspose(filter_count, (kernel_size,kernel_size), padding='same', strides=(stride,stride), \n                                        kernel_initializer=initializer, use_bias=False)(X)\n    \n    if apply_norm:\n        X = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(X)\n        \n    X = tf.keras.layers.Activation(activation)(X)\n    \n    return X","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.509284Z","iopub.execute_input":"2022-06-01T14:45:50.509557Z","iopub.status.idle":"2022-06-01T14:45:50.526410Z","shell.execute_reply.started":"2022-06-01T14:45:50.509524Z","shell.execute_reply":"2022-06-01T14:45:50.525618Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def ResidualBlock(X):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    \n    X_shortcut = X\n    \n    # Layer 1   \n    X = tf.keras.layers.ZeroPadding2D((1,1))(X)\n    X = tf.keras.layers.Conv2D(256, (3,3), padding='valid', strides=(1,1), kernel_initializer=initializer, use_bias=False)(X)\n    X = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(X)\n    X = tf.keras.layers.Activation('relu')(X)\n    \n    # Layer 2  \n    X = tf.keras.layers.ZeroPadding2D((1,1))(X)\n    X = tf.keras.layers.Conv2D(256, (3,3), padding='valid', strides=(1,1), kernel_initializer=initializer, use_bias=False)(X)\n    X = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(X)\n    \n    X = tf.keras.layers.Add()([X, X_shortcut])\n    X = tf.keras.layers.Activation('relu')(X)\n    \n    return X","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.527813Z","iopub.execute_input":"2022-06-01T14:45:50.528102Z","iopub.status.idle":"2022-06-01T14:45:50.539913Z","shell.execute_reply.started":"2022-06-01T14:45:50.528073Z","shell.execute_reply":"2022-06-01T14:45:50.538955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def ResNetGenerator(height=SIZE, width=SIZE):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    \n    X_input = tf.keras.layers.Input((height, width, 3))\n    \n    skips = []\n    \n    X = Downsample(X_input, 64, 7, 3, 1, apply_norm=False)\n    skips.append(X)\n    \n    X = Downsample(X, 128, 3, 1, 2)\n    skips.append(X)\n    \n    X = Downsample(X, 256, 3, 1, 2)\n    \n    X = ResidualBlock(X)\n    X = ResidualBlock(X)\n    X = ResidualBlock(X)\n    X = ResidualBlock(X)\n    X = ResidualBlock(X)\n    X = ResidualBlock(X)\n    #X = ResidualBlock(X)\n    #X = ResidualBlock(X)\n    #X = ResidualBlock(X)\n    \n    skips = list(reversed(skips))\n        \n    X = Upsample(X, 128, 4, 2)\n    X = tf.keras.layers.Concatenate()([X, skips[0]])\n    \n    X = Upsample(X, 64, 4, 2)\n    X = tf.keras.layers.Concatenate()([X, skips[1]])\n    \n    X = Upsample(X, 3, 7, 1, activation='tanh', apply_norm=False)\n    \n    model = tf.keras.models.Model(inputs=X_input, outputs=X)\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.541304Z","iopub.execute_input":"2022-06-01T14:45:50.541581Z","iopub.status.idle":"2022-06-01T14:45:50.558286Z","shell.execute_reply.started":"2022-06-01T14:45:50.541551Z","shell.execute_reply":"2022-06-01T14:45:50.557178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"generator = ResNetGenerator()\ngenerator.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:50.559583Z","iopub.execute_input":"2022-06-01T14:45:50.559821Z","iopub.status.idle":"2022-06-01T14:45:51.954208Z","shell.execute_reply.started":"2022-06-01T14:45:50.559795Z","shell.execute_reply":"2022-06-01T14:45:51.953339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## PatchGAN Discriminator","metadata":{}},{"cell_type":"code","source":"def Discriminator(height=SIZE, width=SIZE):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n    \n    X_input = tf.keras.layers.Input((height, width, 3))\n\n    X = Downsample(X_input, 64, 4, 1, 2, apply_norm=False)\n    X = Downsample(X, 128, 4, 1, 2)\n    X = Downsample(X, 256, 4, 1, 2)\n    X = Downsample(X, 512, 4, 1, 1)\n    \n    X = tf.keras.layers.ZeroPadding2D()(X)\n    X = tf.keras.layers.Conv2D(1, (4,4), padding='valid', strides=(1,1), kernel_initializer=initializer, use_bias=False)(X)   \n    X = tf.keras.layers.Activation('sigmoid')(X)\n    \n    model = tf.keras.models.Model(inputs=X_input, outputs=X)\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:51.955802Z","iopub.execute_input":"2022-06-01T14:45:51.956120Z","iopub.status.idle":"2022-06-01T14:45:51.966004Z","shell.execute_reply.started":"2022-06-01T14:45:51.956080Z","shell.execute_reply":"2022-06-01T14:45:51.965140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"discriminator = Discriminator()\ndiscriminator.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:51.967362Z","iopub.execute_input":"2022-06-01T14:45:51.967636Z","iopub.status.idle":"2022-06-01T14:45:52.160065Z","shell.execute_reply.started":"2022-06-01T14:45:51.967607Z","shell.execute_reply":"2022-06-01T14:45:52.158645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = ResNetGenerator(height=None, width=None) # transforms photos to Monet-esque paintings\n    photo_generator = ResNetGenerator(height=None, width=None) # transforms Monet paintings to be more like photos\n\n    monet_discriminator = Discriminator(height=None, width=None) # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator(height=None, width=None) # differentiates real photos and generated photos","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:52.161461Z","iopub.execute_input":"2022-06-01T14:45:52.162706Z","iopub.status.idle":"2022-06-01T14:45:58.658950Z","shell.execute_reply.started":"2022-06-01T14:45:52.162666Z","shell.execute_reply":"2022-06-01T14:45:58.658075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"to_monet = monet_generator(example_photo)\n\nplt.subplot(1, 2, 1)\nplt.title(\"Original Photo\")\nplt.imshow(example_photo[0] * 0.5 + 0.5)\n\nplt.subplot(1, 2, 2)\nplt.title(\"Monet-esque Photo\")\nplt.imshow(to_monet[0] * 0.5 + 0.5)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:58.660258Z","iopub.execute_input":"2022-06-01T14:45:58.660686Z","iopub.status.idle":"2022-06-01T14:45:59.592452Z","shell.execute_reply.started":"2022-06-01T14:45:58.660650Z","shell.execute_reply":"2022-06-01T14:45:59.591420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Training","metadata":{}},{"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            # 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            # Diff Augmentation Start\n            both_monet = tf.concat([real_monet, fake_monet], axis=0)      \n            both_photo = tf.concat([real_photo, fake_photo], axis=0)            \n            \n            aug_monet = aug_fn(both_monet)\n            aug_photo = aug_fn(both_photo)\n            \n            aug_real_monet, aug_fake_monet = tf.split(aug_monet, num_or_size_splits=2, axis=0)\n            aug_real_photo, aug_fake_photo = tf.split(aug_photo, num_or_size_splits=2, axis=0)\n            # Diff Augmentation End\n            \n            # discriminator used to check, inputing real images\n            disc_real_monet = self.m_disc(aug_real_monet, training=True)\n            disc_real_photo = self.p_disc(aug_real_photo, training=True)\n\n            # discriminator used to check, inputing fake images\n            disc_fake_monet = self.m_disc(aug_fake_monet, training=True)\n            disc_fake_photo = self.p_disc(aug_fake_photo, training=True)\n\n            # evaluates generator loss\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo)\n\n            # evaluates total cycle consistency loss\n            total_cycle_loss = self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle) + self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle)\n\n            # evaluates total generator loss\n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss + self.identity_loss_fn(real_monet, same_monet, self.lambda_cycle)\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + self.identity_loss_fn(real_photo, same_photo, self.lambda_cycle)\n\n            # evaluates discriminator loss\n            monet_disc_loss = self.disc_loss_fn(disc_real_monet, disc_fake_monet)\n            photo_disc_loss = self.disc_loss_fn(disc_real_photo, disc_fake_photo)\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss,\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        # Apply the gradients to the optimizer\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_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":"2022-06-01T14:45:59.594199Z","iopub.execute_input":"2022-06-01T14:45:59.594536Z","iopub.status.idle":"2022-06-01T14:45:59.618814Z","shell.execute_reply.started":"2022-06-01T14:45:59.594471Z","shell.execute_reply":"2022-06-01T14:45:59.617901Z"},"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=False, reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(real), real)\n\n        generated_loss = tf.keras.losses.BinaryCrossentropy(from_logits=False, reduction=tf.keras.losses.Reduction.NONE)(tf.zeros_like(generated), generated)\n\n        total_disc_loss = real_loss + generated_loss\n\n        return total_disc_loss * 0.5","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.620380Z","iopub.execute_input":"2022-06-01T14:45:59.621251Z","iopub.status.idle":"2022-06-01T14:45:59.638476Z","shell.execute_reply.started":"2022-06-01T14:45:59.621215Z","shell.execute_reply":"2022-06-01T14:45:59.637754Z"},"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=False, reduction=tf.keras.losses.Reduction.NONE)(tf.ones_like(generated), generated)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.639955Z","iopub.execute_input":"2022-06-01T14:45:59.641683Z","iopub.status.idle":"2022-06-01T14:45:59.651322Z","shell.execute_reply.started":"2022-06-01T14:45:59.641635Z","shell.execute_reply":"2022-06-01T14:45:59.650533Z"},"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_mean(tf.abs(real_image - cycled_image))\n\n        return LAMBDA * loss1","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.655324Z","iopub.execute_input":"2022-06-01T14:45:59.655593Z","iopub.status.idle":"2022-06-01T14:45:59.665917Z","shell.execute_reply.started":"2022-06-01T14:45:59.655563Z","shell.execute_reply":"2022-06-01T14:45:59.664903Z"},"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":"2022-06-01T14:45:59.667366Z","iopub.execute_input":"2022-06-01T14:45:59.667696Z","iopub.status.idle":"2022-06-01T14:45:59.680938Z","shell.execute_reply.started":"2022-06-01T14:45:59.667663Z","shell.execute_reply":"2022-06-01T14:45:59.679925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"@tf.function\ndef linear_schedule_with_warmup(step):\n    \"\"\" Create a schedule with a learning rate that decreases linearly after\n    linearly increasing during a warmup period.\n    \"\"\"\n    lr_start   = 2e-4\n    lr_max     = 2e-4\n    lr_min     = 0.\n    \n    steps_per_epoch = int(max(n_monet_samples, n_photo_samples)//BATCH_SIZE)\n    total_steps = EPOCHS * steps_per_epoch\n    warmup_steps = 1\n    hold_max_steps = total_steps * 0.8\n    \n    if step < warmup_steps:\n        lr = (lr_max - lr_start) / warmup_steps * step + lr_start\n    elif step < warmup_steps + hold_max_steps:\n        lr = lr_max\n    else:\n        lr = lr_max * ((total_steps - step) / (total_steps - warmup_steps - hold_max_steps))\n        if lr_min is not None:\n            lr = tf.math.maximum(lr_min, lr)\n\n    return lr","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.682280Z","iopub.execute_input":"2022-06-01T14:45:59.682652Z","iopub.status.idle":"2022-06-01T14:45:59.698557Z","shell.execute_reply.started":"2022-06-01T14:45:59.682617Z","shell.execute_reply":"2022-06-01T14:45:59.697641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    \n    lr_monet_gen = lambda: linear_schedule_with_warmup(tf.cast(monet_generator_optimizer.iterations, tf.float32))\n    lr_photo_gen = lambda: linear_schedule_with_warmup(tf.cast(photo_generator_optimizer.iterations, tf.float32))\n    \n    monet_generator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_monet_gen, beta_1=0.5)\n    photo_generator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_photo_gen, beta_1=0.5)\n\n    lr_monet_disc = lambda: linear_schedule_with_warmup(tf.cast(monet_discriminator_optimizer.iterations, tf.float32))\n    lr_photo_disc = lambda: linear_schedule_with_warmup(tf.cast(photo_discriminator_optimizer.iterations, tf.float32))\n    \n    monet_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_monet_disc, beta_1=0.5)\n    photo_discriminator_optimizer = tf.keras.optimizers.Adam(learning_rate=lr_photo_disc, beta_1=0.5)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.700023Z","iopub.execute_input":"2022-06-01T14:45:59.700907Z","iopub.status.idle":"2022-06-01T14:45:59.714069Z","shell.execute_reply.started":"2022-06-01T14:45:59.700864Z","shell.execute_reply":"2022-06-01T14:45:59.713437Z"},"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":"2022-06-01T14:45:59.715410Z","iopub.execute_input":"2022-06-01T14:45:59.716429Z","iopub.status.idle":"2022-06-01T14:45:59.786879Z","shell.execute_reply.started":"2022-06-01T14:45:59.716386Z","shell.execute_reply":"2022-06-01T14:45:59.786123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = cycle_gan_model.fit(tf.data.Dataset.zip((monet_ds, photo_ds)), \n                        epochs=EPOCHS, \n                        steps_per_epoch=max(n_monet_samples, n_photo_samples)//BATCH_SIZE).history","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:45:59.788258Z","iopub.execute_input":"2022-06-01T14:45:59.788506Z","iopub.status.idle":"2022-06-01T14:54:48.481734Z","shell.execute_reply.started":"2022-06-01T14:45:59.788464Z","shell.execute_reply":"2022-06-01T14:54:48.479963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss_results_df = pd.DataFrame(history)\nloss_results_df = loss_results_df.applymap(np.mean)","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:54:48.482716Z","iopub.status.idle":"2022-06-01T14:54:48.483040Z","shell.execute_reply.started":"2022-06-01T14:54:48.482876Z","shell.execute_reply":"2022-06-01T14:54:48.482892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(loss_results_df.index, loss_results_df['monet_gen_loss'], color='g', label='Loss Monet Generator')\nplt.plot(loss_results_df.index, loss_results_df['photo_gen_loss'], color='r', label='Loss Photo Generator')\nplt.plot(loss_results_df.index, loss_results_df['monet_disc_loss'], color='b', label='Loss Monet Discriminator')\nplt.plot(loss_results_df.index, loss_results_df['photo_disc_loss'], color='m', label='Loss Photo Discriminator')\nplt.legend(loc='best')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:54:48.484202Z","iopub.status.idle":"2022-06-01T14:54:48.484579Z","shell.execute_reply.started":"2022-06-01T14:54:48.484372Z","shell.execute_reply":"2022-06-01T14:54:48.484394Z"},"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_test.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    \n    ax[i, 0].imshow(img)\n    ax[i, 1].imshow(prediction)\n    ax[i, 0].set_title(\"Input Photo\")\n    ax[i, 1].set_title(\"Monet-esque\")\n    ax[i, 0].axis(\"off\")\n    ax[i, 1].axis(\"off\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:54:48.486469Z","iopub.status.idle":"2022-06-01T14:54:48.487433Z","shell.execute_reply.started":"2022-06-01T14:54:48.487133Z","shell.execute_reply":"2022-06-01T14:54:48.487161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prediction and Submission","metadata":{}},{"cell_type":"code","source":"import PIL\n! mkdir ../images","metadata":{"execution":{"iopub.status.busy":"2022-06-01T14:54:48.488711Z","iopub.status.idle":"2022-06-01T14:54:48.489668Z","shell.execute_reply.started":"2022-06-01T14:54:48.489363Z","shell.execute_reply":"2022-06-01T14:54:48.489398Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"i = 1\nfor img in photo_ds_test:\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":{"execution":{"iopub.status.busy":"2022-06-01T14:54:48.490840Z","iopub.status.idle":"2022-06-01T14:54:48.491692Z","shell.execute_reply.started":"2022-06-01T14:54:48.491395Z","shell.execute_reply":"2022-06-01T14:54:48.491421Z"},"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":"2022-06-01T14:54:48.492915Z","iopub.status.idle":"2022-06-01T14:54:48.494892Z","shell.execute_reply.started":"2022-06-01T14:54:48.494599Z","shell.execute_reply":"2022-06-01T14:54:48.494626Z"},"trusted":true},"execution_count":null,"outputs":[]}]}