{"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":"df_train=pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_text=df_train.copy()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.mkdir(\"/kaggle/working/train_img\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[0,1,2,3,4]\nfor i in range(len(labels)):\n    k=str(i)\n    os.mkdir(\"/kaggle/working/train_img/\"+k)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil\nfrom tqdm import tqdm\n\nfor j in tqdm(range(len(df_train[\"image_id\"]))):\n    img=df_train[\"image_id\"].iloc[j]\n    if(df_train[\"label\"].iloc[j]==0):\n        shutil.copy(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+img,\"/kaggle/working/train_img/0/\")\n    elif(df_train[\"label\"].iloc[j]==1):\n        shutil.copy(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+img,\"/kaggle/working/train_img/1/\")\n    elif(df_train[\"label\"].iloc[j]==2):\n        shutil.copy(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+img,\"/kaggle/working/train_img/2/\")\n    elif(df_train[\"label\"].iloc[j]==3):\n        shutil.copy(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+img,\"/kaggle/working/train_img/3/\")\n    elif(df_train[\"label\"].iloc[j]==4):\n        shutil.copy(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+img,\"/kaggle/working/train_img/4/\")\nprint(\"Copying Files Done!\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"numeric_to_class_name = {0:\"Cassava Bacterial Blight (CBB)\",\n                         1:\"Cassava Brown Streak Disease (CBSD)\",\n                         2:\"Cassava Green Mottle (CGM)\",\n                         3:\"Cassava Mosaic Disease (CMD)\",\n                         4:\"Healthy\"}\n\ndf_train_text['label'].replace(numeric_to_class_name, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train_text.label.unique()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### There are 5 classes for prediction in this dataset :\n\n* Healthy -> The Leaf is healthy\n* Cassava Bacterial Blight (CBB)\n* Cassava Brown Streak Disease (CBSD)\n* Cassava Green Mottle (CGM)\n* Cassava Mosaic Disease (CMD)"},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nsns.set(rc={'figure.figsize':(24,12)})\nsns.countplot(data=df_train_text,x=\"label\")\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_count=df_train_text[[\"label\"]].value_counts().reset_index()\nlabel_count.columns=[\"Label\",\"Number of Observations\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_count.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\nfig=px.pie(label_count,values=\"Number of Observations\",names=\"Label\")\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom PIL import Image\nimport random \nimport matplotlib.pyplot as plt\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_images(label_name):\n    plt.figure(figsize=((10,8)))\n    for i in range(0,6):\n        plt.subplot(3,2,i+1)\n        path=\"/kaggle/working/train_img/\"+str(label_name)+\"/\"\n        files=os.listdir(path)\n        k=random.choice(files)\n        img=plt.imread(path+k)\n        plt.imshow(img)\n        plt.axis(\"off\")\n    plt.tight_layout()\n        \n            \n    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examples of leaves having disease Cassava Bacterial Blight (CBB)"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examples of leaves having disease Cassava Brown Streak Disease (CBSD)"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examples of leaves having disease Cassava Brown Streak Disease (CBSD)"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(2)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examples of leaves having disease Cassava Mosaic Disease (CMD)"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(3)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examples of leaves which are Healthy"},{"metadata":{"trusted":true},"cell_type":"code","source":"show_images(4)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{},"cell_type":"markdown","source":"## Model Building and Training"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_0.size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ImgDataGen=ImageDataGenerator(\n    rotation_range=0.5, width_shift_range=0.3,\n    height_shift_range=0.3,horizontal_flip=True, vertical_flip=True,\n    validation_split=0.2\n)\nDataGenDir=ImgDataGen.flow_from_directory(\"/kaggle/working/train_img/\",\n                                         target_size=(224,224),\n                                         batch_size=64,\n                                         class_mode=\"categorical\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import efficientnet.tfkeras as efn","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# instantiating the model in the startegy scope creating the model on the TPU\nmodel=tf.keras.Sequential([efn.EfficientNetB0(input_shape=(224,224,3),\n                                             weights=\"imagenet\",\n                                             include_top=False),\n                           tf.keras.layers.Flatten(),\n                           tf.keras.layers.Dropout(0.2),\n                           tf.keras.layers.Dense(5,activation=\"softmax\")\n                                             \n])\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),loss=\"categorical_crossentropy\",metrics=[\"acc\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if tf.test.gpu_device_name(): \n\n    print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))\n\nelse:\n\n   print(\"Please install GPU version of TF\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### To be continued....."},{"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}