{"cells":[{"metadata":{"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":{"trusted":true},"cell_type":"code","source":"from petal_helper import *\nfrom tensorflow.keras import layers\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nfrom tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, LearningRateScheduler","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Create Distribution Strategy ##","execution_count":null},{"metadata":{"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":{},"cell_type":"markdown","source":"## Loading the Competition Data ##","execution_count":null},{"metadata":{"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":{"trusted":true},"cell_type":"code","source":"# check if the pixel values are in `[0,1]`.\nimage_batch, labels_batch = next(iter(ds_train))\nfirst_image = image_batch[0]\n\nprint(np.min(first_image), np.max(first_image)) ","execution_count":null,"outputs":[]},{"metadata":{},"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":{"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":{},"cell_type":"markdown","source":"Examine the shape of the data.","execution_count":null},{"metadata":{"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":{"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":{},"cell_type":"markdown","source":"Peek at training data.","execution_count":null},{"metadata":{"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":{},"cell_type":"markdown","source":"## Define Model #","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# BATCH_SIZE = 128 * strategy.num_replicas_in_sync\n# WARMUP_EPOCHS = 3\n# WARMUP_LEARNING_RATE = 1e-4 * strategy.num_replicas_in_sync\n# EPOCHS = 30\n# LEARNING_RATE = 3e-5 * strategy.num_replicas_in_sync\n# HEIGHT = 512\n# WIDTH = 512\n# CHANNELS = 3\n# N_CLASSES = 104\n# ES_PATIENCE = 6\n# RLROP_PATIENCE = 3\n# DECAY_DROP = 0.3\n\n# model_path = 'DenseNet201_%sx%s.h5' % (HEIGHT, WIDTH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def create_model(input_shape, N_CLASSES):\n#     base_model = tf.keras.applications.DenseNet201(weights='imagenet', \n#                                           include_top=False,\n#                                           input_shape=input_shape)\n\n#     base_model.trainable = False # Freeze layers\n#     model = tf.keras.Sequential([\n#         base_model,\n#         layers.GlobalAveragePooling2D(),\n#         layers.Dense(N_CLASSES, activation='softmax')\n#     ])\n    \n#     return model","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# **Warmup top layers**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\n#     model = create_model((512, 512, 3), N_CLASSES)\n    \n# metric_list = ['sparse_categorical_accuracy']\n\n# optimizer = tf.keras.optimizers.Adam(lr=WARMUP_LEARNING_RATE)\n# model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=metric_list)\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n# warmup_history = model.fit(x=ds_train, \n#                            steps_per_epoch=STEPS_PER_EPOCH, \n#                            validation_data=ds_valid,\n#                            epochs=WARMUP_EPOCHS, \n#                            verbose=2).history","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Schedule Learning Rate","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# LR_START = 0.00000001\n# LR_MIN = 0.000001\n# LR_MAX = LEARNING_RATE\n# LR_RAMPUP_EPOCHS = 3\n# LR_SUSTAIN_EPOCHS = 0\n# LR_EXP_DECAY = .8\n\n# def lrfn(epoch):\n#     if epoch < LR_RAMPUP_EPOCHS:\n#         lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n#     elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n#         lr = LR_MAX\n#     else:\n#         lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n#     return lr\n    \n# rng = [i for i in range(EPOCHS)]\n# y = [lrfn(x) for x in rng]\n\n# sns.set(style=\"whitegrid\")\n# fig, ax = plt.subplots(figsize=(20, 6))\n# plt.plot(rng, y)\n# print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Fine tune all layers","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# for layer in model.layers:\n#     layer.trainable = True # Unfreeze layers\n\n# checkpoint = ModelCheckpoint(model_path, monitor='val_loss', mode='min', save_best_only=True)\n# es = EarlyStopping(monitor='val_loss', mode='min', patience=ES_PATIENCE, \n#                    restore_best_weights=True, verbose=1)\n# lr_callback = LearningRateScheduler(lrfn, verbose=1)\n\n# callback_list = [checkpoint, es, lr_callback]\n\n# optimizer = tf.keras.optimizers.Adam(lr=LEARNING_RATE)\n# model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=metric_list)\n# model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = model.fit(x=ds_train, \n#                     steps_per_epoch=STEPS_PER_EPOCH, \n#                     validation_data=ds_valid,\n#                     callbacks=callback_list,\n#                     epochs=EPOCHS, \n#                     verbose=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Transfer Learning\n\nUnfreeze last block and train.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_model = tf.keras.applications.DenseNet201(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    for layer in pretrained_model.layers[:703]:\n        layer.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.MaxPool2D((2,2) , strides = 2),\n#         tf.keras.layers.Flatten(),\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":{},"cell_type":"markdown","source":"## Train Model ##","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.callbacks import ReduceLROnPlateau\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience = 3, verbose=1,factor=0.6, min_lr=0.000001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 with TPU on\nBATCH_SIZE = 128 * strategy.num_replicas_in_sync\n\n# Define training epochs for committing/submitting. (TPU on)\nEPOCHS = 50\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    callbacks = [learning_rate_reduction]\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Examine training curves.","execution_count":null},{"metadata":{"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":{},"cell_type":"markdown","source":"## Validation ##\n\nCreate a confusion matrix.","execution_count":null},{"metadata":{"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":{"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":{},"cell_type":"markdown","source":"Look at examples from the dataset, with true and predicted classes.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","execution_count":null,"outputs":[]},{"metadata":{"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":{},"cell_type":"markdown","source":"## Test Predictions ##\n\nCreate predictions to submit to the competition.","execution_count":null},{"metadata":{"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":{"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":{"trusted":true},"cell_type":"code","source":"","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}