{"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport tensorflow as tf\n\nDATA_DIR = '/kaggle/input/cassava-leaf-disease-classification/'\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nFILENAMES = tf.io.gfile.glob(DATA_DIR + \"/train_tfrecords/*.tfrec\")\nsplit_ind = int(0.9 * len(FILENAMES))\nTRAINING_FILENAMES, VALID_FILENAMES = FILENAMES[:split_ind], FILENAMES[split_ind:]\nCLASS_NAMES = pd.read_json(DATA_DIR + 'label_num_to_disease_map.json', typ='series')\nBATCH_SIZE = 16\nIMG_HEIGHT = 400\nIMG_WIDTH = 300\nIMAGE_SIZE = (IMG_HEIGHT, IMG_WIDTH)\n\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\n#import os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\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":{"trusted":true},"cell_type":"code","source":"print(tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"model = tf.keras.models.load_model('../input/cassava-checkpoint/cassava_model.h5')\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import re\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nTEST_FILENAMES = tf.io.gfile.glob(DATA_DIR + \"/test_tfrecords/*.tfrec\")\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from functools import partial\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.image.resize(image, [IMG_HEIGHT, IMG_WIDTH])\n    return image\n\ndef read_tfrecord(example, labeled):\n    feature_description = (\n        {\n            \"target\": tf.io.FixedLenFeature([], tf.int64),\n            \"image_name\": tf.io.FixedLenFeature([], tf.string),\n            \"image\": tf.io.FixedLenFeature([], tf.string),\n        }\n        if labeled\n        else {\"image_name\": tf.io.FixedLenFeature([], tf.string),\n              \"image\": tf.io.FixedLenFeature([], tf.string),}\n    )\n    example = tf.io.parse_single_example(example, feature_description)\n    image = decode_image(example[\"image\"])\n    image = tf.image.adjust_saturation( image, 0.3 )\n    image = tf.image.adjust_hue( image, -1 )\n    image = tf.image.adjust_contrast( image, 1 )\n    image = tf.image.adjust_brightness( image, 0.3 )\n    \n    if labeled:\n        \n        label = tf.cast(example[\"target\"], tf.int32)\n        \n        if  label == 0:\n            label = tf.convert_to_tensor([1,0,0,0,0])\n        elif label == 1:\n            label = tf.convert_to_tensor([0,1,0,0,0])\n        elif label == 2:\n            label = tf.convert_to_tensor([0,0,1,0,0])\n        elif label == 3:\n            label = tf.convert_to_tensor([0,0,0,1,0])\n        else:\n            label = tf.convert_to_tensor([0,0,0,0,1])\n        return image, label\n        \n    idnum = example[\"image_name\"]\n    return image, idnum\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False  # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(filenames, \n                                      num_parallel_reads=AUTOTUNE)  # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order)  # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(partial(read_tfrecord, \n                                  labeled=labeled), \n                          num_parallel_calls=AUTOTUNE)\n    # returns a dataset of (image, label) pairs if labeled=True or just images if labeled=False\n    return dataset\n\ndef get_test_dataset(filenames, labeled=False, ordered=True):\n    dataset = load_dataset(filenames, labeled=labeled, ordered=ordered)\n    dataset = dataset.prefetch(buffer_size=AUTOTUNE)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ntest_dataset = get_test_dataset(TEST_FILENAMES, labeled=False, ordered=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"probabilities = model.predict(test_dataset)\npredictions = tf.argmax(probabilities, axis=1)\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset_id = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_dataset_id.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', comments='')\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}