{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"#note that training was done on the following notebook using different hyperparameters and different efficientnet bases\n#https://www.kaggle.com/danielwijaya/cassava-v1?scriptVersionId=50195139\n\n# 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)\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\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        pass\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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nfrom functools import partial\nfrom sklearn.model_selection import train_test_split\nimport re\nimport random\nimport sys\nsys.path.append('/kaggle/input/efficient-net/')\nsys.path.append('/kaggle/input/kerasapplications/')\nimport keras_applications\nimport efficientnet.keras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#load pre-trained models\nmodel_15 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB6_based(15).h5')\nmodel_17 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB4_based(17).h5')\n##model_18 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(18).h5')\n##model_19 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(19).h5')\n##model_20 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(20).h5')\nmodel_21 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(21).h5')\n##model_24 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB4_based(24).h5')\n##model_25 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(25).h5')\n#model_26 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(26).h5')\nmodel_28_1 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(28-1).h5')\n#model_28_2 = tf.keras.models.load_model('../input/cassava-trained/EfficientNetB5_based(28-2).h5')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\nprint(test_df)\nAUTOTUNE = tf.data.experimental.AUTOTUNE\nGCS_PATH = '../input/cassava-leaf-disease-classification'#KaggleDatasets().get_gcs_path('cassava-leaf-disease-classification')\nBATCH_SIZE = 16*8#strategy.num_replicas_in_sync \nIMAGE_SIZE = [512,512]\nCLASSES = [\"1\", \"2\", \"3\", \"4\", \"5\"]\ndef dataset_sizes(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return(np.sum(n))\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH+\"/test_tfrecords/ld_test*.tfrec\")\nNUM_TEST_IMAGES = dataset_sizes(TEST_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def to_float32(image, label):\n    return tf.cast(image, tf.float32), label\n\n#load data\n\n# decode data \ndef decode_img(img):\n    img = tf.io.decode_jpeg(img, channels = 3)\n    img = tf.cast(img, tf.float32)/255.0\n    img = tf.reshape(img, [*IMAGE_SIZE, 3])\n    return img\n# read tfrecords\ndef read_tfrecord(example, labeled):\n    if labeled:\n        TFREC_FORMAT = {\n            \"image\": tf.io.FixedLenFeature([], tf.string), #[] is the shape (is just single value)\n            \"target\": tf.io.FixedLenFeature([], tf.int64)\n        }\n    else:\n        TFREC_FORMAT = {\n            \"image\": tf.io.FixedLenFeature([], tf.string),\n            \"image_name\": tf.io.FixedLenFeature([], tf.string)\n        }\n    example = tf.io.parse_single_example(example, TFREC_FORMAT)\n    img = decode_img(example[\"image\"])\n    if labeled:\n        label = tf.cast(example[\"target\"], tf.int32)\n        return(img, label)\n    else:\n        idNum = example[\"image_name\"]\n        return(img, idNum)\n# load dataset\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, num_parallel_reads = AUTOTUNE) #automatically interleaves reads from multiple files\n    dataset.with_options(ignore_order) #use data as it streams in\n    dataset = dataset.map(partial(read_tfrecord, labeled = labeled), num_parallel_calls = AUTOTUNE)\n    return dataset\ndef get_test_data(ordered = False): #for outputting actual test data, will need to specify ordered = True\n    dataset = load_dataset(filenames = TEST_FILENAMES, labeled = False, ordered = ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_data(ordered=True) \ntest_ds = test_ds.map(to_float32)\n\ntesting_dataset = get_test_data()\ntesting_dataset = testing_dataset.unbatch().batch(1)\n\nprint('Computing predictions...')\ntest_images_ds = testing_dataset\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprob1 = model_15.predict(test_images_ds)\nprob2 = model_17.predict(test_images_ds)\n##prob3 = model_18.predict(test_images_ds)\n#prob4 = model_19.predict(test_images_ds)\n#prob5 = model_20.predict(test_images_ds)\nprob6 = model_21.predict(test_images_ds)\n##prob7 = model_24.predict(test_images_ds)\n##prob8 = model_25.predict(test_images_ds)\n#prob9 = model_26.predict(test_images_ds)\nprob10 = model_28_1.predict(test_images_ds)\n#prob11 = model_28_2.predict(test_images_ds)\nprobabilities = 0.25*(prob1+prob2+prob6+prob10)\npredictions = np.argmax(probabilities, axis = -1)\nprint(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Generating submission.csv file...')\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') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='image_id,label', comments='')","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}