{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","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"},"papermill":{"default_parameters":{},"duration":4520.416664,"end_time":"2023-09-01T23:56:52.849556","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2023-09-01T22:41:32.432892","version":"2.3.4"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# ☀️ Imports and Setup","metadata":{"papermill":{"duration":0.012986,"end_time":"2023-09-01T22:41:35.270597","exception":false,"start_time":"2023-09-01T22:41:35.257611","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"import re\nimport os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tempfile\nimport matplotlib as mlp\nimport matplotlib.pyplot as plt\nimport sklearn\nimport math\n\nfrom functools import partial\nfrom kaggle_datasets import KaggleDatasets\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow import keras\nfrom keras import layers, callbacks\nfrom keras.losses import BinaryCrossentropy\nfrom keras.callbacks import ModelCheckpoint,EarlyStopping\nfrom keras import backend as K\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)\n    \nprint(tf.__version__)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":52.762317,"end_time":"2023-09-01T22:42:28.044248","exception":false,"start_time":"2023-09-01T22:41:35.281931","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mlp.rcParams['figure.figsize'] = (12, 10)\ncolors = plt.rcParams['axes.prop_cycle'].by_key()['color']","metadata":{"papermill":{"duration":0.022364,"end_time":"2023-09-01T22:42:28.081550","exception":false,"start_time":"2023-09-01T22:42:28.059186","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🦆 Hyperparameters","metadata":{"papermill":{"duration":0.014951,"end_time":"2023-09-01T22:42:28.110805","exception":false,"start_time":"2023-09-01T22:42:28.095854","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"AUTOTUNE = tf.data.experimental.AUTOTUNE\nGCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nIMAGE_SIZE = [512, 512]\nEPOCHS = 100","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🔨 Prepare Dataset","metadata":{"papermill":{"duration":0.014666,"end_time":"2023-09-01T22:42:28.176263","exception":false,"start_time":"2023-09-01T22:42:28.161597","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec')\nVALID_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec')\nprint('Train TFRecord Files:', len(TRAINING_FILENAMES))\nprint('Validation TFRecord Files:', len(VALID_FILENAMES))\nprint('Test TFRecord Files:', len(TEST_FILENAMES))","metadata":{"papermill":{"duration":0.051685,"end_time":"2023-09-01T22:42:28.242250","exception":false,"start_time":"2023-09-01T22:42:28.190565","status":"completed"},"tags":[],"editable":false,"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']                                                                                                                                               # 100 - 102","metadata":{"papermill":{"duration":0.028725,"end_time":"2023-09-01T22:42:28.286776","exception":false,"start_time":"2023-09-01T22:42:28.258051","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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","metadata":{"papermill":{"duration":0.028535,"end_time":"2023-09-01T22:42:28.329368","exception":false,"start_time":"2023-09-01T22:42:28.300833","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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)","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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    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(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTOTUNE)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"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":{"papermill":{"duration":0.02282,"end_time":"2023-09-01T22:42:28.366351","exception":false,"start_time":"2023-09-01T22:42:28.343531","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Data augmentation","metadata":{"papermill":{"duration":0.014271,"end_time":"2023-09-01T22:42:28.394703","exception":false,"start_time":"2023-09-01T22:42:28.380432","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTOTUNE)\n    # statement in the next function (below), this happens essentially\n    # for free on TPU. Data pipeline code is executed on the \"CPU\"\n    # 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":{"papermill":{"duration":0.022123,"end_time":"2023-09-01T22:42:28.431137","exception":false,"start_time":"2023-09-01T22:42:28.409014","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Define loading methods","metadata":{"papermill":{"duration":0.014667,"end_time":"2023-09-01T22:42:28.460256","exception":false,"start_time":"2023-09-01T22:42:28.445589","status":"completed"},"tags":[],"editable":false}},{"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() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\ndef 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\ndef 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":{"papermill":{"duration":0.027432,"end_time":"2023-09-01T22:42:28.502353","exception":false,"start_time":"2023-09-01T22:42:28.474921","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","metadata":{"papermill":{"duration":0.023375,"end_time":"2023-09-01T22:42:28.541740","exception":false,"start_time":"2023-09-01T22:42:28.518365","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"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)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint(\n    'Dataset: {} training images, {} validation images, {} unlabeled test images'.format(\n        NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES\n    )\n)","metadata":{"papermill":{"duration":0.023577,"end_time":"2023-09-01T22:42:28.579691","exception":false,"start_time":"2023-09-01T22:42:28.556114","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = get_training_dataset()\nvalid_dataset = get_validation_dataset()\ntest_dataset = get_test_dataset()","metadata":{"papermill":{"duration":0.411998,"end_time":"2023-09-01T22:42:29.006114","exception":false,"start_time":"2023-09-01T22:42:28.594116","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_batch(ds):\n    plt.figure(figsize=(20,4))\n    for idx, data in enumerate(iter(ds)):\n        ax = plt.subplot(2,10,idx+1)\n        img, target = data\n        img = img.numpy()\n        plt.imshow(img)\n        if target.numpy():\n            plt.title(\"MALIGNANT\")\n        else:\n            plt.title(\"BENIGN\")\n        plt.axis(\"off\")","metadata":{"papermill":{"duration":0.025468,"end_time":"2023-09-01T22:42:29.046099","exception":false,"start_time":"2023-09-01T22:42:29.020631","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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,\n                                     # 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\n    # the case for test data)\n    return numpy_images, numpy_labels\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\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):\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\n    # 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_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()\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.'])","metadata":{"papermill":{"duration":0.044139,"end_time":"2023-09-01T22:42:29.105323","exception":false,"start_time":"2023-09-01T22:42:29.061184","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ds_iter = iter(train_dataset.unbatch().batch(20))","metadata":{"papermill":{"duration":0.060071,"end_time":"2023-09-01T22:42:29.181093","exception":false,"start_time":"2023-09-01T22:42:29.121022","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"one_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"papermill":{"duration":5.081312,"end_time":"2023-09-01T22:42:34.277725","exception":false,"start_time":"2023-09-01T22:42:29.196413","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#show_batch(train_dataset.unbatch().take(20))","metadata":{"papermill":{"duration":0.047051,"end_time":"2023-09-01T22:42:34.366605","exception":false,"start_time":"2023-09-01T22:42:34.319554","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🔥 Build the Model","metadata":{"papermill":{"duration":0.043954,"end_time":"2023-09-01T22:42:34.451801","exception":false,"start_time":"2023-09-01T22:42:34.407847","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"# def exponential_decay(lr0, s):\n#     def exponential_decay_fn(epoch):\n#         return lr0 * 0.1 **(epoch / s)\n#     return exponential_decay_fn\n\n# exponential_decay_fn = exponential_decay(0.01, 20)\n\n# lr_scheduler = tf.keras.callbacks.LearningRateScheduler(exponential_decay_fn)","metadata":{"papermill":{"duration":0.054321,"end_time":"2023-09-01T22:42:34.555671","exception":false,"start_time":"2023-09-01T22:42:34.501350","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 0\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_model(metrics = None):\n    base_model = tf.keras.applications.DenseNet201(input_shape=(*IMAGE_SIZE, 3),\n                                                   include_top=False,\n                                                   weights='imagenet',\n                                                   pooling='avg')\n    \n    base_model.trainable = True\n    \n    model = keras.Sequential([\n        base_model,\n        layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    \n    model.compile(optimizer='adam',\n                  loss = 'sparse_categorical_crossentropy',\n                  metrics= metrics\n                 )\n    \n    return model","metadata":{"papermill":{"duration":0.053582,"end_time":"2023-09-01T22:42:34.654478","exception":false,"start_time":"2023-09-01T22:42:34.600896","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALID_STEPS = NUM_VALIDATION_IMAGES // BATCH_SIZE","metadata":{"papermill":{"duration":0.050354,"end_time":"2023-09-01T22:42:34.746232","exception":false,"start_time":"2023-09-01T22:42:34.695878","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = make_model(metrics='sparse_categorical_accuracy')","metadata":{"papermill":{"duration":69.6699,"end_time":"2023-09-01T22:43:44.461095","exception":false,"start_time":"2023-09-01T22:42:34.791195","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_cb = ModelCheckpoint(\"melanoma_model.h5\",save_best_only=True)\nearly_stopping_cb = EarlyStopping(patience=10,restore_best_weights=True)","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 🚅 Train","metadata":{"papermill":{"duration":0.042507,"end_time":"2023-09-01T22:43:44.644580","exception":false,"start_time":"2023-09-01T22:43:44.602073","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"history = model.fit(\n    train_dataset, epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    validation_data=valid_dataset,\n    validation_steps=VALID_STEPS,\n    callbacks=[checkpoint_cb, early_stopping_cb, lr_callback]\n)","metadata":{"papermill":{"duration":4249.360219,"end_time":"2023-09-01T23:54:34.049250","exception":false,"start_time":"2023-09-01T22:43:44.689031","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 📈 Evaluation","metadata":{"papermill":{"duration":0.433907,"end_time":"2023-09-01T23:54:34.912606","exception":false,"start_time":"2023-09-01T23:54:34.478699","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"def plot_metrics(history):\n  metrics = ['loss', 'sparse_categorical_accuracy']\n  for n, metric in enumerate(metrics):\n    name = metric.replace(\"_\",\" \").capitalize()\n    plt.subplot(2,2,n+1)\n    plt.plot(history.epoch, history.history[metric], color=colors[0], label='Train')\n    plt.plot(history.epoch, history.history['val_'+metric],\n             color=colors[0], linestyle=\"--\", label='Val')\n    plt.xlabel('Epoch')\n    plt.ylabel(name)\n    if metric == 'loss':\n      plt.ylim([0, 5])\n    elif metric == 'sparse_categorical_accuracy':\n      plt.ylim([0,1.1])\n    else:\n      plt.ylim([0,1])\n\n    plt.legend()","metadata":{"papermill":{"duration":0.466054,"end_time":"2023-09-01T23:54:35.816103","exception":false,"start_time":"2023-09-01T23:54:35.350049","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_metrics(history)","metadata":{"papermill":{"duration":1.824497,"end_time":"2023-09-01T23:54:38.082172","exception":false,"start_time":"2023-09-01T23:54:36.257675","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 📝 Prediction","metadata":{"papermill":{"duration":0.443446,"end_time":"2023-09-01T23:54:38.969083","exception":false,"start_time":"2023-09-01T23:54:38.525637","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images, labels = next(batch)\nprobabilities = model.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)","metadata":{"papermill":{"duration":86.59609,"end_time":"2023-09-01T23:56:06.039679","exception":false,"start_time":"2023-09-01T23:54:39.443589","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 📃 Submission file","metadata":{"papermill":{"duration":0.469209,"end_time":"2023-09-01T23:56:07.015947","exception":false,"start_time":"2023-09-01T23:56:06.546738","status":"completed"},"tags":[],"editable":false}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\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)","metadata":{"papermill":{"duration":27.96131,"end_time":"2023-09-01T23:56:35.425049","exception":false,"start_time":"2023-09-01T23:56:07.463739","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n# Get image ids from test set and convert to unicode\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')\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n# Look at the first few predictions\n!head submission.csv","metadata":{"papermill":{"duration":7.290354,"end_time":"2023-09-01T23:56:43.232582","exception":false,"start_time":"2023-09-01T23:56:35.942228","status":"completed"},"tags":[],"editable":false,"trusted":true},"execution_count":null,"outputs":[]}],"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"}}