{"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\nfor 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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport seaborn as sb\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imread\nimport cv2","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Problem statement\n  Casava has few types of diseases. The goal is to identify the __type__ of disease based on casava leaf image.\n  \n  ## Data  \n- __label_num_to_disease_mapping__: Contains the label name for the disease.\n- __train.csv__ : This contains image file name and correspoinding label id.\n- __train_images__ : folder contains train images\n- __test_images__ : folder contains test images\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Set up directory paths\nbase_path='/kaggle/input/cassava-leaf-disease-classification/'\ntrain_ds_path='/kaggle/input/cassava-leaf-disease-classification/train_images'\ntest_ds_path='/kaggle/input/cassava-leaf-disease-classification/test_images'\ntrain_label = os.path.join(base_path, 'train.csv')\ntrain_images_path=os.path.join(train_ds_path,'images/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Show details of label - Types of diseases\npd.read_json(os.path.join(base_path,'label_num_to_disease_map.json'),\n             orient='index', typ='frame')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load the train_ds csv file\ntrain_ds = pd.read_csv(filepath_or_buffer=train_label)\ntrain_ds.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check unique labels and ensure that they map to json files - 0-4\nprint(train_ds.nunique(axis=0))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The above confirms that there are 21398 (starts with 0) images with 5 labels.\nLet's see how what are most prevelant disease types"},{"metadata":{"trusted":true},"cell_type":"code","source":"count_by_label=train_ds.groupby(\"label\")['label'].count()\nprint('Count By Label \\n',count_by_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.sort(pd.unique(train_ds[\"label\"]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = {\"Id\": np.sort(pd.unique(train_ds[\"label\"])),\n          \"count\": np.array(count_by_label)}\n\npercenatge_by_label = pd.DataFrame(data=labels)\npercenatge_by_label['%age']=\\\n    percenatge_by_label['count']*100/percenatge_by_label['count'].sum()\npercenatge_by_label=percenatge_by_label.drop(columns=['count'])\n#percenatge_by_label.drop(labels=['count'])\npercenatge_by_label","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This shows that labels are not equally distributed and that disease type - __Cassava Mosaic Disease (CMD)__ seems to be more common in traning set. \n\nLet's check as bar graph- count, pie as % distribution and bar as % distribution"},{"metadata":{"trusted":true},"cell_type":"code","source":"sb.set_style(\"whitegrid\")\nfig,ax = plt.subplots(figsize=(10,6))\nax.set_title(\"Disease type by count\", fontsize=15)\nax.set_xlabel(\"Disease ID\")\nax.set_ylabel(\"Count\")\n\nsb.barplot(x=np.sort(pd.unique(train_ds[\"label\"])),\n           y=count_by_label, dodge=False )\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The chart shows the magnitude by count which can be difficult to understand. Let's check this via percentage. Let's use the one of the controversial charts here - Pei chart."},{"metadata":{"trusted":true},"cell_type":"code","source":"percenatge_by_label=percenatge_by_label.astype({\"Id\":str})\npercenatge_by_label.dtypes\nfig,(ax1, ax2)  = plt.subplots(nrows=1, ncols=2, figsize=(12,5))\n\nax1.set_title('Disease type by %age -pie')\nax1.pie(x=percenatge_by_label['%age'],\n         data=percenatge_by_label,\n        autopct=\"%.2f%%\", \n        #explode=[0.05]*4, \n        labels=percenatge_by_label['Id'],\n        pctdistance=0.5)\nplt.subplot(1,2,2)\nplt.title('Disease type by %age - bar')\nsb.barplot(x=percenatge_by_label['Id'], \ny=percenatge_by_label['%age'])\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"#### Let's look at 3 image of each type"},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\ndef get_top_image_labelId(label_id, num_of_images):\n    files = train_ds['path'].where(train_ds['label'] == label_id).dropna().head(num_of_images)\n    files_as_list = np.array(files)\n    return files_as_list\n\ndef display_image(label_id, num_of_images, nrows, ncols):\n    file_list = get_top_image_labelId(label_id,num_of_images)\n    title = \"Images for Label Id \", str(label_id)\n\n    plt.subplots(figsize=(5,5))\n    for i in range(nrows * ncols):\n        plt.subplot(nrows,ncols,i+1)# the number of images in the grid is 5*5 (25)\n\n        plt.axis('off')\n        plt.suptitle(title)\n        img = imread(file_list[i])\n        plt.imshow(img)\n    plt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ntrain_ds['path'] = train_ds_path +\"/\"+ train_ds['image_id']\ntrain_ds.head()\nfor i in range(5):\n    display_image(i,6,2,3)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds.head()\nimg = train_ds['path'][29]\nimg=cv2.imread(img)\nimg.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"#### Image height, width and channels(RGB) ==> 600 X 800 X 3\n\nCreate train and test labels"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_ds_path","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import models, layers\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\n\nBATCH_SIZE = 8\nSTEPS_PER_EPOCH = len(train_ds)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train_ds)*0.2 / BATCH_SIZE\nEPOCHS = 15\nTARGET_SIZE = 64\n\ntrain_datagen = ImageDataGenerator(validation_split = 0.2,\n                                     preprocessing_function = None,\n                                     rotation_range = 45,\n                                     zoom_range = 0.2,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'nearest',\n                                     shear_range = 0.1,\n                                     height_shift_range = 0.1,\n                                     width_shift_range = 0.1)\n\n#%%\n\ntrain_ds.label = train_ds.label.astype(str)\ntrain_generator = train_datagen.flow_from_dataframe(train_ds,\n                         directory = os.path.join(\"/kaggle/input/cassava-leaf-disease-classification\", \"train_images\"),\n                         subset = \"training\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")\n\n\nvalidation_datagen = ImageDataGenerator(validation_split = 0.2)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(train_ds,\n                         directory = os.path.join(\"/kaggle/input/cassava-leaf-disease-classification\", \"train_images\"),\n                         subset = \"validation\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.optimizers import Adam\ndef create_model():\n    conv_base = EfficientNetB0(include_top = False, weights = None,\n                               input_shape = (TARGET_SIZE, TARGET_SIZE, 3))\n    model = conv_base.output\n    model = layers.GlobalAveragePooling2D()(model)\n    model = layers.Dense(5, activation = \"softmax\")(model)\n    model = models.Model(conv_base.input, model)\n\n    model.compile(optimizer = Adam(lr = 0.001),\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"acc\"])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Our EfficientNet CNN has %d layers' %len(model.layers))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_save = ModelCheckpoint('./EffNetB0_512_8_best_weights.h5',\n                             save_best_only = True,\n                             save_weights_only = True,\n                             monitor = 'val_loss',\n                             mode = 'min', verbose = 1)\nearly_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001,\n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3,\n                              patience = 2, min_delta = 0.001,\n                              mode = 'min', verbose = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 32\nSTEPS_PER_EPOCH = len(train_ds)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train_ds)*0.2 / BATCH_SIZE\nEPOCHS = 10\nTARGET_SIZE = 128\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_generator,\n    validation_steps = VALIDATION_STEPS,\n    callbacks = [model_save, early_stop, reduce_lr]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import DenseNet201\nfrom tensorflow.keras.optimizers import Ftrl\ndef create_model_DenseNet():\n    conv_base = DenseNet201(include_top = False, weights = None,\n                               input_shape = (TARGET_SIZE, TARGET_SIZE, 3))\n    model = conv_base.output\n    model = layers.GlobalAveragePooling2D()(model)\n    model = layers.Dense(5, activation = \"softmax\")(model)\n    model = models.Model(conv_base.input, model)\n\n    model.compile(optimizer = Ftrl(lr = 0.001,\n                                   learning_rate_power= -0.3,\n                                   initial_accumulator_value=0,\n                                   l1_regularization_strength=0,\n                                    l2_regularization_strength=0.001,\n                                    name=\"Ftrl\",\n                                    l2_shrinkage_regularization_strength=0.001,),\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"acc\"])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model_DenseNet()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\n\nmodel_save = ModelCheckpoint('./Densenet_512_8_best_weights.h5',\n                             save_best_only = True,\n                             save_weights_only = True,\n                             monitor = 'val_loss',\n                             mode = 'min', verbose = 1)\nearly_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001,\n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3,\n                              patience = 2, min_delta = 0.001,\n                              mode = 'min', verbose = 1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 32\nSTEPS_PER_EPOCH = len(train_ds)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train_ds)*0.2 / BATCH_SIZE\nEPOCHS = 10\nTARGET_SIZE = 128\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_generator,\n    validation_steps = VALIDATION_STEPS,\n    callbacks = [model_save, early_stop, reduce_lr]\n)","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}