{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"sourceType":"competition"},{"sourceId":11080374,"sourceType":"datasetVersion","datasetId":6906018}],"dockerImageVersionId":30919,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Set up environment","metadata":{"papermill":{"duration":0.037375,"end_time":"2020-11-19T21:45:23.192515","exception":false,"start_time":"2020-11-19T21:45:23.15514","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow import keras\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nprint(\"Tensorflow version \" + tf.__version__)\nprint(\"Num GPUs Available: \", len(tf.config.list_physical_devices('GPU')))","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:38:32.040407Z","iopub.execute_input":"2025-03-18T22:38:32.040709Z","iopub.status.idle":"2025-03-18T22:38:44.790431Z","shell.execute_reply.started":"2025-03-18T22:38:32.040688Z","shell.execute_reply":"2025-03-18T22:38:44.789568Z"},"papermill":{"duration":6.890298,"end_time":"2020-11-19T21:45:30.119979","exception":false,"start_time":"2020-11-19T21:45:23.229681","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Detect TPU","metadata":{"papermill":{"duration":0.037444,"end_time":"2020-11-19T21:45:30.195328","exception":false,"start_time":"2020-11-19T21:45:30.157884","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# I couldn't get tensorflow working with the TPU\n\ntry:\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)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:09.111511Z","iopub.execute_input":"2025-03-18T22:39:09.111826Z","iopub.status.idle":"2025-03-18T22:39:09.117099Z","shell.execute_reply.started":"2025-03-18T22:39:09.111804Z","shell.execute_reply":"2025-03-18T22:39:09.116309Z"},"papermill":{"duration":4.150374,"end_time":"2020-11-19T21:45:34.382816","exception":false,"start_time":"2020-11-19T21:45:30.232442","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Set up variables","metadata":{"papermill":{"duration":0.038122,"end_time":"2020-11-19T21:45:34.458722","exception":false,"start_time":"2020-11-19T21:45:34.4206","status":"completed"},"tags":[]}},{"cell_type":"code","source":"AUTOTUNE = tf.data.AUTOTUNE\nGCS_PATH = '/kaggle/input/cassava-leaf-disease-classification'\nBATCH_SIZE = 16\nIMAGE_SIZE = [512, 512]\nCLASSES = ['0', '1', '2', '3', '4']\nEPOCHS = 10","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:13.694445Z","iopub.execute_input":"2025-03-18T22:39:13.694762Z","iopub.status.idle":"2025-03-18T22:39:13.698656Z","shell.execute_reply.started":"2025-03-18T22:39:13.694739Z","shell.execute_reply":"2025-03-18T22:39:13.697845Z"},"papermill":{"duration":145.219568,"end_time":"2020-11-19T21:47:59.715925","exception":false,"start_time":"2020-11-19T21:45:34.496357","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Load the data","metadata":{"papermill":{"duration":0.037843,"end_time":"2020-11-19T21:47:59.792061","exception":false,"start_time":"2020-11-19T21:47:59.754218","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:17.044998Z","iopub.execute_input":"2025-03-18T22:39:17.045300Z","iopub.status.idle":"2025-03-18T22:39:17.049365Z","shell.execute_reply.started":"2025-03-18T22:39:17.045275Z","shell.execute_reply":"2025-03-18T22:39:17.048672Z"},"papermill":{"duration":0.04859,"end_time":"2020-11-19T21:47:59.955731","exception":false,"start_time":"2020-11-19T21:47:59.907141","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def read_tfrecord(example, labeled):\n    tfrecord_format = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"target\": tf.io.FixedLenFeature([], tf.int64)\n    } if labeled else {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"image_name\": tf.io.FixedLenFeature([], tf.string)\n    }\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example['image'])\n    if labeled:\n        label = tf.cast(example['target'], tf.int32)\n        return image, label\n    idnum = example['image_name']\n    return image, idnum","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:21.461829Z","iopub.execute_input":"2025-03-18T22:39:21.462096Z","iopub.status.idle":"2025-03-18T22:39:21.467177Z","shell.execute_reply.started":"2025-03-18T22:39:21.462077Z","shell.execute_reply":"2025-03-18T22:39:21.466059Z"},"papermill":{"duration":0.052475,"end_time":"2020-11-19T21:48:00.127039","exception":false,"start_time":"2020-11-19T21:48:00.074564","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTOTUNE) # 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(partial(read_tfrecord, labeled=labeled), num_parallel_calls=AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:25.951145Z","iopub.execute_input":"2025-03-18T22:39:25.951519Z","iopub.status.idle":"2025-03-18T22:39:25.956100Z","shell.execute_reply.started":"2025-03-18T22:39:25.951489Z","shell.execute_reply":"2025-03-18T22:39:25.955072Z"},"papermill":{"duration":0.073623,"end_time":"2020-11-19T21:48:00.328703","exception":false,"start_time":"2020-11-19T21:48:00.25508","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"TRAINING_FILENAMES, VALID_FILENAMES = train_test_split(\n    tf.io.gfile.glob(GCS_PATH + '/train_tfrecords/ld_train*.tfrec'),\n    test_size=0.35, random_state=5\n)\n\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test_tfrecords/ld_test*.tfrec')","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:29.717145Z","iopub.execute_input":"2025-03-18T22:39:29.717579Z","iopub.status.idle":"2025-03-18T22:39:29.735671Z","shell.execute_reply.started":"2025-03-18T22:39:29.717534Z","shell.execute_reply":"2025-03-18T22:39:29.734851Z"},"papermill":{"duration":0.225941,"end_time":"2020-11-19T21:48:00.687385","exception":false,"start_time":"2020-11-19T21:48:00.461444","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO) statement in the following function 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    return image, label","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:32.589625Z","iopub.execute_input":"2025-03-18T22:39:32.590044Z","iopub.status.idle":"2025-03-18T22:39:32.594756Z","shell.execute_reply.started":"2025-03-18T22:39:32.590010Z","shell.execute_reply":"2025-03-18T22:39:32.593674Z"},"papermill":{"duration":0.047715,"end_time":"2020-11-19T21:48:00.851918","exception":false,"start_time":"2020-11-19T21:48:00.804203","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Define data loading methods","metadata":{"papermill":{"duration":0.038742,"end_time":"2020-11-19T21:48:00.930185","exception":false,"start_time":"2020-11-19T21:48:00.891443","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)  \n    dataset = dataset.map(data_augment, num_parallel_calls=AUTOTUNE)  \n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:35.813078Z","iopub.execute_input":"2025-03-18T22:39:35.813397Z","iopub.status.idle":"2025-03-18T22:39:35.818042Z","shell.execute_reply.started":"2025-03-18T22:39:35.813371Z","shell.execute_reply":"2025-03-18T22:39:35.817059Z"},"papermill":{"duration":0.052326,"end_time":"2020-11-19T21:48:01.021791","exception":false,"start_time":"2020-11-19T21:48:00.969465","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALID_FILENAMES, labeled=True, ordered=ordered) \n    dataset = dataset.batch(BATCH_SIZE)\n    # dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:39.269026Z","iopub.execute_input":"2025-03-18T22:39:39.269332Z","iopub.status.idle":"2025-03-18T22:39:39.273628Z","shell.execute_reply.started":"2025-03-18T22:39:39.269310Z","shell.execute_reply":"2025-03-18T22:39:39.272711Z"},"papermill":{"duration":0.049787,"end_time":"2020-11-19T21:48:01.112145","exception":false,"start_time":"2020-11-19T21:48:01.062358","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:41.861113Z","iopub.execute_input":"2025-03-18T22:39:41.861427Z","iopub.status.idle":"2025-03-18T22:39:41.866010Z","shell.execute_reply.started":"2025-03-18T22:39:41.861402Z","shell.execute_reply":"2025-03-18T22:39:41.864996Z"},"papermill":{"duration":0.050395,"end_time":"2020-11-19T21:48:01.207665","exception":false,"start_time":"2020-11-19T21:48:01.15727","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"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)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:43.927575Z","iopub.execute_input":"2025-03-18T22:39:43.927858Z","iopub.status.idle":"2025-03-18T22:39:43.931925Z","shell.execute_reply.started":"2025-03-18T22:39:43.927838Z","shell.execute_reply":"2025-03-18T22:39:43.930981Z"},"papermill":{"duration":0.05422,"end_time":"2020-11-19T21:48:01.304611","exception":false,"start_time":"2020-11-19T21:48:01.250391","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"NUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALID_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} (unlabeled) test images'.format(\n    NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:45.711247Z","iopub.execute_input":"2025-03-18T22:39:45.711566Z","iopub.status.idle":"2025-03-18T22:39:45.717935Z","shell.execute_reply.started":"2025-03-18T22:39:45.711536Z","shell.execute_reply":"2025-03-18T22:39:45.717113Z"},"papermill":{"duration":0.051209,"end_time":"2020-11-19T21:48:01.396198","exception":false,"start_time":"2020-11-19T21:48:01.344989","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Brief exploratory data analysis (EDA)","metadata":{"papermill":{"duration":0.041086,"end_time":"2020-11-19T21:48:01.478205","exception":false,"start_time":"2020-11-19T21:48:01.437119","status":"completed"},"tags":[]}},{"cell_type":"code","source":"print(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nprint(\"Validation data shapes:\")\nfor image, label in get_validation_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset().take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:39:48.790210Z","iopub.execute_input":"2025-03-18T22:39:48.790640Z","iopub.status.idle":"2025-03-18T22:40:00.105053Z","shell.execute_reply.started":"2025-03-18T22:39:48.790603Z","shell.execute_reply":"2025-03-18T22:40:00.104266Z"},"papermill":{"duration":17.07767,"end_time":"2020-11-19T21:48:18.597304","exception":false,"start_time":"2020-11-19T21:48:01.519634","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\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], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_plant(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):\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        subplot = display_one_plant(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()","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:40:58.341592Z","iopub.execute_input":"2025-03-18T22:40:58.341888Z","iopub.status.idle":"2025-03-18T22:40:58.354690Z","shell.execute_reply.started":"2025-03-18T22:40:58.341867Z","shell.execute_reply":"2025-03-18T22:40:58.353793Z"},"papermill":{"duration":0.077342,"end_time":"2020-11-19T21:48:18.808133","exception":false,"start_time":"2020-11-19T21:48:18.730791","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load our training dataset for EDA\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:01.861623Z","iopub.execute_input":"2025-03-18T22:41:01.861945Z","iopub.status.idle":"2025-03-18T22:41:01.962524Z","shell.execute_reply.started":"2025-03-18T22:41:01.861922Z","shell.execute_reply":"2025-03-18T22:41:01.961657Z"},"papermill":{"duration":0.104176,"end_time":"2020-11-19T21:48:18.957003","exception":false,"start_time":"2020-11-19T21:48:18.852827","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run this cell again for another randomized set of training images\ndisplay_batch_of_images(next(train_batch))","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:03.382072Z","iopub.execute_input":"2025-03-18T22:41:03.382361Z","iopub.status.idle":"2025-03-18T22:41:11.546986Z","shell.execute_reply.started":"2025-03-18T22:41:03.382338Z","shell.execute_reply":"2025-03-18T22:41:11.545973Z"},"papermill":{"duration":3.371477,"end_time":"2020-11-19T21:48:22.374778","exception":false,"start_time":"2020-11-19T21:48:19.003301","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load our validation dataset for EDA\nvalidation_dataset = get_validation_dataset()\nvalidation_dataset = validation_dataset.unbatch().batch(20)\nvalid_batch = iter(validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:21.194730Z","iopub.execute_input":"2025-03-18T22:41:21.195051Z","iopub.status.idle":"2025-03-18T22:41:21.254248Z","shell.execute_reply.started":"2025-03-18T22:41:21.195023Z","shell.execute_reply":"2025-03-18T22:41:21.253347Z"},"papermill":{"duration":0.136485,"end_time":"2020-11-19T21:48:22.769878","exception":false,"start_time":"2020-11-19T21:48:22.633393","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# run this cell again for another randomized set of training images\ndisplay_batch_of_images(next(valid_batch))","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:24.567291Z","iopub.execute_input":"2025-03-18T22:41:24.567640Z","iopub.status.idle":"2025-03-18T22:41:27.550444Z","shell.execute_reply.started":"2025-03-18T22:41:24.567613Z","shell.execute_reply":"2025-03-18T22:41:27.549552Z"},"papermill":{"duration":3.155802,"end_time":"2020-11-19T21:48:26.010993","exception":false,"start_time":"2020-11-19T21:48:22.855191","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# load our test dataset for EDA\ntesting_dataset = get_test_dataset()\ntesting_dataset = testing_dataset.unbatch().batch(20)\ntest_batch = iter(testing_dataset)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:30.350011Z","iopub.execute_input":"2025-03-18T22:41:30.350343Z","iopub.status.idle":"2025-03-18T22:41:30.405897Z","shell.execute_reply.started":"2025-03-18T22:41:30.350314Z","shell.execute_reply":"2025-03-18T22:41:30.405048Z"},"papermill":{"duration":0.232531,"end_time":"2020-11-19T21:48:26.411209","exception":false,"start_time":"2020-11-19T21:48:26.178678","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# we only have one test image\ndisplay_batch_of_images(next(test_batch))","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:32.365866Z","iopub.execute_input":"2025-03-18T22:41:32.366178Z","iopub.status.idle":"2025-03-18T22:41:33.707499Z","shell.execute_reply.started":"2025-03-18T22:41:32.366153Z","shell.execute_reply":"2025-03-18T22:41:33.706283Z"},"papermill":{"duration":1.333241,"end_time":"2020-11-19T21:48:27.900651","exception":false,"start_time":"2020-11-19T21:48:26.56741","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Building the model","metadata":{"papermill":{"duration":0.230199,"end_time":"2020-11-19T21:48:28.353794","exception":false,"start_time":"2020-11-19T21:48:28.123595","status":"completed"},"tags":[]}},{"cell_type":"code","source":"lr_scheduler = keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate=1e-5, \n    decay_steps=10000, \n    decay_rate=0.9)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:39.710466Z","iopub.execute_input":"2025-03-18T22:41:39.710845Z","iopub.status.idle":"2025-03-18T22:41:39.768268Z","shell.execute_reply.started":"2025-03-18T22:41:39.710818Z","shell.execute_reply":"2025-03-18T22:41:39.767676Z"},"papermill":{"duration":0.248904,"end_time":"2020-11-19T21:48:28.83328","exception":false,"start_time":"2020-11-19T21:48:28.584376","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Building the model","metadata":{"papermill":{"duration":0.22538,"end_time":"2020-11-19T21:48:29.285377","exception":false,"start_time":"2020-11-19T21:48:29.059997","status":"completed"},"tags":[]}},{"cell_type":"code","source":"with strategy.scope():       \n    img_adjust_layer = tf.keras.layers.Lambda(tf.keras.applications.resnet50.preprocess_input, input_shape=[*IMAGE_SIZE, 3])\n    \n    # base_model = tf.keras.applications.ResNet50(weights='imagenet', include_top=False)\n    base_model = tf.keras.applications.ResNet50(weights=None, include_top=False)\n    base_model.load_weights('/kaggle/input/resnet-50-weights/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5')\n    base_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        tf.keras.layers.BatchNormalization(),\n        img_adjust_layer,\n        base_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(8, activation='relu'),\n        #tf.keras.layers.BatchNormalization(renorm=True),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')  \n    ])\n    \n    model.compile(\n        optimizer=tf.keras.optimizers.Adam(learning_rate=lr_scheduler, epsilon=0.001),\n        loss='sparse_categorical_crossentropy',  \n        metrics=['sparse_categorical_accuracy'])","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:47.018002Z","iopub.execute_input":"2025-03-18T22:41:47.018283Z","iopub.status.idle":"2025-03-18T22:41:50.040099Z","shell.execute_reply.started":"2025-03-18T22:41:47.018260Z","shell.execute_reply":"2025-03-18T22:41:50.039384Z"},"papermill":{"duration":19.661572,"end_time":"2020-11-19T21:48:49.158413","exception":false,"start_time":"2020-11-19T21:48:29.496841","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Train the model","metadata":{"papermill":{"duration":0.174404,"end_time":"2020-11-19T21:48:49.513099","exception":false,"start_time":"2020-11-19T21:48:49.338695","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# load data\ntrain_dataset = get_training_dataset()\nvalid_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:41:58.823182Z","iopub.execute_input":"2025-03-18T22:41:58.823565Z","iopub.status.idle":"2025-03-18T22:41:58.897723Z","shell.execute_reply.started":"2025-03-18T22:41:58.823535Z","shell.execute_reply":"2025-03-18T22:41:58.897061Z"},"papermill":{"duration":0.249051,"end_time":"2020-11-19T21:48:49.936435","exception":false,"start_time":"2020-11-19T21:48:49.687384","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE\n\nhistory = model.fit(train_dataset, \n                    steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=EPOCHS,\n                    validation_data=valid_dataset,\n                    validation_steps=VALID_STEPS)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T22:42:01.601566Z","iopub.execute_input":"2025-03-18T22:42:01.601856Z","iopub.status.idle":"2025-03-18T23:16:14.545759Z","shell.execute_reply.started":"2025-03-18T22:42:01.601836Z","shell.execute_reply":"2025-03-18T23:16:14.502915Z"},"papermill":{"duration":956.681695,"end_time":"2020-11-19T22:04:46.795744","exception":false,"start_time":"2020-11-19T21:48:50.114049","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:17:23.740209Z","iopub.execute_input":"2025-03-18T23:17:23.740521Z","iopub.status.idle":"2025-03-18T23:17:23.763388Z","shell.execute_reply.started":"2025-03-18T23:17:23.740462Z","shell.execute_reply":"2025-03-18T23:17:23.762674Z"},"papermill":{"duration":1.344562,"end_time":"2020-11-19T22:04:51.988755","exception":false,"start_time":"2020-11-19T22:04:50.644193","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Evaluating our model","metadata":{"papermill":{"duration":1.245239,"end_time":"2020-11-19T22:04:54.493139","exception":false,"start_time":"2020-11-19T22:04:53.2479","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# print out variables available to us\nprint(history.history.keys())","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:17:26.954635Z","iopub.execute_input":"2025-03-18T23:17:26.954918Z","iopub.status.idle":"2025-03-18T23:17:26.959243Z","shell.execute_reply.started":"2025-03-18T23:17:26.954899Z","shell.execute_reply":"2025-03-18T23:17:26.958438Z"},"papermill":{"duration":1.31245,"end_time":"2020-11-19T22:04:57.054025","exception":false,"start_time":"2020-11-19T22:04:55.741575","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# create learning curves to evaluate model performance\nhistory_frame = pd.DataFrame(history.history)\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:17:42.524300Z","iopub.execute_input":"2025-03-18T23:17:42.524631Z","iopub.status.idle":"2025-03-18T23:17:43.041601Z","shell.execute_reply.started":"2025-03-18T23:17:42.524595Z","shell.execute_reply":"2025-03-18T23:17:43.040895Z"},"papermill":{"duration":1.671861,"end_time":"2020-11-19T22:04:59.983272","exception":false,"start_time":"2020-11-19T22:04:58.311411","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Making predictions","metadata":{"papermill":{"duration":1.326243,"end_time":"2020-11-19T22:05:02.628032","exception":false,"start_time":"2020-11-19T22:05:01.301789","status":"completed"},"tags":[]}},{"cell_type":"code","source":"# this code will convert our test image data to a float32 \ndef to_float32(image, label):\n    return tf.cast(image, tf.float32), label","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:17:53.713711Z","iopub.execute_input":"2025-03-18T23:17:53.714020Z","iopub.status.idle":"2025-03-18T23:17:53.717845Z","shell.execute_reply.started":"2025-03-18T23:17:53.713993Z","shell.execute_reply":"2025-03-18T23:17:53.717065Z"},"papermill":{"duration":1.270192,"end_time":"2020-11-19T22:05:05.187694","exception":false,"start_time":"2020-11-19T22:05:03.917502","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) \ntest_ds = test_ds.map(to_float32)\n\nprint('Computing predictions...')\ntest_images_ds = testing_dataset\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:17:56.826657Z","iopub.execute_input":"2025-03-18T23:17:56.826932Z","iopub.status.idle":"2025-03-18T23:18:01.569569Z","shell.execute_reply.started":"2025-03-18T23:17:56.826913Z","shell.execute_reply":"2025-03-18T23:18:01.568582Z"},"papermill":{"duration":15.776858,"end_time":"2020-11-19T22:05:22.235661","exception":false,"start_time":"2020-11-19T22:05:06.458803","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Creating a submission file","metadata":{"papermill":{"duration":1.271799,"end_time":"2020-11-19T22:05:24.759257","exception":false,"start_time":"2020-11-19T22:05:23.487458","status":"completed"},"tags":[]}},{"cell_type":"code","source":"print('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='image_id,label', comments='')\n!head submission.csv","metadata":{"execution":{"iopub.status.busy":"2025-03-18T23:18:10.604357Z","iopub.execute_input":"2025-03-18T23:18:10.604700Z","iopub.status.idle":"2025-03-18T23:18:11.572142Z","shell.execute_reply.started":"2025-03-18T23:18:10.604674Z","shell.execute_reply":"2025-03-18T23:18:11.570984Z"},"papermill":{"duration":2.185537,"end_time":"2020-11-19T22:05:28.241723","exception":false,"start_time":"2020-11-19T22:05:26.056186","status":"completed"},"tags":[],"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Be aware that because this is a code competition with a hidden test set, internet and TPUs cannot be enabled on your submission notebook. Therefore TPUs will only be available for training models. For a walk-through on how to train on TPUs and run inference/submit on GPUs, see our [TPU Docs](https://www.kaggle.com/docs/tpu#tpu6).","metadata":{"papermill":{"duration":1.255302,"end_time":"2020-11-19T22:05:30.746339","exception":false,"start_time":"2020-11-19T22:05:29.491037","status":"completed"},"tags":[]}}]}