{"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":"# A Simple TF 2.2 notebook\n\nThis is intended as a simple, short introduction to the operations competitors will need to perform with TPUs.","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\n#from tensorflow.keras.applications import DenseNet201\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2022-05-13T05:34:12.176306Z","iopub.execute_input":"2022-05-13T05:34:12.176644Z","iopub.status.idle":"2022-05-13T05:34:12.182161Z","shell.execute_reply.started":"2022-05-13T05:34:12.176609Z","shell.execute_reply":"2022-05-13T05:34:12.181433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detect my accelerator","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('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() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:15.665823Z","iopub.execute_input":"2022-05-13T05:34:15.666350Z","iopub.status.idle":"2022-05-13T05:34:21.576870Z","shell.execute_reply.started":"2022-05-13T05:34:15.666317Z","shell.execute_reply":"2022-05-13T05:34:21.575781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get my data path","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:24.863996Z","iopub.execute_input":"2022-05-13T05:34:24.864278Z","iopub.status.idle":"2022-05-13T05:34:25.283483Z","shell.execute_reply.started":"2022-05-13T05:34:24.864249Z","shell.execute_reply":"2022-05-13T05:34:25.282630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 10\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:28.064386Z","iopub.execute_input":"2022-05-13T05:34:28.064704Z","iopub.status.idle":"2022-05-13T05:34:28.070170Z","shell.execute_reply.started":"2022-05-13T05:34:28.064672Z","shell.execute_reply":"2022-05-13T05:34:28.069269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:32.036668Z","iopub.execute_input":"2022-05-13T05:34:32.036987Z","iopub.status.idle":"2022-05-13T05:34:32.407270Z","shell.execute_reply.started":"2022-05-13T05:34:32.036958Z","shell.execute_reply":"2022-05-13T05:34:32.406363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"SEED = 2020\n\ndef random_blockout(img, sl=0.1, sh=0.2, rl=0.4):\n    p=random.random()\n    if p>=0.25:\n        w, h, c = IMAGE_SIZE[0], IMAGE_SIZE[1], 3\n        origin_area = tf.cast(h*w, tf.float32)\n\n        e_size_l = tf.cast(tf.round(tf.sqrt(origin_area * sl * rl)), tf.int32)\n        e_size_h = tf.cast(tf.round(tf.sqrt(origin_area * sh / rl)), tf.int32)\n\n        e_height_h = tf.minimum(e_size_h, h)\n        e_width_h = tf.minimum(e_size_h, w)\n\n        erase_height = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_height_h, dtype=tf.int32)\n        erase_width = tf.random.uniform(shape=[], minval=e_size_l, maxval=e_width_h, dtype=tf.int32)\n\n        erase_area = tf.zeros(shape=[erase_height, erase_width, c])\n        erase_area = tf.cast(erase_area, tf.uint8)\n\n        pad_h = h - erase_height\n        pad_top = tf.random.uniform(shape=[], minval=0, maxval=pad_h, dtype=tf.int32)\n        pad_bottom = pad_h - pad_top\n\n        pad_w = w - erase_width\n        pad_left = tf.random.uniform(shape=[], minval=0, maxval=pad_w, dtype=tf.int32)\n        pad_right = pad_w - pad_left\n\n        erase_mask = tf.pad([erase_area], [[0,0],[pad_top, pad_bottom], [pad_left, pad_right], [0,0]], constant_values=1)\n        erase_mask = tf.squeeze(erase_mask, axis=0)\n        erased_img = tf.multiply(tf.cast(img,tf.float32), tf.cast(erase_mask, tf.float32))\n\n        return tf.cast(erased_img, img.dtype)\n    else:\n        return tf.cast(img, img.dtype)\n\n    \ndef data_augment_v2(image, label):\n    # Thanks to the dataset.prefetch(AUTO) statement in the next function (below), this happens essentially for free on TPU. \n    # Data pipeline code is executed on the \"CPU\" part of the TPU while the TPU itself is computing gradients.\n    \n    flag = random.randint(1,3)\n    coef_1 = random.randint(70, 90) * 0.01\n    coef_2 = random.randint(70, 90) * 0.01\n    \n    if flag == 1:\n        image = tf.image.random_flip_left_right(image, seed=SEED)\n    elif flag == 2:\n        image = tf.image.random_flip_up_down(image, seed=SEED)\n    else:\n        image = tf.image.random_crop(image, [int(IMAGE_SIZE[0]*coef_1), int(IMAGE_SIZE[0]*coef_2), 3],seed=SEED)\n        \n    image = random_blockout(image)\n    \n    return image, label ","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:35.049655Z","iopub.execute_input":"2022-05-13T05:34:35.050001Z","iopub.status.idle":"2022-05-13T05:34:35.069003Z","shell.execute_reply.started":"2022-05-13T05:34:35.049971Z","shell.execute_reply":"2022-05-13T05:34:35.067989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow_addons as tfa\n\n# Randomly make some changes to the images and return the new images and labels\ndef data_augment_v3(image, label):\n        \n    # Set seed for data augmentation\n    seed = 100\n    \n    # Randomly resize and then crop images\n    image = tf.image.resize(image, [720, 720])\n    image = tf.image.random_crop(image, [512, 512, 3], seed = seed)\n\n    # Randomly reset brightness of images\n    image = tf.image.random_brightness(image, 0.6, seed = seed)\n    \n    # Randomly reset saturation of images\n    image = tf.image.random_saturation(image, 3, 5, seed = seed)\n        \n    # Randomly reset contrast of images\n    image = tf.image.random_contrast(image, 0.3, 0.5, seed = seed)\n\n    # Randomly reset hue of images, but this will make the colors really weird, which we think will not happen\n    # in common photography\n    # image = tf.image.random_hue(image, 0.5, seed = seed)\n    \n    # Blur images\n    image = tfa.image.mean_filter2d(image, filter_shape = 10)\n    \n    # Randomly flip images\n    image = tf.image.random_flip_left_right(image, seed = seed)\n    image = tf.image.random_flip_up_down(image, seed = seed)\n    \n    # Fail to rotate and transform images due to some bug in TensorFlow\n    # angle = random.randint(0, 180)\n    # image = tfa.image.rotate(image, tf.constant(np.pi * angle / 180))\n    # image = tfa.image.transform(image, [1.0, 1.0, -250, 0.0, 1.0, 0.0, 0.0, 0.0])\n    \n    return image, label","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:39.043590Z","iopub.execute_input":"2022-05-13T05:34:39.044335Z","iopub.status.idle":"2022-05-13T05:34:39.189379Z","shell.execute_reply.started":"2022-05-13T05:34:39.044291Z","shell.execute_reply":"2022-05-13T05:34:39.188529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy.num_replicas_in_sync","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:44.915718Z","iopub.execute_input":"2022-05-13T05:34:44.916018Z","iopub.status.idle":"2022-05-13T05:34:44.925116Z","shell.execute_reply.started":"2022-05-13T05:34:44.915986Z","shell.execute_reply":"2022-05-13T05:34:44.924250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"16 * strategy.num_replicas_in_sync","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:45.659348Z","iopub.execute_input":"2022-05-13T05:34:45.659676Z","iopub.status.idle":"2022-05-13T05:34:45.665761Z","shell.execute_reply.started":"2022-05-13T05:34:45.659645Z","shell.execute_reply":"2022-05-13T05:34:45.664882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync #See Note 3.1 above 😀\n\nds_train = training_dataset\nds_valid = validation_dataset\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:48.887483Z","iopub.execute_input":"2022-05-13T05:34:48.887881Z","iopub.status.idle":"2022-05-13T05:34:49.056636Z","shell.execute_reply.started":"2022-05-13T05:34:48.887844Z","shell.execute_reply":"2022-05-13T05:34:49.055715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape) #See Note 3.1 above 😀\nprint(\"Training data label examples:\", label.numpy())","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:34:53.320481Z","iopub.execute_input":"2022-05-13T05:34:53.320785Z","iopub.status.idle":"2022-05-13T05:34:57.981987Z","shell.execute_reply.started":"2022-05-13T05:34:53.320750Z","shell.execute_reply":"2022-05-13T05:34:57.979784Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape) #See Note 3.1 above 😀\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:35:41.134133Z","iopub.execute_input":"2022-05-13T05:35:41.134955Z","iopub.status.idle":"2022-05-13T05:35:42.584868Z","shell.execute_reply.started":"2022-05-13T05:35:41.134910Z","shell.execute_reply":"2022-05-13T05:35:42.584040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case,these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n        # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], \n                                'OK' if correct else 'NO', \n                                u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None, display_mismatches_only=False):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = '' if label is None else CLASSES[label]\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        if display_mismatches_only:\n            if predictions[i] != label:\n                subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n        else:        \n            subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\n\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])\n\ndef display_training_curves_v2(training, validation, learning_rate_list, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title, color='b')\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.', 'learning rate'])        \n    \n    ax2 = ax.twinx()\n    ax2.plot(learning_rate_list, 'g-')\n    ax2.set_ylabel('learning rate', color='g')","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:35:46.739701Z","iopub.execute_input":"2022-05-13T05:35:46.740132Z","iopub.status.idle":"2022-05-13T05:35:46.765474Z","shell.execute_reply.started":"2022-05-13T05:35:46.740102Z","shell.execute_reply":"2022-05-13T05:35:46.764544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape) #See Note 3.1 above 😀\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:36:03.156603Z","iopub.execute_input":"2022-05-13T05:36:03.156973Z","iopub.status.idle":"2022-05-13T05:36:03.667858Z","shell.execute_reply.started":"2022-05-13T05:36:03.156938Z","shell.execute_reply":"2022-05-13T05:36:03.666925Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\nds_iter = iter(ds_train.unbatch().batch(20))\n\none_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:40:21.026154Z","iopub.execute_input":"2022-05-13T05:40:21.026993Z","iopub.status.idle":"2022-05-13T05:40:24.836877Z","shell.execute_reply.started":"2022-05-13T05:40:21.026951Z","shell.execute_reply":"2022-05-13T05:40:24.835978Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO) statement in the next function (below), this happens essentially for free on TPU. \n    # Data pipeline code is executed on the \"CPU\" part of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   ","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:40:31.454935Z","iopub.execute_input":"2022-05-13T05:40:31.455214Z","iopub.status.idle":"2022-05-13T05:40:31.459849Z","shell.execute_reply.started":"2022-05-13T05:40:31.455185Z","shell.execute_reply":"2022-05-13T05:40:31.459005Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row = 3\ncol = 4\nall_elements = get_training_dataset().unbatch()\none_element = tf.data.Dataset.from_tensors(next(iter(all_elements)))\n# Map the images to the data augmentation function for image processing\naugmented_element = one_element.repeat().map(data_augment).batch(row * col)\n\nfor (img, label) in augmented_element:\n    plt.figure(figsize = (15, int(15 * row / col)))\n    for j in range(row * col):\n        plt.subplot(row, col, j + 1)\n        plt.axis('off')\n        plt.imshow(img[j, ])\n    plt.show()\n    break","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:40:40.085246Z","iopub.execute_input":"2022-05-13T05:40:40.085583Z","iopub.status.idle":"2022-05-13T05:40:43.114118Z","shell.execute_reply.started":"2022-05-13T05:40:40.085553Z","shell.execute_reply":"2022-05-13T05:40:43.113174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import random\naugmented_element = one_element.repeat().map(data_augment_v2).batch(row * col)\n\nfor (img, label) in augmented_element:\n    plt.figure(figsize = (15, int(15 * row / col)))\n    for j in range(row * col):\n        plt.subplot(row, col, j + 1)\n        plt.axis('off')\n        plt.imshow(img[j, ])\n    plt.show()\n    break","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:41:21.955138Z","iopub.execute_input":"2022-05-13T05:41:21.955474Z","iopub.status.idle":"2022-05-13T05:41:24.310056Z","shell.execute_reply.started":"2022-05-13T05:41:21.955441Z","shell.execute_reply":"2022-05-13T05:41:24.309232Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"augmented_element = one_element.repeat().map(data_augment_v3).batch(row * col)\n\nfor (img, label) in augmented_element:\n    plt.figure(figsize = (15, int(15 * row / col)))\n    for j in range(row * col):\n        plt.subplot(row, col, j + 1)\n        plt.axis('off')\n        plt.imshow(img[j, ])\n    plt.show()\n    break","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:41:39.882878Z","iopub.execute_input":"2022-05-13T05:41:39.883151Z","iopub.status.idle":"2022-05-13T05:41:48.295133Z","shell.execute_reply.started":"2022-05-13T05:41:39.883123Z","shell.execute_reply":"2022-05-13T05:41:48.294437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"[*IMAGE_SIZE, 3]","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:42:10.048813Z","iopub.execute_input":"2022-05-13T05:42:10.049371Z","iopub.status.idle":"2022-05-13T05:42:10.055553Z","shell.execute_reply.started":"2022-05-13T05:42:10.049334Z","shell.execute_reply":"2022-05-13T05:42:10.054544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''data_augmentation = tf.keras.Sequential(\n  [\n    tf.keras.layers.experimental.preprocessing.RandomFlip(\"horizontal\", \n                                                 input_shape= [*IMAGE_SIZE, 3]),\n    tf.keras.layers.experimental.preprocessing.RandomRotation(0.1),\n    tf.keras.layers.experimental.preprocessing.RandomZoom(0.1),\n  ]\n)'''","metadata":{"execution":{"iopub.status.busy":"2022-05-13T06:08:11.494337Z","iopub.execute_input":"2022-05-13T06:08:11.494916Z","iopub.status.idle":"2022-05-13T06:08:11.633078Z","shell.execute_reply.started":"2022-05-13T06:08:11.494878Z","shell.execute_reply":"2022-05-13T06:08:11.632263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{}},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.InceptionV3(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,  \n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset,\n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=30, \n          validation_data=validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-05-13T06:23:46.231587Z","iopub.execute_input":"2022-05-13T06:23:46.232154Z","iopub.status.idle":"2022-05-13T06:30:41.073688Z","shell.execute_reply.started":"2022-05-13T06:23:46.232116Z","shell.execute_reply":"2022-05-13T06:30:41.072669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2022-05-13T06:31:18.782483Z","iopub.execute_input":"2022-05-13T06:31:18.782778Z","iopub.status.idle":"2022-05-13T06:31:54.609804Z","shell.execute_reply.started":"2022-05-13T06:31:18.782749Z","shell.execute_reply":"2022-05-13T06:31:54.608773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''with strategy.scope():    \n    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = True # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.Conv2D(64, kernel_size = 3, kernel_initializer='he_normal', strides=1, activation='relu',padding='same'),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.MaxPooling2D((2, 2), padding='same'),\n        tf.keras.layers.Conv2D(64, kernel_size = 3,kernel_initializer='he_normal', activation='relu',padding='same'),\n        \n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n\nhistorical = model.fit(training_dataset, \n          steps_per_epoch=STEPS_PER_EPOCH, \n          epochs=EPOCHS, \n          validation_data=validation_dataset)'''","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']\n\n\n\nfig, axs = plt.subplots(3, 3, sharex=True, sharey=True, figsize=(8,8))\n\nindex = 0\nfor i in range(3):\n    for j in range(3):\n        sample = training_dataset\n        for img, label in training_dataset.take(1):\n            axs[i, j].imshow(img[index])\n            axs[i, j].set_title(f\"Label: {CLASSES[label[index]]}\")\n        index += 1\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-13T05:37:53.543563Z","iopub.execute_input":"2022-05-13T05:37:53.543855Z","iopub.status.idle":"2022-05-13T05:38:09.208467Z","shell.execute_reply.started":"2022-05-13T05:37:53.543826Z","shell.execute_reply":"2022-05-13T05:38:09.207389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_dataset.shape","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}