{"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":"# Importing Dependencies","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np \nimport re\nimport math","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:20.072800Z","iopub.execute_input":"2022-11-10T13:45:20.073054Z","iopub.status.idle":"2022-11-10T13:45:20.078854Z","shell.execute_reply.started":"2022-11-10T13:45:20.073014Z","shell.execute_reply":"2022-11-10T13:45:20.077719Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setup TPU and Distribution strategy","metadata":{}},{"cell_type":"code","source":"# Detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:20.277599Z","iopub.execute_input":"2022-11-10T13:45:20.278724Z","iopub.status.idle":"2022-11-10T13:45:25.974966Z","shell.execute_reply.started":"2022-11-10T13:45:20.278651Z","shell.execute_reply":"2022-11-10T13:45:25.974103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Porcessing","metadata":{}},{"cell_type":"markdown","source":"I am not quite exerienced with the tfrecord and efficient tpu optimization so I spent a huge amout of time on the cloud local error 😅😅😅😅 Then I googled and realised that TPUs cannot access local data they only use cloud verified data and therefore in next cell i am going to get the same data but from google cloud.\n**am still learning ig**","metadata":{}},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n# google cloud store path\nPATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(PATH)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:25.977148Z","iopub.execute_input":"2022-11-10T13:45:25.977362Z","iopub.status.idle":"2022-11-10T13:45:26.308897Z","shell.execute_reply.started":"2022-11-10T13:45:25.977337Z","shell.execute_reply":"2022-11-10T13:45:26.308255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# paths \nTRAINING_IMAGES = tf.io.gfile.glob(f'{PATH}/tfrecords-jpeg-512x512/train/*.tfrec')\nVALID_IMAGES = tf.io.gfile.glob(f'{PATH}/tfrecords-jpeg-512x512/val/*.tfrec')\nTEST_IMAGES = tf.io.gfile.glob(f'{PATH}/tfrecords-jpeg-512x512/test/*.tfrec')","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.309769Z","iopub.execute_input":"2022-11-10T13:45:26.309932Z","iopub.status.idle":"2022-11-10T13:45:26.433155Z","shell.execute_reply.started":"2022-11-10T13:45:26.309910Z","shell.execute_reply":"2022-11-10T13:45:26.431250Z"},"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":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.435089Z","iopub.execute_input":"2022-11-10T13:45:26.435280Z","iopub.status.idle":"2022-11-10T13:45:26.444112Z","shell.execute_reply.started":"2022-11-10T13:45:26.435257Z","shell.execute_reply":"2022-11-10T13:45:26.442724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Helper variables\nAUTO = tf.data.experimental.AUTOTUNE\nIMAGE_SHAPE = [512,512]\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nEPOCHS = 5\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.445366Z","iopub.execute_input":"2022-11-10T13:45:26.445994Z","iopub.status.idle":"2022-11-10T13:45:26.464407Z","shell.execute_reply.started":"2022-11-10T13:45:26.445939Z","shell.execute_reply":"2022-11-10T13:45:26.462757Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset Helper Function","metadata":{}},{"cell_type":"code","source":"def decode_image(img):\n    '''Load Image From The Dataset'''\n    image = tf.io.decode_jpeg(img,channels=3)\n    image = tf.cast(image,tf.float32)/255.0\n    image = tf.reshape(image,[*IMAGE_SHAPE,3])\n    return image\n    ","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.620232Z","iopub.execute_input":"2022-11-10T13:45:26.621077Z","iopub.status.idle":"2022-11-10T13:45:26.626752Z","shell.execute_reply.started":"2022-11-10T13:45:26.621009Z","shell.execute_reply":"2022-11-10T13:45:26.625590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_labeled_data(example):\n    '''Read Labeled tfrecord'''\n    labeled_struct = {\n        'image':tf.io.FixedLenFeature([],tf.string),\n        'class': tf.io.FixedLenFeature([],tf.int64)\n    }\n    parsed = tf.io.parse_single_example(example,labeled_struct)\n    image = decode_image(parsed['image'])\n    label = tf.cast(parsed['class'],tf.int32)\n    return image,label","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.628265Z","iopub.execute_input":"2022-11-10T13:45:26.628579Z","iopub.status.idle":"2022-11-10T13:45:26.645727Z","shell.execute_reply.started":"2022-11-10T13:45:26.628540Z","shell.execute_reply":"2022-11-10T13:45:26.644829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_unlabeled_data(example):\n    '''Read unlabeled tfrecord'''\n    unlabeled_struct = {\n        'image':tf.io.FixedLenFeature([],tf.string),\n        'id':tf.io.FixedLenFeature([],tf.string)\n    }\n    parsed = tf.io.parse_single_example(example,unlabeled_struct)\n    image = decode_image(parsed['image'])\n    idnum = parsed['id']\n    return image,idnum","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.646586Z","iopub.execute_input":"2022-11-10T13:45:26.647724Z","iopub.status.idle":"2022-11-10T13:45:26.659915Z","shell.execute_reply.started":"2022-11-10T13:45:26.647670Z","shell.execute_reply":"2022-11-10T13:45:26.658717Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_dataset(filenames,is_labeled = True,inorder=False):\n    '''Load the tfrecord as Dataset.\n    is_label(bool) : is the data labeled or unlabeled\n    inorder(bool) : Should the data be inorder or loaded as soon as it arrives'''\n    options = tf.data.Options()\n    if not inorder:\n        options.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(filenames,num_parallel_reads=AUTO)\n    dataset = dataset.with_options(options)\n    dataset = dataset.map(read_labeled_data if is_labeled else read_unlabeled_data)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.663077Z","iopub.execute_input":"2022-11-10T13:45:26.663323Z","iopub.status.idle":"2022-11-10T13:45:26.674342Z","shell.execute_reply.started":"2022-11-10T13:45:26.663298Z","shell.execute_reply":"2022-11-10T13:45:26.673220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_aug(image,label):\n    '''Image Augummentation'''\n    image = tf.image.random_flip_left_right(image)\n    return image,label","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.675347Z","iopub.execute_input":"2022-11-10T13:45:26.675969Z","iopub.status.idle":"2022-11-10T13:45:26.689436Z","shell.execute_reply.started":"2022-11-10T13:45:26.675936Z","shell.execute_reply":"2022-11-10T13:45:26.688161Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_training_data():\n    '''Load the training dataset'''\n    dataset = load_dataset(TRAINING_IMAGES,is_labeled=True)\n    dataset = dataset.map(data_aug,num_parallel_calls=AUTO)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(49)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.690573Z","iopub.execute_input":"2022-11-10T13:45:26.691251Z","iopub.status.idle":"2022-11-10T13:45:26.702675Z","shell.execute_reply.started":"2022-11-10T13:45:26.691218Z","shell.execute_reply":"2022-11-10T13:45:26.701497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_valid_data():\n    '''Load the validation dataset'''\n    dataset = load_dataset(VALID_IMAGES,is_labeled=True,inorder=True)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.704049Z","iopub.execute_input":"2022-11-10T13:45:26.704572Z","iopub.status.idle":"2022-11-10T13:45:26.715955Z","shell.execute_reply.started":"2022-11-10T13:45:26.704544Z","shell.execute_reply":"2022-11-10T13:45:26.715333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_test_data(ordered=False):\n    '''Load the test dataset'''\n    dataset = load_dataset(TEST_IMAGES,is_labeled=False,inorder=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.716885Z","iopub.execute_input":"2022-11-10T13:45:26.717590Z","iopub.status.idle":"2022-11-10T13:45:26.730366Z","shell.execute_reply.started":"2022-11-10T13:45:26.717557Z","shell.execute_reply":"2022-11-10T13:45:26.729521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_files(filenames):\n    '''Count number of files in the dataset'''\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(file).group(1)) for file in filenames]\n    return np.sum(n)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.731220Z","iopub.execute_input":"2022-11-10T13:45:26.732057Z","iopub.status.idle":"2022-11-10T13:45:26.750927Z","shell.execute_reply.started":"2022-11-10T13:45:26.732006Z","shell.execute_reply":"2022-11-10T13:45:26.749939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAIN_IMG = count_files(TRAINING_IMAGES)\nNUM_VALID_IMG = count_files(VALID_IMAGES)\nNUM_TEST_IMG = count_files(TEST_IMAGES)\nprint(f'Number of training images : {NUM_TRAIN_IMG} \\nNumber of validation images : {NUM_VALID_IMG} \\nNumber of test images : {NUM_TEST_IMG}')","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.752203Z","iopub.execute_input":"2022-11-10T13:45:26.752538Z","iopub.status.idle":"2022-11-10T13:45:26.764526Z","shell.execute_reply.started":"2022-11-10T13:45:26.752507Z","shell.execute_reply":"2022-11-10T13:45:26.763592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get the data\nds_train = get_training_data()\nds_valid = get_valid_data()\nds_test = get_test_data()\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:26.808885Z","iopub.execute_input":"2022-11-10T13:45:26.809141Z","iopub.status.idle":"2022-11-10T13:45:26.935116Z","shell.execute_reply.started":"2022-11-10T13:45:26.809118Z","shell.execute_reply":"2022-11-10T13:45:26.933674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# EDA","metadata":{}},{"cell_type":"code","source":"def batch_to_numpy(data):\n    '''Converts batch of data to numpy '''\n    image , label = data\n    image = image.numpy()\n    label = label.numpy()\n    if label.dtype == object:\n        label = [None for _ in enumerate(label)]\n    return image , label","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:37.523084Z","iopub.execute_input":"2022-11-10T13:45:37.523573Z","iopub.status.idle":"2022-11-10T13:45:37.529456Z","shell.execute_reply.started":"2022-11-10T13:45:37.523546Z","shell.execute_reply":"2022-11-10T13:45:37.528862Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_batch_images(databatch):\n    '''Plots Some Train , Test , Validation data'''\n    # load data as numpy \n    img,label = batch_to_numpy(databatch)\n    \n    rows = int(math.sqrt(len(img)))\n    cols = len(img)//rows\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    for i , (image, label) in enumerate(zip(img[:rows*cols],label[:rows*cols])):\n        plt.subplot(rows,cols,i+1)\n        plt.axis('off')\n        plt.imshow(image)\n        if label:\n            plt.title(CLASSES[label])\n        plt.tight_layout()\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n        ","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:37.920857Z","iopub.execute_input":"2022-11-10T13:45:37.921217Z","iopub.status.idle":"2022-11-10T13:45:37.930148Z","shell.execute_reply.started":"2022-11-10T13:45:37.921192Z","shell.execute_reply":"2022-11-10T13:45:37.929153Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display_batch_images(next(iter(ds_valid.unbatch().batch(25))))","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:45:39.527443Z","iopub.execute_input":"2022-11-10T13:45:39.527691Z","iopub.status.idle":"2022-11-10T13:45:45.217221Z","shell.execute_reply.started":"2022-11-10T13:45:39.527668Z","shell.execute_reply":"2022-11-10T13:45:45.212828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modeling & tuning ","metadata":{"execution":{"iopub.status.busy":"2022-11-10T07:22:01.114433Z","iopub.execute_input":"2022-11-10T07:22:01.114716Z","iopub.status.idle":"2022-11-10T07:22:02.859570Z","shell.execute_reply.started":"2022-11-10T07:22:01.114686Z","shell.execute_reply":"2022-11-10T07:22:02.858468Z"}}},{"cell_type":"code","source":"# Model Creation using the strategy \nwith strategy.scope():\n    pt = tf.keras.applications.xception.Xception(\n    include_top=False,\n    weights='imagenet',\n    input_shape=(*IMAGE_SHAPE,3)\n)\n    pt.trainable = True\n    model = tf.keras.Sequential([\n        pt,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(128,activation='relu'),\n        tf.keras.layers.Dense(len(CLASSES),activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:46:36.363826Z","iopub.execute_input":"2022-11-10T13:46:36.364159Z","iopub.status.idle":"2022-11-10T13:46:45.368229Z","shell.execute_reply.started":"2022-11-10T13:46:36.364126Z","shell.execute_reply":"2022-11-10T13:46:45.366849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\nearly_stopping = tf.keras.callbacks.EarlyStopping(\n    monitor='val_loss',\n    min_delta=0.001, # minimium amount of change to count as an improvement\n    patience=5, # how many epochs to wait before stopping\n    restore_best_weights=True,\n)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:46:45.369600Z","iopub.execute_input":"2022-11-10T13:46:45.369784Z","iopub.status.idle":"2022-11-10T13:46:45.413710Z","shell.execute_reply.started":"2022-11-10T13:46:45.369763Z","shell.execute_reply":"2022-11-10T13:46:45.412566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:46:45.415109Z","iopub.execute_input":"2022-11-10T13:46:45.415340Z","iopub.status.idle":"2022-11-10T13:46:45.433523Z","shell.execute_reply.started":"2022-11-10T13:46:45.415314Z","shell.execute_reply":"2022-11-10T13:46:45.432041Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Adaptive LR\nLR_START = 0.00005\nLR_MAX = LR_START \nLR_MIN = 0.00001 \nLR_RAMPUP_EPOCHS = 0 \nLR_SUSTAIN_EPOCHS = 5 \nLR_EXP_DECAY = 0.85\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:  \n        lr = LR_START + (epoch * (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS)   \n    elif epoch < (LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):  \n        lr = LR_MAX\n    else:    \n        lr = LR_MIN + (LR_MAX - LR_MIN) * LR_EXP_DECAY ** (epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)\n\n    return lr\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\nlr = [lrfn(n) for n in range(30)]\nplt.plot(lr)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:46:51.238885Z","iopub.execute_input":"2022-11-10T13:46:51.239163Z","iopub.status.idle":"2022-11-10T13:46:51.397971Z","shell.execute_reply.started":"2022-11-10T13:46:51.239140Z","shell.execute_reply":"2022-11-10T13:46:51.396533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# training \nSTEPS_PER_EPOCH = NUM_TRAIN_IMG // BATCH_SIZE\nEPOCHS = 15\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback, early_stopping],\n)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:46:59.037545Z","iopub.execute_input":"2022-11-10T13:46:59.037817Z","iopub.status.idle":"2022-11-10T13:58:26.701884Z","shell.execute_reply.started":"2022-11-10T13:46:59.037766Z","shell.execute_reply":"2022-11-10T13:58:26.700533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_hist(history,EPOCHS):\n    plt.subplot(2,1,1)\n    loss = history.history['loss']\n    vloss = history.history['val_loss']\n    plt.plot(range(1,EPOCHS+1),loss,c='b',label='loss')\n    plt.plot(range(1,EPOCHS+1),vloss,c='r',label='val_loss')\n    plt.legend()\n    plt.subplot(2,1,2)\n    acc = history.history['sparse_categorical_accuracy']\n    vacc = history.history['val_sparse_categorical_accuracy']\n    plt.plot(range(1,EPOCHS+1),acc,c='b',label='accuracy')\n    plt.plot(range(1,EPOCHS+1),vacc,c='r',label='val_accuracy')\n    plt.legend()\n    plt.plot()\n","metadata":{"execution":{"iopub.status.busy":"2022-11-10T14:20:01.843792Z","iopub.execute_input":"2022-11-10T14:20:01.844076Z","iopub.status.idle":"2022-11-10T14:20:01.852473Z","shell.execute_reply.started":"2022-11-10T14:20:01.844051Z","shell.execute_reply":"2022-11-10T14:20:01.851117Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_hist(history,EPOCHS)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T14:20:05.339140Z","iopub.execute_input":"2022-11-10T14:20:05.339391Z","iopub.status.idle":"2022-11-10T14:20:05.623178Z","shell.execute_reply.started":"2022-11-10T14:20:05.339367Z","shell.execute_reply":"2022-11-10T14:20:05.621876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save the model\nmodel.save('Petals_to_the_Metal_save1.h5')","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:58:26.703763Z","iopub.execute_input":"2022-11-10T13:58:26.704006Z","iopub.status.idle":"2022-11-10T13:58:29.656851Z","shell.execute_reply.started":"2022-11-10T13:58:26.703982Z","shell.execute_reply":"2022-11-10T13:58:29.655583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prediction & submission","metadata":{}},{"cell_type":"code","source":"#load the test dataset\ntest_ds = get_test_data(ordered=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:59:15.265196Z","iopub.execute_input":"2022-11-10T13:59:15.265439Z","iopub.status.idle":"2022-11-10T13:59:15.351669Z","shell.execute_reply.started":"2022-11-10T13:59:15.265415Z","shell.execute_reply":"2022-11-10T13:59:15.350637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# seperate image and id \ntest_images_ds = test_ds.map(lambda image, idnum: image)\ntest_id_ds = test_ds.map(lambda image, idnum: idnum)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:59:33.770437Z","iopub.execute_input":"2022-11-10T13:59:33.770698Z","iopub.status.idle":"2022-11-10T13:59:33.809172Z","shell.execute_reply.started":"2022-11-10T13:59:33.770672Z","shell.execute_reply":"2022-11-10T13:59:33.807806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# perform prediction on the test data using trained model\npred = model.predict(test_images_ds)\n# since the model output is sparse we only need the max value index\nlabel_pred = np.argmax(pred,axis=-1)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T13:59:37.182792Z","iopub.execute_input":"2022-11-10T13:59:37.183054Z","iopub.status.idle":"2022-11-10T14:00:15.088362Z","shell.execute_reply.started":"2022-11-10T13:59:37.183005Z","shell.execute_reply":"2022-11-10T14:00:15.087288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Id dataset -> numpy \nids = next(iter(test_id_ds.unbatch().batch(NUM_TEST_IMG))).numpy().astype('U')","metadata":{"execution":{"iopub.status.busy":"2022-11-10T14:04:14.138246Z","iopub.execute_input":"2022-11-10T14:04:14.139366Z","iopub.status.idle":"2022-11-10T14:04:39.968097Z","shell.execute_reply.started":"2022-11-10T14:04:14.139282Z","shell.execute_reply":"2022-11-10T14:04:39.966794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# dictionary to create dataframe from data\ndf = {\n    'id':ids,\n    'label':label_pred\n}\ndf = pd.DataFrame(df)\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2022-11-10T14:05:51.335895Z","iopub.execute_input":"2022-11-10T14:05:51.336470Z","iopub.status.idle":"2022-11-10T14:05:51.358075Z","shell.execute_reply.started":"2022-11-10T14:05:51.336437Z","shell.execute_reply":"2022-11-10T14:05:51.356869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save as csv\ndf.to_csv('submission.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-11-10T14:06:13.372661Z","iopub.execute_input":"2022-11-10T14:06:13.373352Z","iopub.status.idle":"2022-11-10T14:06:13.392405Z","shell.execute_reply.started":"2022-11-10T14:06:13.373325Z","shell.execute_reply":"2022-11-10T14:06:13.389885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}