{"cells":[{"metadata":{"_uuid":"0246c2c7-02a2-47dd-ada8-67141d4dd786","_cell_guid":"b3d9fd9f-27dc-46c1-b16e-a8b453c8ae68","trusted":true},"cell_type":"markdown","source":"**[Deep Learning Home Page](https://www.kaggle.com/learn/deep-learning)**\n\n---","execution_count":null},{"metadata":{"_uuid":"49b298e9-e2ae-4d31-b049-2faacb9710fc","_cell_guid":"380d4a4d-ab61-4ef2-a24e-c6bfbd794e05","trusted":true},"cell_type":"markdown","source":"Submission to the [**Petals to the Metal**](https://www.kaggle.com/c/tpu-getting-started) competition.","execution_count":null},{"metadata":{"_uuid":"21345407-6b71-45b4-972e-ad1be5f9d95a","_cell_guid":"63483856-b290-40f9-b9a3-8f173e495bc5","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":"aa8f4688-373a-4d18-80a2-f4f52a1cc0c5","_cell_guid":"c0fc63fa-0316-4a97-964f-2d70c74bf7b7","trusted":true},"cell_type":"markdown","source":"\n## Load Helper Functions ##","execution_count":null},{"metadata":{"_uuid":"3edb7ada-16f4-4661-9f51-9d4bca09730f","_cell_guid":"b238dfad-c7a0-42d4-8a22-a61c71e785b3","trusted":true},"cell_type":"code","source":"from petal_helper import *","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"327676f2-e7b5-43b5-bcc0-8d7a6147f16b","_cell_guid":"065fb2ba-30b7-497a-a062-4e03e0cba4ba","trusted":true},"cell_type":"markdown","source":"## Create Distribution Strategy ##","execution_count":null},{"metadata":{"_uuid":"b6de221f-3a7a-40ca-8427-a5237cb46e7a","_cell_guid":"f69897be-88e5-4a17-bcbc-e3d9a2c2259f","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":"dd2fb037-fcfc-42fa-9ec0-984a6220af4f","_cell_guid":"7f09705c-318c-492a-b1fc-0f77cf288e2d","trusted":true},"cell_type":"markdown","source":"## Loading the Competition Data ##","execution_count":null},{"metadata":{"_uuid":"4c620565-cf1d-4850-9695-ec0c5602a627","_cell_guid":"1c5db456-1080-44da-aa8c-ce08e3bd3985","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)\nds_train","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"1084a01a-ee9c-45d8-bf30-1a66dc9bfc1e","_cell_guid":"db9abd7b-def4-4654-9eb1-8ed7e8e79cfe","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":"eddf264a-7755-419f-bc20-6b533b7ef529","_cell_guid":"32bad332-ee29-4f63-896d-a3f5211305b3","trusted":true},"cell_type":"code","source":"print(\"Number of classes: {}\".format(len(CLASSES)))\n\nprint(\"First 15 classes, sorted alphabetically:\")\nfor name in sorted(CLASSES)[:15]:\n    print(name)\n\nprint (\"Number of training images: {}\".format(NUM_TRAINING_IMAGES))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"2af951bd-8455-4253-aed4-2759eac6d83b","_cell_guid":"c8454940-d3b0-4d40-90b9-5815dddda44d","trusted":true},"cell_type":"markdown","source":"Examine the shape of the data.","execution_count":null},{"metadata":{"_uuid":"c035cca4-c783-49fc-8275-8d83a044c490","_cell_guid":"f17f0787-d406-4333-a388-9a192db369b0","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":"588d583b-beb7-4fed-81ec-0f0acc632c9f","_cell_guid":"26fd9652-7b32-481c-af1b-6505b07e083a","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":"d6f281bf-aa54-4d57-bdd9-20e9282768a3","_cell_guid":"30138047-5056-436d-8b8b-203867a4fe6a","trusted":true},"cell_type":"markdown","source":"Peek at training data.","execution_count":null},{"metadata":{"_uuid":"d81047af-bb8e-495e-903e-923186c86342","_cell_guid":"42ca6265-001b-4147-bac4-941b9cd37ae3","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":"cba29cf2-2275-4ac7-865d-bed0da83ba08","_cell_guid":"4a2c11fd-d4cb-48d4-a27d-b6fa2cb4fc56","trusted":true},"cell_type":"markdown","source":"## Define Model #","execution_count":null},{"metadata":{"_uuid":"ba6450f5-e420-4a84-a317-8d000300ecde","_cell_guid":"7ef85084-c26a-44a1-ac25-c969a56ac0a0","trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.Xception(\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(512,activation = \"relu\"),\n        tf.keras.layers.Dropout(0.1),\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":"cb7b1272-3a9a-4096-978e-fa4cedbedab2","_cell_guid":"2fdc3e6f-a47b-41f3-b4bb-f61f03159f20","trusted":true},"cell_type":"markdown","source":"## Train Model ##","execution_count":null},{"metadata":{"_uuid":"1cba20a8-542c-4e95-bf4f-ce6a151e3241","_cell_guid":"d9ef1be6-7968-44b7-ad8a-a6c21b20ae40","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":"e9601b4c-94e0-49b7-9af3-1110cda87a6e","_cell_guid":"82e0e720-dcca-42ac-be9d-e5a10b9e2c63","trusted":true},"cell_type":"markdown","source":"Plot of training curves...","execution_count":null},{"metadata":{"_uuid":"a548f78f-94af-4adf-acda-cce3ff7b5272","_cell_guid":"1cf69676-c454-4961-9694-f5a3f697221b","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":"0de757fb-5979-4ee0-87cb-b43dd6ee16ee","_cell_guid":"41f9c84f-fb9a-49f2-ae16-3b2a22637e8e","trusted":true},"cell_type":"markdown","source":"## Validation ##\n\nCreate a confusion matrix.","execution_count":null},{"metadata":{"_uuid":"8f3ba84d-7919-4a06-8303-f122696449f1","_cell_guid":"b6308d4d-aaa3-4a58-be62-bc84bb18b020","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":"06dba250-755c-4d9d-b8e6-7773504b929e","_cell_guid":"7e741ad2-35dd-4151-8dc8-e86c056aeef9","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":"dbece53c-0f98-4cd6-8ca7-7e602b36ca8f","_cell_guid":"cea8e528-3ce5-46cf-a1d8-2c103c2b1334","trusted":true},"cell_type":"markdown","source":"Look at examples from the dataset, with true and predicted classes.","execution_count":null},{"metadata":{"_uuid":"33cbf96e-7bd5-4ec3-97e0-c571cbdc7828","_cell_guid":"5bff5657-9985-4f3e-a180-5068454fbaf6","trusted":true},"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"71d16b5d-97df-47cd-8fd6-43cb6683fdc9","_cell_guid":"a44980f8-bf95-4ca4-bf16-268e8e39b66d","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":"1fa1a022-b0a7-4a1e-a00a-f6a4247c034d","_cell_guid":"5f03b93f-b598-41bb-8107-21d76c3bab43","trusted":true},"cell_type":"markdown","source":"## Test Predictions ##\n\nCreate predictions to submit to the competition.","execution_count":null},{"metadata":{"_uuid":"e140ed23-b566-492d-9667-a8d5de176d62","_cell_guid":"233012e8-d2aa-4286-86a4-5150357227b1","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":"eedb574d-26f6-498d-864f-09cdb4d36e83","_cell_guid":"277aad56-a53d-4c04-9274-d093f93acd70","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":"e4567564-6787-477b-9888-786bf379be5a","_cell_guid":"eac8025f-e7bb-4ccc-8218-6ddd99f12862","trusted":true},"cell_type":"markdown","source":"","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}