{"cells":[{"metadata":{"_uuid":"7fff9e9a-30bf-43a4-98a0-fe8d95622cc3","_cell_guid":"16c53049-c951-4a2c-9b8b-1e17370959f6","trusted":true},"cell_type":"code","source":"!pip install -U -t /kaggle/working/ git+https://github.com/Kaggle/learntools.git\nfrom learntools.core import binder\nbinder.bind(globals())\nfrom learntools.deep_learning.ex_tpu import *\nstep_1.check()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"83fe174b-2850-46b7-9eb5-db9a2493ff2d","_cell_guid":"ec79e2e8-9285-4354-bc63-b219b2bab8b2","trusted":true},"cell_type":"code","source":"from petal_helper import *","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"25c1f21b-4d94-4943-8148-0064966d7f8b","_cell_guid":"27bf7eee-ba25-467b-9dd2-204c49b6120f","trusted":true},"cell_type":"markdown","source":"## Create Distribution Strategy ##","execution_count":null},{"metadata":{"_uuid":"9c4d95c7-9a69-4afe-a052-120c9244a073","_cell_guid":"13b476ea-2388-4547-bf35-5dab54a99114","trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"5bad9fa9-814a-4883-adb3-0a41907a605b","_cell_guid":"45c7d837-d252-4c89-b8e4-b141ea1a416f","trusted":true},"cell_type":"markdown","source":"## Loading the Competition Data ##","execution_count":null},{"metadata":{"_uuid":"606b87eb-4047-47d3-bcfd-9673df1126f6","_cell_guid":"e52bf337-c412-4411-9a58-00ca5f92f25e","trusted":true},"cell_type":"code","source":"ds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"bf5eb051-1eb9-4179-b78e-91cc5a4b2287","_cell_guid":"9cd9e8ca-53fa-44d2-9f6e-61f1b8f54fdd","trusted":true},"cell_type":"markdown","source":"## Explore the Data ##\n\nTry using some of the helper functions described in the **Getting Started** tutorial to explore the dataset.","execution_count":null},{"metadata":{"_uuid":"105d87cd-32dd-4da1-81fe-9ee63e815334","_cell_guid":"9c4f599e-2bf2-4dd4-aed4-309c801e6532","trusted":true},"cell_type":"code","source":"print(\"Number of classes: {}\".format(len(CLASSES)))\n\nprint(\"First five classes, sorted alphabetically:\")\nfor name in sorted(CLASSES)[:5]:\n    print(name)\n\nprint (\"Number of training images: {}\".format(NUM_TRAINING_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7c357587-acf8-4c7b-8114-41eee3157fc0","_cell_guid":"eb2a384d-47cc-42e3-94da-4e2383d810ea","trusted":true},"cell_type":"markdown","source":"Examine the shape of the data.","execution_count":null},{"metadata":{"_uuid":"8e14588f-9e8e-45f9-a616-63e2f401bcd1","_cell_guid":"64aae20f-caf4-4061-b6f4-2725db9f439b","trusted":true},"cell_type":"code","source":"print(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"480d61ca-4c20-4a34-9064-f698a35564a6","_cell_guid":"492d1149-cf97-4fd6-a079-2e3013edfbaf","trusted":true},"cell_type":"code","source":"print(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"72e722d2-3b47-44b5-b22d-c74586a81a65","_cell_guid":"a55a8280-b4be-4f0f-ba7d-c51eb33301b4","trusted":true},"cell_type":"markdown","source":"Peek at training data.","execution_count":null},{"metadata":{"_uuid":"6a295be2-8924-4677-ae3f-d2c24a2f3d5d","_cell_guid":"ab2c3640-e01d-4f45-969c-584423f27256","trusted":true},"cell_type":"code","source":"one_batch = next(iter(ds_train.unbatch().batch(20)))\ndisplay_batch_of_images(one_batch)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f20d72f0-f4db-4a35-b4b5-bfdb43479cfc","_cell_guid":"ed8e18ae-2c57-4caf-ac59-8552521a570d","trusted":true},"cell_type":"markdown","source":"## Define Model #","execution_count":null},{"metadata":{"_uuid":"7d0ba0fe-4cdc-421e-b13c-29ff10e7308a","_cell_guid":"a1425885-d111-46fa-8062-972153aeafe9","trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model,\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='sigmoid')\n    ])\n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"94be9775-3673-4bcb-b3c1-e15d08543f86","_cell_guid":"71e9951b-86c7-45b7-9569-3068d62c1082","trusted":true},"cell_type":"markdown","source":"## Train Model ##","execution_count":null},{"metadata":{"_uuid":"197c15aa-9b26-48c3-abe4-41f96a2c094b","_cell_guid":"255a4615-6725-4745-a501-322ccba52491","trusted":true},"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 with TPU on\nBATCH_SIZE = 32 * strategy.num_replicas_in_sync\n\n# Define training epochs for committing/submitting. (TPU on)\nEPOCHS = 500\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"ebdf8595-bf3c-4bea-97ca-aeff0e32bbbf","_cell_guid":"44ff5e07-8117-43c2-9fe6-4b649e28cf19","trusted":true},"cell_type":"markdown","source":"Examine training curves.","execution_count":null},{"metadata":{"_uuid":"5b2cd67a-fdaf-4e73-bfea-10b586cfc8cf","_cell_guid":"1a5fcd73-294a-4bd2-a56a-a8de727538dc","trusted":true},"cell_type":"code","source":"display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"375a9dd8-60e9-4d2a-b361-1c58cf3d6889","_cell_guid":"59240811-66b5-4280-a0c7-6ccfe50d5ff2","trusted":true},"cell_type":"markdown","source":"## Validation ##\n\nCreate a confusion matrix.","execution_count":null},{"metadata":{"_uuid":"de109635-5314-4284-9393-18db81a537ed","_cell_guid":"66e67acb-25f4-4c25-b77a-140b70910212","trusted":true},"cell_type":"code","source":"cmdataset = get_validation_dataset(ordered=True)\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\ncmat = confusion_matrix(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f396ced-9163-46e4-a01b-abccd9871776","_cell_guid":"3f512acd-8f57-46a5-9ff8-bc75ac16544c","trusted":true},"cell_type":"code","source":"score = f1_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprecision = precision_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nrecall = recall_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\ndisplay_confusion_matrix(cmat, score, precision, recall)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"e2b175ff-2adc-4208-a340-d062390477ab","_cell_guid":"4485b66f-8aa0-4d06-b24e-27318874341b","trusted":true},"cell_type":"markdown","source":"Look at examples from the dataset, with true and predicted classes.","execution_count":null},{"metadata":{"_uuid":"eb737d4f-7f35-4a09-b499-8d0a0ac0d6de","_cell_guid":"270cf933-6c66-49a9-b3c4-2391dad12e6e","trusted":true},"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"dc70eea9-a670-4be8-a9ff-faf9bfed0473","_cell_guid":"4107e2ae-6dcc-4190-84f3-28a07a65ec8d","trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"f4d6643a-8cd9-4fc4-8912-135d2f78c914","_cell_guid":"611ef77c-55d1-4e35-a825-a7dfcfb8fbe3","trusted":true},"cell_type":"markdown","source":"## Test Predictions ##\n\nCreate predictions to submit to the competition.","execution_count":null},{"metadata":{"_uuid":"a5465a46-5762-4641-affa-4b7bddca9a4d","_cell_guid":"d6c74974-7c40-4512-993a-e7c8b260f9f7","trusted":true},"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)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7fc931b6-2ef1-4647-856e-f1a732d4a6e6","_cell_guid":"6019c1ad-0a43-4f0e-87b4-2df4bc01859b","trusted":true},"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to integers\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\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\n# Look at the first few predictions\n!head submission.csv","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}