{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-output":true,"_kg_hide-input":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\nfrom tensorflow import keras\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom keras.layers import GlobalAveragePooling2D,Flatten,Dense,Dropout\nfrom keras import layers\n!pip install --quiet /kaggle/input/efficientnet-git\nimport efficientnet.keras as efn\n\n\n\n#from tensorflow.keras.applications import EfficientNetB0\n\nfrom tensorflow.keras.applications import EfficientNetB3\n\nimport cv2\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":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_path='../input/cassava-leaf-disease-classification/train_images'\ndf=pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\ndf.head()\nnew_df1=df\nnew_df=df\ndf.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"new_df['weights']=np.where(new_df['label']==3,1,0)\nnew_df=new_df.sample(n=2500,weights=new_df.weights,random_state=42)\nsampled_df=new_df.drop(['weights'],axis=1)\nsampled_df.count()\n"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"index=new_df1[new_df1['label']==3].index"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"new_df1.drop(index,inplace=True)"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"new_df1['label'].value_counts()"},{"metadata":{"trusted":true},"cell_type":"markdown","source":"#new_df1.append(new_df1,ignore_index=True)\n\nfinal_df=new_df1.append(sampled_df,ignore_index=True)\nfinal_df['label'].value_counts()"},{"metadata":{"trusted":true},"cell_type":"code","source":"train,val=train_test_split(df,test_size=0.05,random_state=123)\nprint(train.shape)\nprint(val.shape)\nsns.countplot(df['label'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.countplot(df['label'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"shapes=[]\ndf_train_id=df['image_id']\nrange(len(df_train_id))\n\nfor i in range(len(df_train_id)):\n    img_id=df_train_id[i]\n    img_path = os.path.join(train_path, img_id)\n    shapes.append(cv2.imread(img_path).shape)\n    \n"},{"metadata":{},"cell_type":"markdown","source":"shapes_df=pd.DataFrame({'Shapes':shapes})\nshapes_df.to_csv('imageSizes.csv')\nshapes_df.value_counts()"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train['label']=train['label'].astype('string')\nval['label']=val['label'].astype('string')\n\n#converting to string because when class_mode=categorical we need strings or lists","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# using image data generator to read files "},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train.shape)\nprint(val.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = ImageDataGenerator(preprocessing_function = tf.keras.applications.efficientnet.preprocess_input,\n                                     rotation_range = 0,\n                                     width_shift_range = 0.2,\n                                     height_shift_range = 0.2,\n                                     shear_range = 0.5,\n                                     zoom_range = 0.2,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'reflect').flow_from_dataframe(\n                            train,\n                            directory = train_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            #weight_col = None,\n                            target_size = (256, 256),\n                            #color_mode = \"rgb\",\n                            #classes = None,\n                            class_mode = \"categorical\",\n                            batch_size = 32,\n                            shuffle = True,\n                            #seed = 34,\n                            #save_to_dir = None,\n                            #save_prefix = \"\",\n                            #save_format = \"png\",\n                            \n                            interpolation = \"nearest\",\n                            #validate_filenames = True\n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch=next(train_generator)\nprint(batch[0].shape)\nimage=(batch[0][2])/255\nplt.imshow(image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_generator = ImageDataGenerator(preprocessing_function = tf.keras.applications.efficientnet.preprocess_input,).flow_from_dataframe(\n                            val,\n                            directory = train_path,\n                            x_col = \"image_id\",\n                            y_col = \"label\",\n                            #weight_col = None,\n                            target_size = (256, 256),\n                            #color_mode = \"rgb\",\n                            #classes = None,\n                            class_mode = \"categorical\",\n                            batch_size = 32,\n                            shuffle = True,\n                            #seed = 34,\n                            #save_to_dir = None,\n                            #save_prefix = \"\",\n                            #save_format = \"png\",\n                            \n                            interpolation = \"nearest\",\n                            #validate_filenames = True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"batch1=next(valid_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(batch1[0].shape)\nplt.imshow((batch1[0][2])/255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"# building the efficient net b3 model"},{"metadata":{"trusted":true},"cell_type":"code","source":"def modelEfficientNetB3():\n    model=keras.Sequential()\n    model.add(EfficientNetB3(include_top=False,\n                             weights='imagenet',\n                             input_shape=(256,256,3)\n                            \n                            ))\n    model.add(GlobalAveragePooling2D()),\n    model.add(Flatten())\n    \n    model.add(Dense(256, activation = 'relu', bias_regularizer=tf.keras.regularizers.L1L2(l1=0.01, l2=0.001)))\n    model.add(Dropout(0.5))\n    model.add(Dense(5,activation='softmax'))\n    \n    return model\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=modelEfficientNetB3()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import utils","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"utils.plot_model(model)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt=keras.optimizers.Adam(learning_rate=0.0001)\nmodel.compile(optimizer=opt,\n              loss='categorical_crossentropy',\n              metrics='accuracy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit_generator(train_generator,epochs=25,validation_data=valid_generator)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('./EffNetB4_300_try8.h5')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history_df_save8=pd.DataFrame(history.history)\nhistory_df_save8.to_csv('history_undersampling8.csv',index=False)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"ss = pd.read_csv(\"../input/cassava-leaf-disease-classification/sample_submission.csv\")\npreds = []\n\nfor image_id in ss.image_id:\n    image = cv2.cvtColor(cv2.imread('../input/cassava-leaf-disease-classification/test_images/'+image_id),cv2.COLOR_BGR2RGB)\n    image = cv2.resize(image,(224,224))\n    image = np.expand_dims(image, axis = 0)\n    preds.append(np.argmax(model.predict_generator(image)))\n\nss['label'] = preds\nss.to_csv('submission.csv', index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sample=pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\nsample.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n\n\nss.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}