{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"0cf03230-9df0-4805-914d-b0a60f49f013","_cell_guid":"666ffadf-dd24-4222-ab27-a5945c52b1f7","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:28:32.045381Z","iopub.execute_input":"2021-07-26T01:28:32.046163Z","iopub.status.idle":"2021-07-26T01:28:36.824407Z","shell.execute_reply.started":"2021-07-26T01:28:32.046012Z","shell.execute_reply":"2021-07-26T01:28:36.823549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport math\nimport random\nimport matplotlib.pyplot as plt\nimport cv2\nimport tensorflow as tf\nfrom   tensorflow import keras\nfrom   tensorflow.keras import layers\nimport tensorflow_addons as tfa\nimport tensorflow_datasets as tfds\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow.keras.backend as K\nimport os, random, json, PIL, shutil, re, imageio, glob\nfrom tensorflow.keras import Model, losses, optimizers\nfrom tensorflow.keras.callbacks import Callback\nfrom kaggle_datasets import KaggleDatasets","metadata":{"_uuid":"cde3432f-31f7-4114-b1a9-27a17e05c6b8","_cell_guid":"0227b91b-e4c2-4dff-b64e-26dd00717dec","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:28:36.825683Z","iopub.execute_input":"2021-07-26T01:28:36.82593Z","iopub.status.idle":"2021-07-26T01:28:43.284334Z","shell.execute_reply.started":"2021-07-26T01:28:36.825906Z","shell.execute_reply":"2021-07-26T01:28:43.283504Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(f'Running on TPU {tpu.master()}')\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy()\n\n\nREPLICAS = strategy.num_replicas_in_sync\nAUTO = tf.data.experimental.AUTOTUNE\nprint(f'REPLICAS: {REPLICAS}')","metadata":{"_uuid":"a2e1fd45-d2a8-40cb-9f53-9ae8355de95c","_cell_guid":"0531fd44-86d7-4dc7-b88f-2805440e6edd","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:28:43.285901Z","iopub.execute_input":"2021-07-26T01:28:43.28628Z","iopub.status.idle":"2021-07-26T01:28:48.716174Z","shell.execute_reply.started":"2021-07-26T01:28:43.286223Z","shell.execute_reply":"2021-07-26T01:28:48.715235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_PATH = '../input/gan-getting-started/'\nMONET_PATH = os.path.join(BASE_PATH, 'monet_jpg')\nPHOTO_PATH = os.path.join(BASE_PATH, 'photo_jpg')","metadata":{"_uuid":"e3208e13-ebe7-4d2b-a5e8-03b0c6e02402","_cell_guid":"c321ac27-c641-40a9-a0be-47e063749cba","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:28:48.717414Z","iopub.execute_input":"2021-07-26T01:28:48.71771Z","iopub.status.idle":"2021-07-26T01:28:48.721352Z","shell.execute_reply.started":"2021-07-26T01:28:48.717683Z","shell.execute_reply":"2021-07-26T01:28:48.720737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_folder_info(path):\n    d_image_sizes = {}\n    for image_name in os.listdir(path):\n        image = cv2.imread(os.path.join(path, image_name))\n        d_image_sizes[image.shape] = d_image_sizes.get(image.shape, 0) + 1\n        \n    for size, count in d_image_sizes.items():\n        print(f'shape: {size}\\tcount: {count}')\n\n\nprint('Monet images:')\nshow_folder_info(MONET_PATH)\n\nprint('Photo images:')\nshow_folder_info(PHOTO_PATH)","metadata":{"_uuid":"31698a42-b4fe-4b0f-8091-a7128f13679f","_cell_guid":"6fd5b891-1fa2-4a87-b787-f3137227ae11","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:28:48.722104Z","iopub.execute_input":"2021-07-26T01:28:48.722322Z","iopub.status.idle":"2021-07-26T01:29:35.792915Z","shell.execute_reply.started":"2021-07-26T01:28:48.7223Z","shell.execute_reply":"2021-07-26T01:29:35.792086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def batch_visualization(path, n_images, is_random=True, figsize=(16, 16)):\n    plt.figure(figsize=figsize)\n    \n    w = int(n_images ** .5)\n    h = math.ceil(n_images / w)\n    \n    all_names = os.listdir(path)\n    \n    image_names = all_names[:n_images]\n    if is_random:\n        image_names = random.sample(all_names, n_images)\n    \n    for ind, image_name in enumerate(image_names):\n        img = cv2.imread(os.path.join(path, image_name))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n        plt.subplot(h, w, ind + 1)\n        plt.imshow(img)\n        plt.axis('off')\n    \n    plt.show()","metadata":{"_uuid":"99ada080-19cf-42ef-9ef2-27bed39d56ae","_cell_guid":"54590376-5e1a-4b15-9352-ff1c84982167","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:35.793975Z","iopub.execute_input":"2021-07-26T01:29:35.794231Z","iopub.status.idle":"2021-07-26T01:29:35.802411Z","shell.execute_reply.started":"2021-07-26T01:29:35.794206Z","shell.execute_reply":"2021-07-26T01:29:35.801553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_visualization(MONET_PATH, 12, is_random=True, figsize=(23, 23))","metadata":{"_uuid":"b6fd45d8-f14c-4a6a-bedc-a080b7ad7fe6","_cell_guid":"6716e514-39c9-442f-8593-7ceed912b16a","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:35.803633Z","iopub.execute_input":"2021-07-26T01:29:35.803903Z","iopub.status.idle":"2021-07-26T01:29:37.178023Z","shell.execute_reply.started":"2021-07-26T01:29:35.803877Z","shell.execute_reply":"2021-07-26T01:29:37.176976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_visualization(PHOTO_PATH, 12, is_random=True, figsize=(23, 23))","metadata":{"_uuid":"7775ce58-e3d7-4e4b-8dc2-d16ffdffc415","_cell_guid":"71440f8e-4016-405f-9604-1c1f979ba729","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:37.18037Z","iopub.execute_input":"2021-07-26T01:29:37.180704Z","iopub.status.idle":"2021-07-26T01:29:38.450709Z","shell.execute_reply.started":"2021-07-26T01:29:37.180672Z","shell.execute_reply":"2021-07-26T01:29:38.449704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plotting colour histograms for Monet paintings\ndef color_hist_visualization(image_path, figsize=(16, 4)):\n    plt.figure(figsize=figsize)\n    colors = ['red', 'green', 'blue']\n    \n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    plt.subplot(1, 4, 1)\n    plt.imshow(img)\n    plt.axis('off')\n    \n    for i in range(len(colors)):\n        plt.subplot(1, 4, i + 2)\n        plt.hist(\n            img[:, :, i].reshape(-1),\n            bins=25,\n            alpha=0.5,\n            color=colors[i],\n            density=True\n        )\n        plt.xlim(0, 255)\n        plt.xticks([])\n        plt.yticks([])\n    plt.show()","metadata":{"_uuid":"c6aaaa95-27c5-4168-9cf9-6de6292c699d","_cell_guid":"dc92f338-b9c5-413b-b3f4-6e00505ce22b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:38.452467Z","iopub.execute_input":"2021-07-26T01:29:38.452781Z","iopub.status.idle":"2021-07-26T01:29:38.460479Z","shell.execute_reply.started":"2021-07-26T01:29:38.452753Z","shell.execute_reply":"2021-07-26T01:29:38.459588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/05b493ff42.jpg'\ncolor_hist_visualization(img_path)","metadata":{"_uuid":"7d19dfee-c22a-4d0d-b76e-9757224356b3","_cell_guid":"6db397a9-9bc9-4c03-bee9-c3648ee23dc0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:38.46156Z","iopub.execute_input":"2021-07-26T01:29:38.46185Z","iopub.status.idle":"2021-07-26T01:29:38.832871Z","shell.execute_reply.started":"2021-07-26T01:29:38.461824Z","shell.execute_reply":"2021-07-26T01:29:38.831877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/052a77c020.jpg'\ncolor_hist_visualization(img_path)","metadata":{"_uuid":"6b9468f9-9bb8-4855-8435-3852cb705205","_cell_guid":"a9566b43-5ff1-4dd5-8d64-f33980e1443d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:38.834241Z","iopub.execute_input":"2021-07-26T01:29:38.834641Z","iopub.status.idle":"2021-07-26T01:29:39.40078Z","shell.execute_reply.started":"2021-07-26T01:29:38.834583Z","shell.execute_reply":"2021-07-26T01:29:39.39984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/0e3b3292da.jpg'\ncolor_hist_visualization(img_path)","metadata":{"execution":{"iopub.status.busy":"2021-07-26T01:29:39.402202Z","iopub.execute_input":"2021-07-26T01:29:39.402763Z","iopub.status.idle":"2021-07-26T01:29:39.754544Z","shell.execute_reply.started":"2021-07-26T01:29:39.402718Z","shell.execute_reply":"2021-07-26T01:29:39.753676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/09b76b6471.jpg'\ncolor_hist_visualization(img_path)","metadata":{"_uuid":"553f3508-c110-491c-a6ce-d089b8a6509b","_cell_guid":"882318b6-3668-43f1-9230-8a3f67b33c20","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:39.755901Z","iopub.execute_input":"2021-07-26T01:29:39.756413Z","iopub.status.idle":"2021-07-26T01:29:40.104Z","shell.execute_reply.started":"2021-07-26T01:29:39.756376Z","shell.execute_reply":"2021-07-26T01:29:40.103057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/064487d630.jpg'\ncolor_hist_visualization(img_path)","metadata":{"execution":{"iopub.status.busy":"2021-07-26T01:29:40.105509Z","iopub.execute_input":"2021-07-26T01:29:40.105912Z","iopub.status.idle":"2021-07-26T01:29:40.458458Z","shell.execute_reply.started":"2021-07-26T01:29:40.10586Z","shell.execute_reply":"2021-07-26T01:29:40.457502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Individual channels visualization \ndef channels_visualization(image_path, figsize=(16, 4)):\n    plt.figure(figsize=figsize)\n    \n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    plt.subplot(1, 4, 1)\n    plt.imshow(img)\n    plt.axis('off')\n    \n    for i in range(3):\n        plt.subplot(1, 4, i + 2)\n        tmp_img = np.full_like(img, 0)\n        tmp_img[:, :, i] = img[:, :, i]\n        plt.imshow(tmp_img)\n        plt.xlim(0, 255)\n        plt.xticks([])\n        plt.yticks([])\n    plt.show()","metadata":{"_uuid":"efb95b21-ea1e-4c67-b613-048d878535bd","_cell_guid":"1ff1f71f-0b4f-4680-8f06-488290420445","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:40.459857Z","iopub.execute_input":"2021-07-26T01:29:40.460244Z","iopub.status.idle":"2021-07-26T01:29:40.467239Z","shell.execute_reply.started":"2021-07-26T01:29:40.460211Z","shell.execute_reply":"2021-07-26T01:29:40.466477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/0bd913dbc7.jpg'\ncolor_hist_visualization(img_path)\nchannels_visualization(img_path)","metadata":{"_uuid":"717d8940-7170-463b-ae54-b5a6a1786fa5","_cell_guid":"01d90c08-f157-43e7-9053-29220a4d52e0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:40.468395Z","iopub.execute_input":"2021-07-26T01:29:40.468909Z","iopub.status.idle":"2021-07-26T01:29:41.124109Z","shell.execute_reply.started":"2021-07-26T01:29:40.468879Z","shell.execute_reply":"2021-07-26T01:29:41.122963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Grayscale visualization\ndef grayscale_visualization(image_path, figsize=(8, 4)):\n    plt.figure(figsize=figsize)\n    \n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) \n    plt.subplot(1, 2, 1)\n    plt.imshow(img)\n    plt.axis('off')\n    \n    plt.subplot(1, 2, 2)\n    tmp_img = np.full_like(img, 0)\n    for i in range(3):\n        tmp_img[:, :, i] = img.mean(axis=-1)\n    plt.imshow(tmp_img)\n    plt.axis('off')\n    \n    \n    plt.show()","metadata":{"_uuid":"616004a3-0e1c-430c-a8ef-1a4c8499e08f","_cell_guid":"e51e996f-f6e0-428f-b64d-c7bcc5ec49ec","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:41.125702Z","iopub.execute_input":"2021-07-26T01:29:41.126116Z","iopub.status.idle":"2021-07-26T01:29:41.138862Z","shell.execute_reply.started":"2021-07-26T01:29:41.126077Z","shell.execute_reply":"2021-07-26T01:29:41.136465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = '../input/gan-getting-started/monet_jpg/990ed28f62.jpg'\ngrayscale_visualization(img_path)","metadata":{"_uuid":"2babbf8e-d8d2-4467-a586-f26a21458ed7","_cell_guid":"7d1d4e97-b74e-447d-966a-cd97cd2b064f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:41.139979Z","iopub.execute_input":"2021-07-26T01:29:41.140347Z","iopub.status.idle":"2021-07-26T01:29:41.32145Z","shell.execute_reply.started":"2021-07-26T01:29:41.140321Z","shell.execute_reply":"2021-07-26T01:29:41.320472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_PATH = KaggleDatasets().get_gcs_path()","metadata":{"_uuid":"625385e9-1357-4611-a3c7-46cc48f99146","_cell_guid":"e1bad8a6-ee02-437b-9bce-31109df87ad2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:41.322811Z","iopub.execute_input":"2021-07-26T01:29:41.323181Z","iopub.status.idle":"2021-07-26T01:29:41.838395Z","shell.execute_reply.started":"2021-07-26T01:29:41.323144Z","shell.execute_reply":"2021-07-26T01:29:41.837604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the Google Cloud Storage path URI (GCS path) for Kaggle Datasets\nGCS_PATH = KaggleDatasets().get_gcs_path('gan-getting-started')\n\nGCS_PATH","metadata":{"_uuid":"3c39f9ca-d789-4c80-b2f9-0b2eafb20762","_cell_guid":"86364407-7186-4717-950d-e66a1303becc","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:41.839479Z","iopub.execute_input":"2021-07-26T01:29:41.839746Z","iopub.status.idle":"2021-07-26T01:29:42.337821Z","shell.execute_reply.started":"2021-07-26T01:29:41.839721Z","shell.execute_reply":"2021-07-26T01:29:42.336755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Obtain two lists of files that match the given patterns specified in str()\ndef 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\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\nn_monet_samples = count_data_items(MONET_FILENAMES)\nn_photo_samples = count_data_items(PHOTO_FILENAMES)\n\nprint('Number of Monet TFRecord Files:', len(MONET_FILENAMES))\nprint('Number of Photo TFRecord Files:', len(PHOTO_FILENAMES))","metadata":{"_uuid":"9b8ca1a8-fb8f-48a4-ad3a-6d0fb39f7370","_cell_guid":"70c8dbc3-e3dd-4616-8f65-ccf83ac101eb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.340892Z","iopub.execute_input":"2021-07-26T01:29:42.341181Z","iopub.status.idle":"2021-07-26T01:29:42.619443Z","shell.execute_reply.started":"2021-07-26T01:29:42.341152Z","shell.execute_reply":"2021-07-26T01:29:42.61859Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BUFFER_SIZE = 1000\nBATCH_SIZE =  4\nEPOCHS_NUM = 15\nIMG_WIDTH = 256\nIMG_HEIGHT = 256","metadata":{"_uuid":"39654bf3-0a61-4855-a7ef-21173479fc23","_cell_guid":"a7dee4e5-74b9-4c0a-b372-446f0e297e56","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.620469Z","iopub.execute_input":"2021-07-26T01:29:42.620749Z","iopub.status.idle":"2021-07-26T01:29:42.625267Z","shell.execute_reply.started":"2021-07-26T01:29:42.620725Z","shell.execute_reply":"2021-07-26T01:29:42.624058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def decode_image(image):\n    # Decode a JPEG-encoded image to a uint8 tensor.\n    image = tf.image.decode_jpeg(image, channels=3)\n    \n    # Normalize the image to the range of the tanh activation function [-1, 1] for \n    # inputs to the generator and discriminator in GAN model \n    # (i.e. the pixel values are divided by (255/2) to form a value of in a range of [0, 2] and then subtract by 1\n    # to result into a range of [-1, 1])\n    image = (tf.cast(image, tf.float32) / 127.5) - 1        \n    \n    # Reshape the tensor using (256, 256, 3) where 3 is number of channels: Red, Green, and Blue \n    image = tf.reshape(image, [IMG_HEIGHT, IMG_WIDTH, 3])             \n    return image\n\ndef read_tfrecord(example):\n    # Define TFRecord format \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    # Parse a single example\n    example = tf.io.parse_single_example(example, tfrecord_format)  \n    # Decode a JPEG image to a uint8 tensor by calling decode_image()\n    image = decode_image(example['image'])    \n    \n    return image # Return an image tensor","metadata":{"_uuid":"6747e4a4-28eb-41f6-97e8-349b7b4fbf50","_cell_guid":"c9906129-347d-4692-bf35-021b7208231d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.630536Z","iopub.execute_input":"2021-07-26T01:29:42.63096Z","iopub.status.idle":"2021-07-26T01:29:42.638805Z","shell.execute_reply.started":"2021-07-26T01:29:42.630931Z","shell.execute_reply":"2021-07-26T01:29:42.637674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image):\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    p_crop = tf.random.uniform([], 0, 1.0, dtype=tf.float32)\n    \n    # Apply jitter\n    if p_crop > .5:\n        image = tf.image.resize(image, [286, 286])\n        image = tf.image.random_crop(image, size=[256, 256, 3])\n        if p_crop > .9:\n            image = tf.image.resize(image, [300, 300])\n            image = tf.image.random_crop(image, size=[256, 256, 3])\n    \n    # Random rotation\n    if p_rotate > .9:\n        image = tf.image.rot90(image, k=3) # rotate 270º\n    elif p_rotate > .7:\n        image = tf.image.rot90(image, k=2) # rotate 180º\n    elif p_rotate > .5:\n        image = tf.image.rot90(image, k=1) # rotate 90º\n    \n    # Random mirroring\n    if p_spatial > .6:\n        image = tf.image.random_flip_left_right(image)\n        image = tf.image.random_flip_up_down(image)\n        if p_spatial > .9:\n            image = tf.image.transpose(image)\n    \n    return image","metadata":{"_uuid":"9daf433a-71b5-4917-bb98-8ae6f481f59e","_cell_guid":"7999bf38-94a5-4a22-82ae-f9769ccb1014","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.640722Z","iopub.execute_input":"2021-07-26T01:29:42.640976Z","iopub.status.idle":"2021-07-26T01:29:42.651073Z","shell.execute_reply.started":"2021-07-26T01:29:42.640952Z","shell.execute_reply":"2021-07-26T01:29:42.649988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set it to tf.data.experimental.AUTOTUNE which will prompt \n# the tf.data runtime to tune the value dynamically at runtime.\nAUTOTUNE = tf.data.experimental.AUTOTUNE  \n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    dataset = tf.data.TFRecordDataset(filenames)\n    # map a dataset with a mapping function read_tfrecord and \n    # Number of parallel calls is set to AUTOTUNE constant previously defined\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"_uuid":"5844bdc6-bbee-497f-906f-7172a7164149","_cell_guid":"0d297002-6857-443f-bdb8-74c32b48cb90","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.652585Z","iopub.execute_input":"2021-07-26T01:29:42.653072Z","iopub.status.idle":"2021-07-26T01:29:42.664525Z","shell.execute_reply.started":"2021-07-26T01:29:42.65302Z","shell.execute_reply":"2021-07-26T01:29:42.663712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCHSIZE = 1\nmonet_ds = load_dataset(MONET_FILENAMES, labeled=True).batch(BATCHSIZE, drop_remainder=True)\nphoto_ds = load_dataset(PHOTO_FILENAMES, labeled=True).batch(BATCHSIZE, drop_remainder=True)","metadata":{"_uuid":"5660fbfc-ed9f-4ee8-9520-18bab230580a","_cell_guid":"70ffa645-3f8c-4a6b-9db5-d6da017d9b89","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.665929Z","iopub.execute_input":"2021-07-26T01:29:42.666397Z","iopub.status.idle":"2021-07-26T01:29:42.835397Z","shell.execute_reply.started":"2021-07-26T01:29:42.666358Z","shell.execute_reply":"2021-07-26T01:29:42.834636Z"},"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=AUTO)\n        photo_ds = photo_ds.map(augment, num_parallel_calls=AUTO)\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(AUTO)\n    photo_ds = photo_ds.prefetch(AUTO)\n    \n    gan_ds = tf.data.Dataset.zip((monet_ds, photo_ds))\n    \n    return gan_ds","metadata":{"_uuid":"20db98bb-3c41-4a9e-a586-5e942745642a","_cell_guid":"957bab65-8616-44e5-ad8e-da4ef0b919b0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.83649Z","iopub.execute_input":"2021-07-26T01:29:42.836751Z","iopub.status.idle":"2021-07-26T01:29:42.843917Z","shell.execute_reply.started":"2021-07-26T01:29:42.836727Z","shell.execute_reply":"2021-07-26T01:29:42.843015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"full_dataset = get_gan_dataset(MONET_FILENAMES, PHOTO_FILENAMES, augment=data_augment, repeat=True, shuffle=True, batch_size=BATCH_SIZE)","metadata":{"_uuid":"e71baf4a-cd37-4565-8925-1ebaf0ae584e","_cell_guid":"f4905eca-77cd-449b-a03a-3e77be4c14a1","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:42.845271Z","iopub.execute_input":"2021-07-26T01:29:42.845684Z","iopub.status.idle":"2021-07-26T01:29:43.615117Z","shell.execute_reply.started":"2021-07-26T01:29:42.845641Z","shell.execute_reply":"2021-07-26T01:29:43.614292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"example_monet , example_photo = next(iter(full_dataset))","metadata":{"_uuid":"cd05100f-f857-4fe4-bf65-dd3f35041cfe","_cell_guid":"923a732c-f542-4166-a175-9f170620c517","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:43.617261Z","iopub.execute_input":"2021-07-26T01:29:43.617582Z","iopub.status.idle":"2021-07-26T01:29:49.69927Z","shell.execute_reply.started":"2021-07-26T01:29:43.617554Z","shell.execute_reply":"2021-07-26T01:29:49.69833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def view_image(ds, nrows=1, ncols=5):\n    ds_iter = iter(ds)\n    # image = next(iter(ds)) # extract 1 from the dataset\n    # image = image.numpy()  # convert the image tensor to NumPy ndarrays.\n\n    fig = plt.figure(figsize=(25, nrows * 5.05 )) # figsize with Width, Height\n\n    # loop thru all the images (number of rows * number of columns)\n    for i in range(ncols * nrows):\n        image = next(ds_iter)\n        image = image.numpy()\n        ax = fig.add_subplot(nrows, ncols, i+1, xticks=[], yticks=[])\n        ax.imshow(image[0] * 0.5 + .5) # rescale the data in [0, 1] for display","metadata":{"_uuid":"73cdcc8d-625f-48b2-ad8c-1183a8d8abb7","_cell_guid":"7b4e6696-5aee-4029-b683-6ede4d202fae","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:49.700433Z","iopub.execute_input":"2021-07-26T01:29:49.700725Z","iopub.status.idle":"2021-07-26T01:29:49.706142Z","shell.execute_reply.started":"2021-07-26T01:29:49.700699Z","shell.execute_reply":"2021-07-26T01:29:49.705507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_image(monet_ds,2, 5)","metadata":{"_uuid":"aa352b6c-265f-4077-8900-0fd52f443c7e","_cell_guid":"54d1d0b4-3cc4-449c-a2ea-3cd37a22441e","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:49.707059Z","iopub.execute_input":"2021-07-26T01:29:49.707314Z","iopub.status.idle":"2021-07-26T01:29:51.817892Z","shell.execute_reply.started":"2021-07-26T01:29:49.70729Z","shell.execute_reply":"2021-07-26T01:29:51.816929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"view_image(photo_ds,2, 5)","metadata":{"_uuid":"5162fa64-821f-413a-9174-ff98dbb93740","_cell_guid":"59dc609e-b846-4f49-b63b-b7dbd8b7fc5b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:51.819095Z","iopub.execute_input":"2021-07-26T01:29:51.819381Z","iopub.status.idle":"2021-07-26T01:29:52.904066Z","shell.execute_reply.started":"2021-07-26T01:29:51.819355Z","shell.execute_reply":"2021-07-26T01:29:52.903109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"OUTPUT_CHANNELS = 3\n\ndef downsample(filters, size, apply_instancenorm=True):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2D(filters, size, strides=2, padding='same',\n                             kernel_initializer=initializer, use_bias=False))\n\n    if apply_instancenorm:\n        result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    result.add(layers.LeakyReLU())\n\n    return result","metadata":{"_uuid":"7af8f940-62de-4aa9-9394-4e19978b4e94","_cell_guid":"67d39b50-ee43-4e41-904d-597f7d6489b2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:52.905256Z","iopub.execute_input":"2021-07-26T01:29:52.905556Z","iopub.status.idle":"2021-07-26T01:29:52.912145Z","shell.execute_reply.started":"2021-07-26T01:29:52.905526Z","shell.execute_reply":"2021-07-26T01:29:52.911184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def upsample(filters, size, apply_dropout=False):\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    result = keras.Sequential()\n    result.add(layers.Conv2DTranspose(filters, size, strides=2,\n                                      padding='same',\n                                      kernel_initializer=initializer,\n                                      use_bias=False))\n\n    result.add(tfa.layers.InstanceNormalization(gamma_initializer=gamma_init))\n\n    if apply_dropout:\n        result.add(layers.Dropout(0.5))\n\n    result.add(layers.ReLU())\n\n    return result","metadata":{"_uuid":"87370511-1390-484f-a47c-d513bbc05c75","_cell_guid":"629a7cc6-14c1-424d-b2f8-34a2f5428036","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:52.913312Z","iopub.execute_input":"2021-07-26T01:29:52.9136Z","iopub.status.idle":"2021-07-26T01:29:52.927404Z","shell.execute_reply.started":"2021-07-26T01:29:52.913573Z","shell.execute_reply":"2021-07-26T01:29:52.926662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Generator():\n    inputs = layers.Input(shape=[256,256,3])\n\n    # bs = batch size\n    down_stack = [\n        downsample(64, 4, apply_instancenorm=False), # (bs, 128, 128, 64)\n        downsample(128, 4), # (bs, 64, 64, 128)\n        downsample(256, 4), # (bs, 32, 32, 256)\n        downsample(512, 4), # (bs, 16, 16, 512)\n        downsample(512, 4), # (bs, 8, 8, 512)\n        downsample(512, 4), # (bs, 4, 4, 512)\n        downsample(512, 4), # (bs, 2, 2, 512)\n        downsample(512, 4), # (bs, 1, 1, 512)\n    ]\n\n    up_stack = [\n        upsample(512, 4, apply_dropout=True), # (bs, 2, 2, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 4, 4, 1024)\n        upsample(512, 4, apply_dropout=True), # (bs, 8, 8, 1024)\n        upsample(512, 4), # (bs, 16, 16, 1024)\n        upsample(256, 4), # (bs, 32, 32, 512)\n        upsample(128, 4), # (bs, 64, 64, 256)\n        upsample(64, 4), # (bs, 128, 128, 128)\n    ]\n\n    initializer = tf.random_normal_initializer(0., 0.02)\n    last = layers.Conv2DTranspose(OUTPUT_CHANNELS, 4,\n                                  strides=2,\n                                  padding='same',\n                                  kernel_initializer=initializer,\n                                  activation='tanh') # (bs, 256, 256, 3)\n\n    x = inputs\n\n    # Downsampling through the model\n    skips = []\n    for down in down_stack:\n        x = down(x)\n        skips.append(x)\n\n    skips = reversed(skips[:-1])\n\n    # Upsampling and establishing the skip connections\n    for up, skip in zip(up_stack, skips):\n        x = up(x)\n        x = layers.Concatenate()([x, skip])\n\n    x = last(x)\n\n    return keras.Model(inputs=inputs, outputs=x)","metadata":{"_uuid":"4393075b-dec0-4d95-8b15-c8848c20c77c","_cell_guid":"336aeb0b-9a02-48e5-a820-30914a604b1b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:52.928504Z","iopub.execute_input":"2021-07-26T01:29:52.928841Z","iopub.status.idle":"2021-07-26T01:29:52.940367Z","shell.execute_reply.started":"2021-07-26T01:29:52.928812Z","shell.execute_reply":"2021-07-26T01:29:52.939401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def Discriminator():\n    initializer = tf.random_normal_initializer(0., 0.02)\n    gamma_init = keras.initializers.RandomNormal(mean=0.0, stddev=0.02)\n\n    inp = layers.Input(shape=[256, 256, 3], name='input_image')\n\n    x = inp\n\n    down1 = downsample(64, 4, False)(x) # (bs, 128, 128, 64)\n    down2 = downsample(128, 4)(down1) # (bs, 64, 64, 128)\n    down3 = downsample(256, 4)(down2) # (bs, 32, 32, 256)\n\n    zero_pad1 = layers.ZeroPadding2D()(down3) # (bs, 34, 34, 256)\n    conv = layers.Conv2D(512, 4, strides=1,\n                         kernel_initializer=initializer,\n                         use_bias=False)(zero_pad1) # (bs, 31, 31, 512)\n\n    norm1 = tfa.layers.InstanceNormalization(gamma_initializer=gamma_init)(conv)\n\n    leaky_relu = layers.LeakyReLU()(norm1)\n\n    zero_pad2 = layers.ZeroPadding2D()(leaky_relu) # (bs, 33, 33, 512)\n\n    last = layers.Conv2D(1, 4, strides=1,\n                         kernel_initializer=initializer)(zero_pad2) # (bs, 30, 30, 1)\n\n    return tf.keras.Model(inputs=inp, outputs=last)","metadata":{"_uuid":"c52399cf-56ff-4f73-b492-11d15c9a3b0d","_cell_guid":"869bce1f-85a5-4d39-9e33-29ec8b9930f8","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:52.941672Z","iopub.execute_input":"2021-07-26T01:29:52.942182Z","iopub.status.idle":"2021-07-26T01:29:52.955172Z","shell.execute_reply.started":"2021-07-26T01:29:52.942149Z","shell.execute_reply":"2021-07-26T01:29:52.954317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    monet_generator = Generator() # transforms photos to Monet-esque paintings\n    photo_generator = Generator() # transforms Monet paintings to be more like photos\n\n    monet_discriminator = Discriminator() # differentiates real Monet paintings and generated Monet paintings\n    photo_discriminator = Discriminator() # differentiates real photos and generated photos","metadata":{"_uuid":"6b43a3d6-34c9-4b6d-b194-5d922d46de89","_cell_guid":"70abc0d2-1bb7-4e72-9935-0837c27029b8","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:29:52.956449Z","iopub.execute_input":"2021-07-26T01:29:52.95692Z","iopub.status.idle":"2021-07-26T01:30:02.302836Z","shell.execute_reply.started":"2021-07-26T01:29:52.956882Z","shell.execute_reply":"2021-07-26T01:30:02.301956Z"},"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":{"_uuid":"7585483b-cc4e-4957-8e8b-e9ab62d32ed3","_cell_guid":"64d6ae8d-31a8-46ff-a4c5-91b384b37d65","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:02.304023Z","iopub.execute_input":"2021-07-26T01:30:02.304296Z","iopub.status.idle":"2021-07-26T01:30:02.963682Z","shell.execute_reply.started":"2021-07-26T01:30:02.304271Z","shell.execute_reply":"2021-07-26T01:30:02.962732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CycleGan(keras.Model):\n    def __init__(\n        self,\n        monet_generator,\n        photo_generator,\n        monet_discriminator,\n        photo_discriminator,\n        lambda_cycle=10,\n    ):\n        super(CycleGan, self).__init__()\n        self.m_gen = monet_generator\n        self.p_gen = photo_generator\n        self.m_disc = monet_discriminator\n        self.p_disc = photo_discriminator\n        self.lambda_cycle = lambda_cycle\n        \n    def compile(\n        self,\n        m_gen_optimizer,\n        p_gen_optimizer,\n        m_disc_optimizer,\n        p_disc_optimizer,\n        gen_loss_fn,\n        disc_loss_fn,\n        cycle_loss_fn,\n        identity_loss_fn\n    ):\n        super(CycleGan, self).compile()\n        self.m_gen_optimizer = m_gen_optimizer\n        self.p_gen_optimizer = p_gen_optimizer\n        self.m_disc_optimizer = m_disc_optimizer\n        self.p_disc_optimizer = p_disc_optimizer\n        self.gen_loss_fn = gen_loss_fn\n        self.disc_loss_fn = disc_loss_fn\n        self.cycle_loss_fn = cycle_loss_fn\n        self.identity_loss_fn = identity_loss_fn\n        \n    def train_step(self, batch_data):\n        real_monet, real_photo = batch_data\n        \n        with tf.GradientTape(persistent=True) as tape:\n            # photo to monet back to photo\n            fake_monet = self.m_gen(real_photo, training=True)\n            cycled_photo = self.p_gen(fake_monet, training=True)\n\n            # monet to photo back to monet\n            fake_photo = self.p_gen(real_monet, training=True)\n            cycled_monet = self.m_gen(fake_photo, training=True)\n\n            # generating itself\n            same_monet = self.m_gen(real_monet, training=True)\n            same_photo = self.p_gen(real_photo, training=True)\n\n            # discriminator used to check, inputing real images\n            disc_real_monet = self.m_disc(real_monet, training=True)\n            disc_real_photo = self.p_disc(real_photo, training=True)\n\n            # discriminator used to check, inputing fake images\n            disc_fake_monet = self.m_disc(fake_monet, training=True)\n            disc_fake_photo = self.p_disc(fake_photo, training=True)\n\n            # evaluates generator loss\n            monet_gen_loss = self.gen_loss_fn(disc_fake_monet)\n            photo_gen_loss = self.gen_loss_fn(disc_fake_photo)\n\n            # evaluates total cycle consistency loss\n            total_cycle_loss = self.cycle_loss_fn(real_monet, cycled_monet, self.lambda_cycle) + self.cycle_loss_fn(real_photo, cycled_photo, self.lambda_cycle)\n\n            # evaluates total generator loss\n            total_monet_gen_loss = monet_gen_loss + total_cycle_loss + self.identity_loss_fn(real_monet, same_monet, self.lambda_cycle)\n            total_photo_gen_loss = photo_gen_loss + total_cycle_loss + self.identity_loss_fn(real_photo, same_photo, self.lambda_cycle)\n\n            # evaluates discriminator loss\n            monet_disc_loss = self.disc_loss_fn(disc_real_monet, disc_fake_monet)\n            photo_disc_loss = self.disc_loss_fn(disc_real_photo, disc_fake_photo)\n\n        # Calculate the gradients for generator and discriminator\n        monet_generator_gradients = tape.gradient(total_monet_gen_loss,\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":{"_uuid":"25aa4039-49fe-4400-833a-a188df124d9a","_cell_guid":"a3b83b78-e8cb-4ed1-8d3d-9381c6b9d458","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:02.964936Z","iopub.execute_input":"2021-07-26T01:30:02.965227Z","iopub.status.idle":"2021-07-26T01:30:02.98309Z","shell.execute_reply.started":"2021-07-26T01:30:02.965198Z","shell.execute_reply":"2021-07-26T01:30:02.982055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    # Discriminator loss {0: fake, 1: real} (The discriminator loss outputs the average of the real and generated loss)\n    def discriminator_loss(real, generated):\n        real_loss = losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.NONE)(tf.ones_like(real), real)\n\n        generated_loss = losses.BinaryCrossentropy(from_logits=True, reduction=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\n    \n    # Generator loss\n    def generator_loss(generated):\n        return losses.BinaryCrossentropy(from_logits=True, reduction=losses.Reduction.NONE)(tf.ones_like(generated), generated)\n    \n    \n    # Cycle consistency loss (measures if original photo and the twice transformed photo to be similar to one another)\n    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\n\n    # Identity loss (compares the image with its generator (i.e. photo with photo generator))\n    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":{"_uuid":"b5e1898b-f4c3-4d7a-9c60-deb12e99382d","_cell_guid":"85b78b5c-6c66-437a-a575-275990d45469","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:02.984247Z","iopub.execute_input":"2021-07-26T01:30:02.984525Z","iopub.status.idle":"2021-07-26T01:30:03.000124Z","shell.execute_reply.started":"2021-07-26T01:30:02.984499Z","shell.execute_reply":"2021-07-26T01:30:02.999095Z"},"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)","metadata":{"_uuid":"8b255820-cdfa-4850-968e-5c2985a22f45","_cell_guid":"411c6bf7-7a5b-493c-9051-73fa75170192","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:03.00155Z","iopub.execute_input":"2021-07-26T01:30:03.002095Z","iopub.status.idle":"2021-07-26T01:30:03.011698Z","shell.execute_reply.started":"2021-07-26T01:30:03.002055Z","shell.execute_reply":"2021-07-26T01:30:03.010688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    cycle_gan_model = CycleGan(\n        monet_generator, photo_generator, \n        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":{"_uuid":"6459da31-4e8d-4f13-a411-526d4b2ddf60","_cell_guid":"7c905b38-9353-4713-b80c-61a08f6c024d","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:03.013089Z","iopub.execute_input":"2021-07-26T01:30:03.013608Z","iopub.status.idle":"2021-07-26T01:30:03.079848Z","shell.execute_reply.started":"2021-07-26T01:30:03.013561Z","shell.execute_reply":"2021-07-26T01:30:03.078555Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cycle_gan_model.fit(\n    full_dataset,\n    epochs=EPOCHS_NUM,\n    steps_per_epoch=(max(n_monet_samples, n_photo_samples)//BATCH_SIZE),\n)","metadata":{"_uuid":"e5a758af-d98c-420d-96c8-23acafe3c35f","_cell_guid":"477f8bcc-7ec6-469a-9d22-4a8480fd6ef6","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T01:30:03.081438Z","iopub.execute_input":"2021-07-26T01:30:03.081887Z","iopub.status.idle":"2021-07-26T02:26:38.407745Z","shell.execute_reply.started":"2021-07-26T01:30:03.081845Z","shell.execute_reply":"2021-07-26T02:26:38.40632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_generated_samples(ds, model, n_samples):\n    ds_iter = iter(ds)\n    for n_sample in range(n_samples):\n        example_sample = next(ds_iter)\n        generated_sample = model.predict(example_sample)\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":{"_uuid":"fa3112ca-f62e-417c-8fa6-ccd3b274e71f","_cell_guid":"7616d54a-bf22-4b82-8832-e451158d65e0","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T02:26:38.410886Z","iopub.execute_input":"2021-07-26T02:26:38.411269Z","iopub.status.idle":"2021-07-26T02:26:38.42062Z","shell.execute_reply.started":"2021-07-26T02:26:38.411223Z","shell.execute_reply":"2021-07-26T02:26:38.419564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_generated_samples(load_dataset(PHOTO_FILENAMES).batch(1), monet_generator, 7)","metadata":{"_uuid":"cf2d0ccf-ac97-4dc3-b658-882f1405da45","_cell_guid":"9471307d-c598-424c-956f-493767b21224","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T02:26:38.422165Z","iopub.execute_input":"2021-07-26T02:26:38.422565Z","iopub.status.idle":"2021-07-26T02:26:54.754341Z","shell.execute_reply.started":"2021-07-26T02:26:38.42252Z","shell.execute_reply":"2021-07-26T02:26:54.753348Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import PIL\ndef predict_and_save(input_ds, generator_model, output_path):\n    i = 1\n    for img in input_ds:\n        prediction = generator_model(img, training=False)[0].numpy() # make predition\n        prediction = (prediction * 127.5 + 127.5).astype(np.uint8)   # re-scale\n        im = PIL.Image.fromarray(prediction)\n        im.save(f'{output_path}{str(i)}.jpg')\n        i += 1","metadata":{"_uuid":"09d86f58-cf1a-47d3-b098-d9120ba891b4","_cell_guid":"a124644e-2b6d-43bf-9207-a0ef9556fc77","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T02:26:54.756499Z","iopub.execute_input":"2021-07-26T02:26:54.75682Z","iopub.status.idle":"2021-07-26T02:26:54.762325Z","shell.execute_reply.started":"2021-07-26T02:26:54.756791Z","shell.execute_reply":"2021-07-26T02:26:54.761497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nos.makedirs('../images/') # Create folder to save generated images\n\npredict_and_save(load_dataset(PHOTO_FILENAMES).batch(1), monet_generator, '../images/')","metadata":{"_uuid":"ca1275fd-2936-4234-839f-79c9b7543aad","_cell_guid":"ca851db4-8db7-4cb0-8039-e91add2a6952","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T02:26:54.763831Z","iopub.execute_input":"2021-07-26T02:26:54.764215Z","iopub.status.idle":"2021-07-26T03:01:31.914223Z","shell.execute_reply.started":"2021-07-26T02:26:54.764184Z","shell.execute_reply":"2021-07-26T03:01:31.912994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\nshutil.make_archive('/kaggle/working/images/', 'zip', '../images')\n\nprint(f\"Number of generated samples: {len([name for name in os.listdir('../images/') if os.path.isfile(os.path.join('../images/', name))])}\")","metadata":{"_uuid":"c46b5bf4-f6c1-4616-90a2-4163d5229f0d","_cell_guid":"0d594de6-9395-4cd7-a618-b37460eecc21","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2021-07-26T03:01:31.91579Z","iopub.execute_input":"2021-07-26T03:01:31.916051Z","iopub.status.idle":"2021-07-26T03:01:35.716661Z","shell.execute_reply.started":"2021-07-26T03:01:31.916024Z","shell.execute_reply":"2021-07-26T03:01:35.715933Z"},"trusted":true},"execution_count":null,"outputs":[]}]}