{"cells":[{"metadata":{"_uuid":"05987ed8-67bb-4177-97c3-319ad02d7be4","_cell_guid":"7dd00cdf-cb3c-4033-a483-0c745a56d353","trusted":true},"cell_type":"markdown","source":"**[Deep Learning Home Page](https://www.kaggle.com/learn/deep-learning)**\n\n---","execution_count":null},{"metadata":{"_uuid":"57e57669-5213-49be-8c9c-7727e700a438","_cell_guid":"62089727-bf02-4e2b-8970-bc063d2cf5f2","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":"3fd28e85-6f02-4889-b660-a75becab6fb1","_cell_guid":"3f95d118-0cb2-44cd-a3e9-16ef4f8a40e7","trusted":true},"cell_type":"markdown","source":"# Code #\n\nThe code reproduces the code we covered together in **[the tutorial](https://www.kaggle.com/ryanholbrook/create-your-first-submission)**.  If you commit the notebook by following the instructions above, then the code is run for you.\n\n## Load Helper Functions ##","execution_count":null},{"metadata":{"_uuid":"da717fc5-cac7-48da-9a8d-8b0444cc9165","_cell_guid":"430cb68b-14d7-41f0-b04a-de5802bf20e1","trusted":true},"cell_type":"code","source":"from petal_helper import *","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7c546957-aa2a-4dc9-9b30-b309a465a00c","_cell_guid":"6ffbc651-dc38-4472-805e-5ba693bc6c6c","trusted":true},"cell_type":"markdown","source":"## Create Distribution Strategy ##","execution_count":null},{"metadata":{"_uuid":"bc7e1eb5-db2a-4012-8095-3a1725f30d32","_cell_guid":"e8020353-4271-4ca4-9391-e34a1b20394b","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":"89f23f2f-8af9-4b5d-8466-f6b885080413","_cell_guid":"a34a9054-0eed-40e6-b5cc-5883625a1c33","trusted":true},"cell_type":"markdown","source":"## Loading the Competition Data ##","execution_count":null},{"metadata":{"_uuid":"71259430-1ebd-4331-bb9c-9595a73ee135","_cell_guid":"943caa96-793f-492a-910c-f56c7b0a833e","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":"b1ace279-c7c4-499d-9c9e-a7012d6cdaa3","_cell_guid":"5ebe126b-8d94-46d3-bb39-9c9a4fffc497","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":"10e98da8-07d8-4f5f-a1fc-741e017b8456","_cell_guid":"5ce4820f-9d80-46a5-bf3f-0d9a145afb9f","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":"9e0c9390-cf3d-4118-b891-e515882323cd","_cell_guid":"13977bbe-1ed4-45f1-a015-76bdcd404c1a","trusted":true},"cell_type":"markdown","source":"Examine the shape of the data.","execution_count":null},{"metadata":{"_uuid":"9edb9212-2c9f-444e-b3af-ada559936bf9","_cell_guid":"648dec8d-1e9d-4627-b9f0-4c017ae61a8e","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":"3d9dd746-6e69-408a-9aff-7e3e170d18c9","_cell_guid":"2e7051f3-b353-48c5-9e1e-ad3bdd35d0f2","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":"fef6ebf3-50d9-4b5d-b37b-6c7390cc4618","_cell_guid":"1ec20372-2a8d-46ea-b00f-763506f1a104","trusted":true},"cell_type":"markdown","source":"Peek at training data.","execution_count":null},{"metadata":{"_uuid":"25098d87-6d76-495c-9e5c-60827cc3cc1e","_cell_guid":"c1111adc-f55c-4e9a-bc15-60644e0dee1f","trusted":true},"cell_type":"code","source":"one_batch = next(iter(ds_train.unbatch().batch(10)))\ndisplay_batch_of_images(one_batch)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"3baf209e-0f70-4921-b2c4-b9e8fd80ede2","_cell_guid":"7cdb13d3-3384-4ed1-9881-fa79479eaaa4","trusted":true},"cell_type":"markdown","source":"## Define Model #","execution_count":null},{"metadata":{"_uuid":"d454349d-7e30-4f53-9dbd-f4992a53500e","_cell_guid":"be77286e-a883-466b-a3b3-39a6c11ce653","trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"edeeab28-6dec-44d6-a402-5f85f3cd13e0","_cell_guid":"d7f4cfbe-3f3b-467b-892b-08227f49068d","trusted":true},"cell_type":"code","source":"import efficientnet.tfkeras as efn\n\nwith strategy.scope():\n    pretrained_model = efn.EfficientNetB7(\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       \n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\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":"0f4d93f3-3a2b-4830-863d-9c943438f1a8","_cell_guid":"e16fb417-c7d1-4de7-a485-8d123418f3f0","trusted":true},"cell_type":"markdown","source":"## Train Model ##","execution_count":null},{"metadata":{"_uuid":"24dce2f2-65aa-4329-be44-1ee215a18067","_cell_guid":"c4df0e98-2830-4117-abb2-fafaca59c58c","trusted":true},"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 with TPU on\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\n# Define training epochs for committing/submitting. (TPU on)\nEPOCHS = 30\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":"cc3a9791-3271-4750-8b2e-ba471f048134","_cell_guid":"e0a65dbd-947d-498e-a456-536c76140394","trusted":true},"cell_type":"markdown","source":"Examine training curves.","execution_count":null},{"metadata":{"_uuid":"29959c5e-6563-4541-94a2-ccfc937c67d6","_cell_guid":"0c144e8e-db45-4f61-9106-79a7d999d52c","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":"12866c7a-c659-4fac-b28d-77183dc31bed","_cell_guid":"8095d23f-afe8-4d8a-8465-5c678978feb4","trusted":true},"cell_type":"markdown","source":"## Validation ##\n\nCreate a confusion matrix.","execution_count":null},{"metadata":{"_uuid":"c95c96ef-58dc-4501-8f51-56888d20156e","_cell_guid":"27141176-3e54-45a0-a115-ce897a8199a2","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":"aba7129e-a036-4d8c-bb51-b7bb9e17533a","_cell_guid":"89845d63-e180-44fd-b605-f01e01b526cb","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":"b20b181a-bc18-4945-bd3c-0330b246dd5b","_cell_guid":"4167c3f7-7c76-4057-923a-6bbddc927ca2","trusted":true},"cell_type":"markdown","source":"Look at examples from the dataset, with true and predicted classes.","execution_count":null},{"metadata":{"_uuid":"f878d680-3557-4876-b380-517c3cb00d8c","_cell_guid":"bb8e9487-5a7a-48f6-bc96-638c078465a2","trusted":true},"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"b0e653bf-fdcc-42ee-b3d4-24bc80042ca8","_cell_guid":"e61528fc-c609-4bbe-8b49-6296cc710568","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":"71b85a80-400b-448d-9b0b-a610c5f773dc","_cell_guid":"b1ab160b-9896-48d9-9436-3c7ff47f8fff","trusted":true},"cell_type":"markdown","source":"## Test Predictions ##\n\nCreate predictions to submit to the competition.","execution_count":null},{"metadata":{"_uuid":"05496bfb-3486-4d9c-b3d7-7d445f73e9a9","_cell_guid":"b160a6ed-9cc4-412c-b3bb-10d6c45efda2","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":"79cf37d6-10a5-49c4-a080-1e0d7d53ddb5","_cell_guid":"263ce890-2ff0-4bfd-b84a-d821611ae56c","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":{"_uuid":"ca86c2a8-7961-4f28-a7b5-aefdb69ad845","_cell_guid":"139021cd-47c4-44dc-a820-351c39e3b911","trusted":true},"cell_type":"markdown","source":"---\n**[Deep Learning Home Page](https://www.kaggle.com/learn/deep-learning)**\n\n\n\n\n\n*Have questions or comments? Visit the [Learn Discussion forum](https://www.kaggle.com/learn-forum) to chat with other Learners.*","execution_count":null}],"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}