{"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_minor":4,"nbformat":4,"cells":[{"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\nimport json\nimport cv2\n\nimport seaborn as sn\nimport random\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.utils import to_categorical\nfrom keras.preprocessing import image\n\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n%matplotlib inline\n\nimport numpy as np\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","id":"YLjyKMlsh4ne","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# mount google drive\n# file authorization\n\n# from google.colab import drive\n\n# drive.mount('/content/drive')","metadata":{"id":"f_mR8JCFiUVR","outputId":"f5edaed9-9c1d-446f-d2f0-f9d1e046e672","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # open file from \n# try:\n#   zipLeafImages = ZipFile('/content/drive/My Drive/Data/cassavaleafdiseaseclassification.zip')\n#   zipLeafImages.extractall()\n# except:\n#   print('file not found !!!')\n#   exit()","metadata":{"id":"9iVxvcumipV7","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# from google.colab import drive\n# drive.mount('/content/drive')","metadata":{"id":"pPwwMSeUBQE1","outputId":"c77b8661-2052-4bf1-f19d-894bea03d951","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BASE_DIR = \"../input/cassava-leaf-disease-classification/\"\n# BASE_DIR = \"/content/drive/MyDrive/Data/cassava-leaf-disease-classification/\"","metadata":{"id":"1r3mCgahh4nh","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(os.path.join(BASE_DIR, \"label_num_to_disease_map.json\")) as file:\n    map_classes = json.loads(file.read())\n    map_classes = {int(k) : v for k, v in map_classes.items()}\n\nprint(json.dumps(map_classes, indent=4))","metadata":{"id":"sDq0UlFjh4nh","outputId":"5a46fb81-ca6b-4ec1-e88e-de3a2e182e34","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"inputs_files = os.listdir(os.path.join(BASE_DIR, \"train_images\"))\nprint(f\"Number of input images : {len(inputs_files)}\")","metadata":{"id":"m5Dpozdmh4ni","outputId":"428e17ac-0a94-4d0b-c291-30a82a841eff","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Get the images shape, shape should be same for all images","metadata":{"id":"N6L8YY9Th4ni"}},{"cell_type":"code","source":"image_shape = {}\nfor image_name in os.listdir(os.path.join(BASE_DIR, \"train_images\"))[:5]:\n    images = cv2.imread(os.path.join(BASE_DIR, \"train_images\", image_name))\n    image_shape[images.shape] = image_shape.get(images.shape, 0) + 1\n\nprint(image_shape)","metadata":{"id":"g4AFjsYYh4nj","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Merging images with labels","metadata":{"id":"6t4Tz1sbh4nj"}},{"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(BASE_DIR, \"train.csv\"))\ndf_train['class_name'] = df_train['label'].map(map_classes)\ndf_train = df_train.sample(n=1000)\ndf_train.shape","metadata":{"id":"yoQMfI-Zh4nj","outputId":"3a073b9a-61d3-48d0-b46b-6288c623046e","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (12, 8))\nsn.countplot(y = \"class_name\", data = df_train)","metadata":{"id":"tcieTplTh4nm","outputId":"08a6c549-b3b2-468d-eb46-aa1b1b8eb134","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Labeling data in different way","metadata":{"id":"pMNTUENlh4nj"}},{"cell_type":"code","source":"def f(row):\n    if row['label'] == 0:\n        val = 1\n    else:\n        val = 0\n    return val","metadata":{"id":"xa2SQ3aXh4nk","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def e(row):\n    if row['label'] == 3:\n        val = 1\n    else:\n        val = 0\n    return val","metadata":{"id":"-4WlH7h6h4nk","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def d(row):\n    if row['label'] == 1:\n        val = 1\n    else:\n        val = 0\n    return val","metadata":{"id":"Stuu37jXh4nk","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def c(row):\n    if row['label'] == 4:\n        val = 1\n    else:\n        val = 0\n    return val","metadata":{"id":"OZcdbyBrh4nk","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def b(row):\n    if row['label'] == 2:\n        val = 1\n    else:\n        val = 0\n    return val","metadata":{"id":"FdzoADavlAJL","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_with_label = df_train\ndf_train_with_label['class_name'] = df_train['label'].map(map_classes)\ndf_train_with_label['cbb'] = df_train_with_label.apply(f, axis=1)\ndf_train_with_label['cmd'] = df_train_with_label.apply(e, axis=1)\ndf_train_with_label['cbsd'] = df_train_with_label.apply(d, axis=1)\ndf_train_with_label['cgm'] = df_train_with_label.apply(b, axis=1)\ndf_train_with_label['healthy'] = df_train_with_label.apply(c, axis=1)\ndf_train_with_label.reset_index(drop=True, inplace=True)\ndf_train_with_label","metadata":{"id":"VNPFgdoKh4nl","outputId":"c8f3a7a5-8408-4e40-821c-df34c3aa7f62","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = np.array(df_train_with_label.drop(['image_id','label', 'class_name'],axis=1))","metadata":{"id":"ABTEG6Dth4nl","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y.shape","metadata":{"id":"tpwfTWkWh4nl","outputId":"747f6675-6381-4583-8619-d69be6801efa","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train_with_label","metadata":{"id":"No45PGkkh4nm","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,10))\nfolder= BASE_DIR + '/train_images'\nfor images in os.listdir(os.path.join(BASE_DIR, \"train_images\"))[:30]:\n    ax = plt.subplot(3,3, random.randint(1,9))\n    img = cv2.imread(os.path.join(folder,images))\n    plt.imshow(img)\n    plt.axis(\"off\")","metadata":{"id":"ErpHKE6_h4nm","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Lets see image for each deases","metadata":{"id":"vAA4rGZXh4nm"}},{"cell_type":"markdown","source":"# Visual Image Selector","metadata":{"id":"46nhudf-h4nn"}},{"cell_type":"code","source":"def print_random_images(label):\n    plt.figure(figsize=(10,10))\n    folder= BASE_DIR + '/train_images'\n    cbb_images = df_train[df_train.label == label]\n    for images in cbb_images.image_id.head(29):\n        ax = plt.subplot(3,3, random.randint(1,9))\n        img = cv2.imread(os.path.join(folder,images))\n        plt.imshow(img)\n        plt.axis(\"off\")","metadata":{"id":"LME9lfHkh4nn","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data needs to be labeled before to identify is our module did the job or not","metadata":{"id":"CskhMNMmh4nn"}},{"cell_type":"code","source":"df_train.columns","metadata":{"id":"eZ7AAp_HYq4o","outputId":"36e2118c-f648-49a3-c5b4-6c9a6f3c0f99","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train.reset_index(drop=True, inplace=True)\ndf_train","metadata":{"id":"eDOq19I8YLhD","outputId":"376fd9f5-2230-4cfe-a463-0d18161d4322","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_image = []\nfor i in tqdm(range(df_train.shape[0])):\n    img = image.load_img(BASE_DIR + 'train_images/'+df_train['image_id'][i],target_size=(400,400,3))\n    img = image.img_to_array(img)\n    img = img/255\n    train_image.append(img)\n\nX = np.array(train_image)","metadata":{"id":"GWN-cXiyNdot","outputId":"5b061425-5651-4c30-d057-5f4d3ab6d13a","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def transfer_mages(df_train_pool):\n  train_image = []\n  for i in tqdm(range(df_train_pool.shape[0])):\n    img = image.load_img(BASE_DIR + 'train_images/'+df_train_pool['image_id'][i],target_size=(400,400,3))\n    img = image.img_to_array(img)\n    img = img/255\n    train_image.append(img)\n    \n  X = np.array(train_image)\n  return X","metadata":{"id":"BUmBZqEMh4nn","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X.shape","metadata":{"id":"vq3XMXaEh4no","outputId":"dfb21114-e6c0-44c5-da94-5a8b4520bf10","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(X[2])","metadata":{"id":"9vT3G0tkh4no","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#     \"0\": \"Cassava Bacterial Blight (CBB)\",","metadata":{"id":"BNuaw_E5h4no"}},{"cell_type":"code","source":"print_random_images(0)","metadata":{"id":"CG1K9V5_h4no","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#     \"1\": \"Cassava Brown Streak Disease (CBSD)\"","metadata":{"id":"AXa4PU66h4no"}},{"cell_type":"code","source":"print_random_images(1)","metadata":{"id":"uFoqcqzyh4np","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# \"2\": \"Cassava Green Mottle (CGM)\"","metadata":{"id":"8X6Z1b4kh4np"}},{"cell_type":"code","source":"print_random_images(2)","metadata":{"id":"KURfGpGVh4np","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#    \"3\": \"Cassava Mosaic Disease (CMD)\"\n","metadata":{"id":"s2G5BbNeh4np"}},{"cell_type":"code","source":"print_random_images(3)","metadata":{"id":"e4ij4cbDh4np","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#    \"4\": \"Healthy\"","metadata":{"id":"xoR5aljKh4nq"}},{"cell_type":"code","source":"print_random_images(4)","metadata":{"id":"bRVhwhWTh4nq","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make a model","metadata":{"id":"pWEDDOGyh4nq"}},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.2)","metadata":{"id":"F-hO0YBth4nq","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model = Sequential()\n# model.add(Conv2D(filters=16, kernel_size=(5, 5), activation=\"relu\", input_shape=(400,400,3)))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n# model.add(Conv2D(filters=32, kernel_size=(5, 5), activation='relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n# model.add(Conv2D(filters=64, kernel_size=(5, 5), activation=\"relu\"))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n# model.add(Conv2D(filters=64, kernel_size=(5, 5), activation='relu'))\n# model.add(MaxPooling2D(pool_size=(2, 2)))\n# model.add(Dropout(0.25))\n# model.add(Flatten())\n# model.add(Dense(128, activation='relu'))\n# model.add(Dropout(0.5))\n# model.add(Dense(64, activation='relu'))\n# model.add(Dropout(0.5))\n# model.add(Dense(5, activation='sigmoid'))","metadata":{"id":"AlyWyYVMh4nq","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = (400, 400)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentation = keras.Sequential(\n    [\n        layers.experimental.preprocessing.RandomFlip(\"horizontal\"),\n        layers.experimental.preprocessing.RandomRotation(0.1),\n    ]\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def make_model(input_shape, num_classes):\n    inputs = keras.Input(shape=input_shape)\n    # Image augmentation block\n    x = data_augmentation(inputs)\n\n    # Entry block\n    x = layers.experimental.preprocessing.Rescaling(1.0 / 255)(x)\n    \n    x = layers.Conv2D(32, 3, strides=2, padding=\"same\")(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation(\"relu\")(x)\n\n    x = layers.Conv2D(64, 3, padding=\"same\")(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation(\"relu\")(x)\n\n    previous_block_activation = x  # Set aside residual\n\n    for size in [128, 256, 512, 728]:\n        x = layers.Activation(\"relu\")(x)\n        x = layers.SeparableConv2D(size, 3, padding=\"same\")(x)\n        x = layers.BatchNormalization()(x)\n\n        x = layers.Activation(\"relu\")(x)\n        x = layers.SeparableConv2D(size, 3, padding=\"same\")(x)\n        x = layers.BatchNormalization()(x)\n\n        x = layers.MaxPooling2D(3, strides=2, padding=\"same\")(x)\n\n        # Project residual\n        residual = layers.Conv2D(size, 1, strides=2, padding=\"same\")(\n            previous_block_activation\n        )\n        x = layers.add([x, residual])  # Add back residual\n        previous_block_activation = x  # Set aside next residual\n\n    x = layers.SeparableConv2D(1024, 3, padding=\"same\")(x)\n    x = layers.BatchNormalization()(x)\n    x = layers.Activation(\"relu\")(x)\n\n    x = layers.GlobalAveragePooling2D()(x)\n    if num_classes == 2:\n        activation = \"sigmoid\"\n        units = 1\n    else:\n        activation = \"softmax\"\n        units = num_classes\n\n    x = layers.Dropout(0.5)(x)\n    outputs = layers.Dense(units, activation=activation)(x)\n    return keras.Model(inputs, outputs)\n\n\nmodel = make_model(input_shape=image_size + (3,), num_classes=5)\nkeras.utils.plot_model(model, show_shapes=True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"id":"dxctnaewh4nq","outputId":"7c4c1468-c3bf-4545-bb10-c0931af36e0d","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=keras.optimizers.Adam(1e-3), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"id":"vJWw_9YLhXxN","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test.shape, y_test.shape","metadata":{"id":"V_jLO-kxi0GL","outputId":"b803c2dd-6f22-4563-dd2d-5918c8ed0245","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train.shape, y_train.shape","metadata":{"id":"PMPTk-TcjZza","outputId":"f40c5b5d-26c7-4224-9581-faaed75e88b2","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train, y_train, epochs=50, validation_data=(X_test, y_test), batch_size=16)","metadata":{"id":"25gnf4Dghb_Z","outputId":"1e7899d9-9c78-4bb0-b621-51db4c3b47c0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Test","metadata":{"id":"65gGPfOL3za_"}},{"cell_type":"code","source":"img = image.load_img(BASE_DIR+'test_images/2216849948.jpg',target_size=(400,400,3))\nimg = image.img_to_array(img)\nimg = img/255","metadata":{"id":"I4LPeiwgzkQZ","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = np.array(df_train.columns[3:])\nproba = model.predict(img.reshape(1,400,400,3))\ntop_3 = np.argsort(proba[0])\nfor i in range(5):\n    print(\"{}\".format(classes[top_3[i]])+\" ({:.3})\".format(proba[0][top_3[i]]))\nplt.imshow(img)","metadata":{"id":"FyOAPamB4N5Q","outputId":"9b528216-f4cc-410d-83f4-ef79bf9b3242","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output = dict(zip(classes[top_3],proba.ravel()))\noutput_value = max(output, key=output.get)\noutput_value","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val = 4\ndef get_label_value(label):\n    if label == 'cbb':\n        val = 0\n    elif label == 'cbsd':\n        val = 1\n    elif label == 'cgm':\n        val = 2\n    elif label == 'cmd':\n        val = 3\n    else:\n        val = 4\n    return val","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.DataFrame({'image_id': ['2216849948.jpg']})\ntest_df['label'] = get_label_value(output_value)\ntest_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv('submission.csv', encoding='utf-8')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}