{"cells":[{"metadata":{},"cell_type":"markdown","source":"## About this kernel\n\nThis is the 3rd notebook I'm making using EfficientNet on TPUs. The full list:\n1. https://www.kaggle.com/xhlulu/flowers-tpu-concise-efficientnet-b7\n2. https://www.kaggle.com/xhlulu/plant-pathology-very-concise-tpu-efficientnet\n\nIf you want to dive deeper in the `tf.data.Dataset` way of building your input pipeline, please check out [this tutorial by Martin](https://codelabs.developers.google.com/codelabs/keras-flowers-data/#0), which I followed in order to build this kernel.\n\n### References\n\n* https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n* https://codelabs.developers.google.com/codelabs/keras-flowers-data/#0"},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"cell_type":"code","source":"import math, re, os\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nimport keras\nimport efficientnet.tfkeras as efn\nfrom keras.callbacks import ModelCheckpoint\n\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## TPU Strategy and other configs "},{"metadata":{"trusted":true},"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    # TPU detection. No parameters necessary if TPU_NAME environment variable is\n    # set: this is always the case on Kaggle.\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    # Default distribution strategy in Tensorflow. Works on CPU and single GPU.\n    strategy = tf.distribute.get_strategy()\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# For tf.dataset\nAUTO = tf.data.experimental.AUTOTUNE\n\n# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('alaska2-image-steganalysis')\n\n# Configuration\nEPOCHS = 50\nBATCH_SIZE = 100","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load label and paths"},{"metadata":{"trusted":true},"cell_type":"code","source":"def append_path(pre):\n    return np.vectorize(lambda file: os.path.join(GCS_DS_PATH, pre, file))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/alaska2-image-steganalysis/sample_submission.csv')\ntrain_filenames = np.array(os.listdir(\"/kaggle/input/alaska2-image-steganalysis/Cover/\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt     \n\nnp.random.seed(0)\npositives = train_filenames.copy()\nnegatives = train_filenames.copy()\nnp.random.shuffle(positives)\nnp.random.shuffle(negatives)\n\njmipod = append_path('JMiPOD')(positives[:10000])\njuniward = append_path('JUNIWARD')(positives[10000:20000])\nuerd = append_path('UERD')(positives[20000:30000])\n\npos_paths_uerds = np.concatenate([uerd])\npos_paths_jmipod = np.concatenate([jmipod])\npos_paths_juniward = np.concatenate([juniward])\n\ndef decode_image(filename, label=None, image_size=(512, 512)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_jpeg(bits, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.image.resize(image, image_size)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\n\ndef data_augment(image, label=None):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\n\npos_paths = np.concatenate([jmipod, juniward, uerd])\ntest_paths = append_path('Test')(sub.Id.values)\nneg_paths = append_path('Cover')(negatives[:30000])\n\ntrain_paths = np.concatenate([pos_paths, neg_paths])\ntrain_labels = np.array([1] * len(pos_paths) + [0] * len(neg_paths))\n\ntrain_paths, valid_paths, train_labels, valid_labels = train_test_split(\n    train_paths, train_labels, test_size=0.15, random_state=2020)\n\ntrain_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((train_paths, train_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    .cache()\n    .repeat()\n    .shuffle(1024)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((valid_paths, valid_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(test_paths)\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n)\n\n'''model = keras.models.load_model('../input/vgg16wotrans/VGG16WoTrans.h5')\n\nfor inter_images, inter_labels in valid_dataset.take(1):\n    images = inter_images.numpy()\n    labels = inter_labels.numpy()\n\ny_pred = model.predict(images)\ncr = metrics.classification_report(labels, y_pred.round())\ncm = metrics.confusion_matrix(labels, y_pred.round())\nprint(cr)\nprint(cm)\nax= plt.subplot()\nsns.heatmap(cm, annot=True, ax = ax,cmap='BuPu'); #annot=True to annotate cells\n# labels, title and ticks\nax.set_xlabel('Predicted labels');ax.set_ylabel('True labels'); \nax.set_title('Confusion Matrix'); \nax.xaxis.set_ticklabels(['Stego', 'Cover']); ax.yaxis.set_ticklabels([ 'Stego','Cover']);'''","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Create Dataset objects\n\nA `tf.data.Dataset` object is needed in order to run the model smoothly on the TPUs. Here, I heavily trim down [my previous kernel](https://www.kaggle.com/xhlulu/flowers-tpu-concise-efficientnet-b7), which was inspired by [Martin's kernel](https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu)."},{"metadata":{},"cell_type":"markdown","source":"## Modelling"},{"metadata":{},"cell_type":"markdown","source":"### Helper Functions"},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.000075, \n               lr_min=0.000001, lr_rampup_epochs=20, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\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    return lrfn","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Load Model into TPU"},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.Sequential([\n        tf.keras.applications.VGG16(\n            include_top=False,\n            weights=None,\n            input_shape=(512, 512, 3)\n        ),\n        L.GlobalAveragePooling2D(),\n        L.Dense(1, activation='sigmoid')\n    ])\n        \n    model.compile(\n        optimizer='adam',\n        loss = 'binary_crossentropy',\n        metrics=['accuracy']\n    )\n    model.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Start training"},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"# lrfn = build_lrfn()\n# lr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nSTEPS_PER_EPOCH = train_labels.shape[0] // BATCH_SIZE\ncheckpoint = ModelCheckpoint(\"best_model.hdf5\", monitor='accuracy', verbose=1,\n    save_best_only=True, mode='auto', period=1)\n\nhistory = model.fit(\n    train_dataset, \n    epochs=EPOCHS, \n    callbacks=[checkpoint],\n    verbose = 1, \n    steps_per_epoch=STEPS_PER_EPOCH,\n    validation_data=valid_dataset\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"model.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Evaluation"},{"metadata":{},"cell_type":"markdown","source":"Unhide below to see helper function `display_training_curves`:"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def display_training_curves_acc(training, validation, title, subplot):\n    \"\"\"\n    Source: https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n    \"\"\"\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    ax.set_ylim(0.30, 1.0)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'validation'])\ndef display_training_curves_loss(training, validation, title, subplot):\n    \"\"\"\n    Source: https://www.kaggle.com/mgornergoogle/getting-started-with-100-flowers-on-tpu\n    \"\"\"\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.30,1.0)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'validation'])","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"display_training_curves_loss(\n    history.history['loss'], \n    history.history['val_loss'], \n    'loss', 211)\ndisplay_training_curves_acc(\n    history.history['accuracy'], \n    history.history['val_accuracy'], \n    'accuracy', 212)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"'''sub.Label = model.predict(test_dataset, verbose=1)\nsub.to_csv('submission.csv', index=False)\nsub.head()'''","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}