{"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)\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\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":"# import eda packages\n\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport os\nimport tensorflow as tf\nfrom functools import partial\n\n# import deep learning packages\n\nfrom keras.layers import Dense, Dropout, Input, MaxPool2D, GlobalAveragePooling2D, ZeroPadding2D, Conv2D, Flatten, BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom tensorflow.keras.applications import EfficientNetB6, VGG16, ResNet101, ResNet50, EfficientNetB0\nfrom keras.optimizers import Adam\n!pip install tensorflow_addons\nfrom tensorflow_addons.optimizers import Yogi\nfrom keras import Model, regularizers\nfrom tensorflow.keras import layers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#navigate to the correct folder for training data\n%cd /kaggle/input/cassava-leaf-disease-classification/train_tfrecords","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom functools import partial\nimport matplotlib.pyplot as plt\nBATCH_SIZE = 32\nIMAGE_SIZE = (512, 512)\nTRAIN_FILENAMES = ['ld_train13-1338.tfrec',\n 'ld_train15-1327.tfrec',\n 'ld_train07-1338.tfrec',\n 'ld_train04-1338.tfrec',\n 'ld_train05-1338.tfrec',\n 'ld_train00-1338.tfrec',\n 'ld_train08-1338.tfrec',\n 'ld_train06-1338.tfrec',\n 'ld_train03-1338.tfrec',\n 'ld_train09-1338.tfrec',\n 'ld_train02-1338.tfrec',\n 'ld_train11-1338.tfrec',\n 'ld_train01-1338.tfrec',\n 'ld_train12-1338.tfrec']\nVALIDATION_FILENAMES = ['ld_train14-1338.tfrec', 'ld_train10-1338.tfrec'] ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Code from https://keras.io/examples/keras_recipes/tfrecord/\n\ndef decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    image = tf.cast(image, tf.float32)\n    image = tf.image.resize(image, [224, 224])\n    return image\n\ndef read_tfrecord(example, labeled):\n    tfrecord_format = (\n        {\n            \"image\": tf.io.FixedLenFeature([], tf.string),\n            \"target\": tf.io.FixedLenFeature([], tf.int64),\n        }\n        if labeled\n        else {\"image\": tf.io.FixedLenFeature([], tf.string),}\n    )\n    example = tf.io.parse_single_example(example, tfrecord_format)\n    image = decode_image(example[\"image\"])\n    if labeled:\n        label = tf.cast(example[\"target\"], tf.int32)\n        return image, label\n    return image\n\ndef load_dataset(filenames, labeled=True):\n    ignore_order = tf.data.Options()\n    ignore_order.experimental_deterministic = False  # disable order, increase speed\n    dataset = tf.data.TFRecordDataset(\n        filenames\n    )  # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(\n        ignore_order\n    )  # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(\n        partial(read_tfrecord, labeled=labeled), num_parallel_calls=1\n    )\n    # returns a dataset of (image, label) pairs if labeled=True or just images if labeled=False\n    return dataset\n\n\ndef get_dataset(filenames, labeled=True):\n    dataset = load_dataset(filenames, labeled=labeled)\n    dataset = dataset.shuffle(100)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(buffer_size=AUTOTUNE)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#create the train and validation sets\nAUTOTUNE = tf.data.AUTOTUNE\ntrain_dataset = get_dataset(TRAIN_FILENAMES)\nvalidation_dataset = get_dataset(VALIDATION_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import keras, tensorflow\nfrom keras.models import load_model\n\nmodels = list()\n%cd ~\n\nmodel1 = tensorflow.keras.models.load_model(\"/kaggle/input/model-eff/model_unfrozen_tf\")\nmodel2 = tensorflow.keras.models.load_model(\"/kaggle/input/model-res/model2_unfrozen_tf\")\nmodel3 = tensorflow.keras.models.load_model(\"/kaggle/input/model-vgg/model3_unfrozen_tf\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%cd /kaggle/input/cassava-leaf-disease-classification/test_tfrecords/\n\nTEST_FILENAMES = ['ld_test00-1.tfrec'] \ntest_dataset = load_dataset(TEST_FILENAMES, labeled = False)\ntest_dataset = test_dataset.shuffle(100)\ntest_dataset = test_dataset.batch(BATCH_SIZE)\ntest_dataset = test_dataset.prefetch(buffer_size=AUTOTUNE)\n\nmodels = list()\n\nmodels.append(model1)\nmodels.append(model2)\nmodels.append(model3)\n\npreds = []\n\nsample_sub = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/sample_submission.csv')\n\nfor image in sample_sub.image_id:\n    img = keras.preprocessing.image.load_img('/kaggle/input/cassava-leaf-disease-classification/test_images/' + image, target_size = (224, 224))\n    yhats = [model.predict(test_dataset) for model in models]\n    yhats = np.array(yhats)\n    summed = np.sum(yhats, axis=0)\n    preds.append(np.argmax(summed, axis=1))\n\nmy_submission = pd.DataFrame({'image_id': sample_sub.image_id, 'label': preds})\nmy_submission.to_csv('/kaggle/working/submission.csv', index=False)","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}