{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Introduction"},{"metadata":{},"cell_type":"markdown","source":"Current methods produce unreliable results, raising false alarms. One reason for inaccuracy is the many different devices and processing combinations. Yet, detection models are trained on a homogeneous dataset. To increase accuracy, researchers must put data hidden within digital images “into the wild” (hence the name ALASKA) to mimic real world conditions."},{"metadata":{},"cell_type":"markdown","source":"In the competition, you’ll create an efficient and reliable method to detect secret data hidden within innocuous-seeming digital images. Rather than limiting the data source, these images have been acquired with as many as 50 different cameras (from smartphone to full-format high end) and processed in different fashions. Successful entries will include robust detection algorithms with minimal false positives."},{"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 efficientnet.tfkeras as efn\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nimport cv2\nimport matplotlib\nimport matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# EDA"},{"metadata":{"trusted":true},"cell_type":"code","source":"base_path = '/kaggle/input/alaska2-image-steganalysis/'\nalgorithm = ('Cover(Unaltered)', 'JMiPOD', 'UERD', 'JUNIWARD')\nfig, axes = plt.subplots(nrows=4, ncols=4, figsize = (11,11) )\nnp.random.seed(55)\nfor i,id in enumerate(np.random.randint(0,75001,4)):\n    id = '{:05d}'.format(id)    \n    cover_path = os.path.join(base_path, 'Cover', id + '.jpg')\n    jmipod_path = os.path.join(base_path, 'JMiPOD', id + '.jpg')\n    uerd_path = os.path.join(base_path, 'UERD', id + '.jpg')\n    juniward_path = os.path.join(base_path, 'JUNIWARD', id + '.jpg')\n    cover_img = plt.imread(cover_path)\n    jmipod_img = plt.imread(jmipod_path)\n    uerd_img = plt.imread(uerd_path)\n    juniward_img = plt.imread(juniward_path)\n    axes[i,0].imshow(cover_img)\n    axes[i,1].imshow(jmipod_img)\n    axes[i,2].imshow(uerd_img)\n    axes[i,3].imshow(juniward_img)\n    axes[i,0].set(ylabel=id+'.jpg')\n\nfor i,algo in enumerate(algorithm):\n    axes[0,i].set(title=algo) \nfor ax in axes.flat:\n    ax.set(xticks=[], yticks=[])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cover_hist = {}\njmipod_hist = {}\nuerd_hist = {}\njuniward_hist = {}\ncolor = ('b','g','r')\nfor i,col in enumerate(color):\n    cover_hist[col] = cv2.calcHist([cover_img],[i],None,[256],[0,256])\n    jmipod_hist[col] = cv2.calcHist([jmipod_img],[i],None,[256],[0,256])\n    uerd_hist[col] = cv2.calcHist([uerd_img],[i],None,[256],[0,256])\n    juniward_hist[col] = cv2.calcHist([juniward_img],[i],None,[256],[0,256])\n    \nfig_hist, axes_hist = plt.subplots(nrows=2, ncols=2, figsize=(12,12))\nfor ax, hist, algo in zip(axes_hist.flat, [cover_hist, jmipod_hist, uerd_hist, juniward_hist], algorithm):\n    ax.plot(hist['r'], color = 'r', label='r')\n    ax.plot(hist['g'], color = 'g', label='g')\n    ax.plot(hist['b'], color = 'b', label='b')\n    ax.set(ylabel='# of pixels', xlabel='Pixel value(0-255)', title=algo)\n    ax.legend()\nfig_hist.subplots_adjust(wspace=0.4, hspace=0.3)\nfig_hist.suptitle('Histogram of a sample (' + id + '.jpg)', fontsize=20)\n    #     ax.xlim([0,256])\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, ax = plt.subplots(figsize=(10,10))\nax.plot(cover_hist['r'][50:80], color = 'c', label=algorithm[0])\nax.plot(jmipod_hist['r'][50:80], color = 'm', label=algorithm[1])\nax.plot(uerd_hist['r'][50:80], color = 'y', label=algorithm[2])\nax.plot(juniward_hist['r'][50:80], color = 'g', label=algorithm[3])\nax.legend()\nax.set_ylabel('# of pixels', fontsize=15) \nax.set_xlabel('Pixel value(50-80)', fontsize=15)\nax.xaxis.set(ticklabels=np.linspace(50,80,8, dtype=np.int))\nax.set_title('R-channel Histogram Compared (zoomed in)', fontsize=20)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig, axes = plt.subplots(nrows=4, ncols=4, figsize = (11,11) )\nnp.random.seed(55)\ndef disp_diff_img(alt, ref, ax, chnl=0):\n    diff = np.abs(alt.astype(np.int)-ref.astype(np.int)).astype(np.uint8)\n    ax.imshow(diff[:,:,chnl], vmin=0, vmax=np.amax(diff[:,:,chnl]), cmap='hot')\nfor i,id in enumerate(np.random.randint(0,75001,4)):\n    id = '{:05d}'.format(id)    \n    cover_path = os.path.join(base_path, 'Cover', id + '.jpg')\n    jmipod_path = os.path.join(base_path, 'JMiPOD', id + '.jpg')\n    uerd_path = os.path.join(base_path, 'UERD', id + '.jpg')\n    juniward_path = os.path.join(base_path, 'JUNIWARD', id + '.jpg')\n    cover_img = plt.imread(cover_path)\n    jmipod_img = plt.imread(jmipod_path)\n    uerd_img = plt.imread(uerd_path)\n    juniward_img = plt.imread(juniward_path)\n    axes[i,0].imshow(cover_img)\n    disp_diff_img(jmipod_img, cover_img, axes[i,1], 0)\n    disp_diff_img(uerd_img, cover_img, axes[i,2], 0)\n    disp_diff_img(juniward_img, cover_img, axes[i,3], 0)\n    axes[i,0].set(ylabel=id+'.jpg')\n\nfor i,algo in enumerate(algorithm):\n    axes[0,i].set(title=algo + 'diff') \nfor ax in axes.flat:\n    ax.set(xticks=[], yticks=[])\nplt.show()","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()\n\n# Configuration\nEPOCHS = 10\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","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":"np.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 = np.concatenate([jmipod, juniward, uerd])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_paths = append_path('Test')(sub.Id.values)\nneg_paths = append_path('Cover')(negatives[:30000])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = np.concatenate([pos_paths, neg_paths])\ntrain_labels = np.array([1] * len(pos_paths) + [0] * len(neg_paths))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths, valid_paths, train_labels, valid_labels = train_test_split(\n    train_paths, train_labels, test_size=0.15, random_state=2020)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Create Dataset objects\n"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"def 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_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)","execution_count":null,"outputs":[]},{"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        efn.EfficientNetB3(\n            input_shape=(512, 512, 3),\n            weights='imagenet',\n            include_top=False\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\n\nhistory = model.fit(\n    train_dataset, \n    epochs=EPOCHS, \n#     callbacks=[lr_schedule],\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":false},"cell_type":"code","source":"def display_training_curves(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.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":false},"cell_type":"code","source":"display_training_curves(\n    history.history['loss'], \n    history.history['val_loss'], \n    'loss', 211)\ndisplay_training_curves(\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":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":4}