{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport os\n# using python csv library for writing results\nimport csv\n# loading data in windows environment\nimport pathlib\nimport re\nprint (tf.__version__)\nfrom kaggle_datasets import KaggleDatasets\nAUTO = tf.data.experimental.AUTOTUNE\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n# Loading Test Files from the Competition Dataset\nTEST_NAMES = tf.io.gfile.glob(\"../input/cassava-leaf-disease-classification/test_tfrecords/*.tfrec\")\n\n# Helper Function\ndef mapping_image_name(dat):\n    # Extracting Image Content and Name from dataset\n    TFREC_MAP = {\"image\": tf.io.FixedLenFeature([], tf.string),\n                 \"image_name\": tf.io.FixedLenFeature([], tf.string),\n                }\n    # Parsing the Extracted Data\n    parsed_dat = tf.io.parse_single_example(dat, TFREC_MAP)\n    # Decoding Image from Extracted Data\n    image = tf.io.decode_jpeg(parsed_dat['image'], channels=3)\n    # Normalizing the Image Data\n    image = tf.cast(image/255, dtype=tf.float32)\n    # Loading the Image Target Label\n    target = parsed_dat['image_name']\n    # Returning the tuple\n    return image, target\n\n# Define the Image Height\nIMG_HEIGHT = 386\n# Define the Image Width\nIMG_WIDTH = 386\n\nT_NAMES=[]\nIMG=[]\n\n# Loading the Dataset\nTEST_DATA = tf.data.TFRecordDataset(TEST_NAMES, num_parallel_reads=AUTO)\n# Loading the Test Data\nT_DATA = TEST_DATA.map(mapping_image_name)\n\n# Define the Data Augmentation\ndata_augmentation = tf.keras.Sequential([\n  # Random Flip the Image\n  tf.keras.layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\"),\n  # Random Rotating the Image\n  tf.keras.layers.experimental.preprocessing.RandomRotation(0.2),\n  #tf.keras.layers.experimental.preprocessing.RandomZoom(0.1),\n])\n\n# Helper Function for Extracting Image Content\ndef mapping_image(dat):\n    TFREC_MAP = {\"image\": tf.io.FixedLenFeature([], tf.string)}\n    parsed_dat = tf.io.parse_single_example(dat, TFREC_MAP)\n    image = tf.io.decode_image(parsed_dat['image'], channels=3)\n    image = tf.cast(image/255, dtype=tf.float32)\n    return image\n\n# Helper Function for Extracting Image ID\ndef mapping_id(dat):\n    TFREC_MAP = {\"target\": tf.io.FixedLenFeature([], tf.int64)}\n    parsed_dat = tf.io.parse_single_example(dat, TFREC_MAP)\n    image_id = parsed_dat['target']\n    image_id = tf.cast(image_id, dtype=tf.int32)\n    return image_id\n\n# Helper Function for Extracting Image Name\ndef mapping_name(dat):\n    TFREC_MAP = {\"image_name\": tf.io.FixedLenFeature([], tf.string)}\n    parsed_dat = tf.io.parse_single_example(dat, TFREC_MAP)\n    image_name = parsed_dat['image_name']\n    return image_name\n\n\n\nimport os\n\n# Results list for submission\nRESULTS = []\n\n# Getting predictions\n\n# Loading the Pretrained Model from Dataset\n# The pretrained model code is defined in another file\nkaggle_model = tf.keras.models.load_model('../input/cassava/kaggle_cassava_model_tpu_V20.h5')\n\n# Loading the Image and Label for Prediction\nfor image, label in T_DATA:\n    # Resized the Testing Image\n    re_image = tf.image.resize_with_pad(image, IMG_HEIGHT, IMG_WIDTH, method=tf.image.ResizeMethod.BICUBIC, antialias=False)\n    # Load Image into List\n    IMG.append(re_image)\n    # Convert List into Tensor Object\n    img = tf.convert_to_tensor(IMG, dtype=tf.float32)\n    # Checking the Image Shape\n    print (img.shape)\n    # Using the Model to predict\n    predict = kaggle_model.predict(img)\n    # Loading the Maximum Probability\n    V = tf.math.argmax(predict[0]).numpy()\n    print (V)\n    # Loading the result into list\n    RESULTS.append(V)\n    # Loading Image Name\n    T_NAMES.append(label.numpy().decode('utf-8'))\n    # Clear Image List\n    IMG=[]\n\n#preds = kaggle_model.predict(DATA)\n\n#preds = model.predict(IMG[0])\n\n#for dat in preds:\n    #print (dat)\n    #V = tf.math.argmax(dat).numpy()\n    #RESULTS.append(V)\n\n# Checking the Prediction Results\nprint (RESULTS)\n# Checking the Image Names\nprint (T_NAMES)\n\n# Prediction Submission\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([T_NAMES, RESULTS]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='image_id,label',\n    comments='',\n)\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","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}