{"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":"none","dataSources":[{"sourceId":21154,"databundleVersionId":1243559,"sourceType":"competition"},{"sourceId":7060436,"sourceType":"datasetVersion","datasetId":4064636}],"dockerImageVersionId":30579,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# <center>Petals to the Metal - Flower Classification on TPU<center>","metadata":{}},{"cell_type":"markdown","source":"## <center>_DS 5220 Submission Notebook_<center>","metadata":{"execution":{"iopub.status.busy":"2023-11-26T22:55:25.026824Z","iopub.execute_input":"2023-11-26T22:55:25.02729Z","iopub.status.idle":"2023-11-26T22:55:25.035925Z","shell.execute_reply.started":"2023-11-26T22:55:25.027255Z","shell.execute_reply":"2023-11-26T22:55:25.034222Z"}}},{"cell_type":"markdown","source":"#### Imports","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport os\n\nimport tensorflow as tf\nimport keras\nfrom kaggle_datasets import KaggleDatasets\nprint(\"TF version: \" + tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:45:44.805399Z","iopub.execute_input":"2023-11-26T23:45:44.805822Z","iopub.status.idle":"2023-11-26T23:45:55.407819Z","shell.execute_reply.started":"2023-11-26T23:45:44.805787Z","shell.execute_reply":"2023-11-26T23:45:55.406759Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Upload saved model (as 'dataset') and paste path below. \n\nUse legacy _'.hf'_ format to avoid shape mismatch errors.","metadata":{}},{"cell_type":"code","source":"# Upload saved model and paste total path here:\nloaded_model_path = \"___\"\n\n# example:\nloaded_model_path = \"/kaggle/input/small-model-3/small_model_3.h5\"\n\n","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:45:55.409645Z","iopub.execute_input":"2023-11-26T23:45:55.410757Z","iopub.status.idle":"2023-11-26T23:45:55.414937Z","shell.execute_reply.started":"2023-11-26T23:45:55.410723Z","shell.execute_reply":"2023-11-26T23:45:55.413893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Image Parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [224, 224] # at this size, a GPU will run out of memory. Use the TPU\nNUM_TEST_IMAGES = 7382","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:45:55.415994Z","iopub.execute_input":"2023-11-26T23:45:55.416311Z","iopub.status.idle":"2023-11-26T23:45:55.431534Z","shell.execute_reply.started":"2023-11-26T23:45:55.416279Z","shell.execute_reply":"2023-11-26T23:45:55.430536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Define Helper Functions","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(datapoint):\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    datapoint = tf.io.parse_single_example(datapoint, LABELED_TFREC_FORMAT)\n    image = decode_image(datapoint['image'])\n    label = tf.cast(datapoint['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(datapoint):\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    datapoint = tf.io.parse_single_example(datapoint, UNLABELED_TFREC_FORMAT)\n    image = decode_image(datapoint['image'])\n    idnum = datapoint['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_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob('/kaggle/input/tpu-getting-started/tfrecords-jpeg-224x224/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(1) # do we need this?\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:45:55.434053Z","iopub.execute_input":"2023-11-26T23:45:55.435029Z","iopub.status.idle":"2023-11-26T23:45:55.445482Z","shell.execute_reply.started":"2023-11-26T23:45:55.434997Z","shell.execute_reply":"2023-11-26T23:45:55.444646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Rebuild Trained Model","metadata":{}},{"cell_type":"code","source":"# loads saved model architecture and weights as saved from training\nloaded_model = tf.keras.saving.load_model(loaded_model_path)\n\n# displays summary and plot of loaded model\nprint(\"\\nModel Summary:\\n\")\nloaded_model.summary()\n\nprint(\"\\n Model Diagram:\\n\")\nkeras.utils.plot_model(loaded_model, show_shapes=True)","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:45:55.446320Z","iopub.execute_input":"2023-11-26T23:45:55.447089Z","iopub.status.idle":"2023-11-26T23:45:56.444858Z","shell.execute_reply.started":"2023-11-26T23:45:55.447065Z","shell.execute_reply":"2023-11-26T23:45:56.443667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Evaluate Test Data with Loaded Model\n\nUses our trained model to produce class predictions based on the test images","metadata":{}},{"cell_type":"code","source":"# since we are splitting the dataset and iterating separately on images and ids, order matters.\ntest_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = loaded_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":"2023-11-26T23:45:56.446086Z","iopub.execute_input":"2023-11-26T23:45:56.446859Z","iopub.status.idle":"2023-11-26T23:48:20.457600Z","shell.execute_reply.started":"2023-11-26T23:45:56.446826Z","shell.execute_reply":"2023-11-26T23:48:20.456686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Clear out submission file if needed:","metadata":{}},{"cell_type":"code","source":"# !rm /kaggle/working/submission.csv","metadata":{"execution":{"iopub.status.busy":"2023-11-26T23:48:20.458870Z","iopub.execute_input":"2023-11-26T23:48:20.459230Z","iopub.status.idle":"2023-11-26T23:48:20.463662Z","shell.execute_reply.started":"2023-11-26T23:48:20.459202Z","shell.execute_reply":"2023-11-26T23:48:20.462585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}