{"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":{"trusted":true},"cell_type":"code","source":"import pandas as pd\n\ndf=pd.read_csv(\"/kaggle/input/cassava-leaf-disease-classification/train.csv\")\ndf.head()\n\ntrain_ratio=0.8\ndf_train=df[:int(train_ratio*len(df))]\ndf_valid=df[int(train_ratio*len(df)):]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df[\"label\"].unique()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"group=df_train.groupby([\"label\"]).agg(\"count\")\nfrom matplotlib import  pyplot as plt\nfrom matplotlib.pyplot import figure\nfigure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')\nplt.pie(group.values,labels=group.index)\nplt.legend()\ngroup.index","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np\nfrom PIL import Image\n\n\ndef plot_images(df,label=0,num_images=10):\n    figure(num=None, figsize=(10, 10), dpi=80, facecolor='w', edgecolor='k')\n    df=df[df[\"label\"]==label]\n    i=0\n    size = np.sqrt(num_images)\n    for index,row in df.iterrows():\n        i=i+1\n        if i>num_images:\n            break\n        plt.subplot(size, size,i)\n        img = Image.open(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+row[\"image_id\"])\n        plt.imshow(img)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images(df_train,label=0,num_images=16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images(df_train,label=1,num_images=16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images(df_train,label=2,num_images=16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images(df_train,label=3,num_images=16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plot_images(df_train,label=4,num_images=16)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! mkdir /kaggle/working/datasets/\n! mkdir /kaggle/working/datasets/train\n! mkdir /kaggle/working/datasets/train/0\n! mkdir /kaggle/working/datasets/train/1\n! mkdir /kaggle/working/datasets/train/2\n! mkdir /kaggle/working/datasets/train/3\n! mkdir /kaggle/working/datasets/train/4\n! mkdir /kaggle/working/datasets/valid\n! mkdir /kaggle/working/datasets/valid/0\n! mkdir /kaggle/working/datasets/valid/1\n! mkdir /kaggle/working/datasets/valid/2\n! mkdir /kaggle/working/datasets/valid/3\n! mkdir /kaggle/working/datasets/valid/4","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfrom shutil import copyfile\n\nfor index, row in df_train.iterrows():\n    image_id=row[\"image_id\"]\n    copyfile(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+image_id,\"/kaggle/working/datasets/train/\"+str(row['label'])+\"/\"+image_id)\nfor index, row in df_valid.iterrows():\n    image_id=row[\"image_id\"]\n    copyfile(\"/kaggle/input/cassava-leaf-disease-classification/train_images/\"+image_id,\"/kaggle/working/datasets/valid/\"+str(row['label'])+\"/\"+image_id)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import ImageDataGenerator\n\n# All images will be rescaled by 1./255\ntrain_datagen = ImageDataGenerator(\n      rescale=1./255,\n      rotation_range=40,\n      width_shift_range=0.2,\n      height_shift_range=0.2,\n      shear_range=0.2,\n      zoom_range=0.2,\n      horizontal_flip=True,\n      fill_mode='nearest')\ntrain_generator = train_datagen.flow_from_directory(\n        '/kaggle/working/datasets/train/',  # This is the source directory for training images\n        target_size=(500, 500),  # All images will be resized to 150x150\n        batch_size=128,\n        # Since we use binary_crossentropy loss, we need binary labels\n        class_mode='binary')\nvalid_datagen = ImageDataGenerator(\n      rescale=1./255)\nvalid_generator = train_datagen.flow_from_directory(\n        '/kaggle/working/datasets/valid',  # This is the source directory for training images\n        target_size=(500, 500),  # All images will be resized to 150x150\n        batch_size=128,\n        # Since we use binary_crossentropy loss, we need binary labels\n        class_mode='binary')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow  as tf\n\nmodel = tf.keras.models.Sequential([\n    # Note the input shape is the desired size of the image 300x300 with 3 bytes color\n    # This is the first convolution\n    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(500, 500, 3)),\n    tf.keras.layers.MaxPooling2D(2, 2),\n    # The second convolution\n    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The third convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The fourth convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # The fifth convolution\n    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),\n    tf.keras.layers.MaxPooling2D(2,2),\n    # Flatten the results to feed into a DNN\n    tf.keras.layers.Flatten(),\n    # 512 neuron hidden layer\n    tf.keras.layers.Dense(512, activation='relu'),\n    # Only 1 output neuron. It will contain a value from 0-1 where 0 for 1 class ('horses') and 1 for the other ('humans')\n    tf.keras.layers.Dense(5, activation='softmax')\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import layers\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3\nfrom tensorflow.keras import Model\npre_trained_model = InceptionV3(input_shape = (500, 500, 3), \n                                include_top = False, \n                                weights = \"imagenet\")\nfor layer in pre_trained_model.layers:\n    layer.trainable = False\nlast_layer = pre_trained_model.get_layer('mixed10')\nlast_output = last_layer.output\nfrom tensorflow.keras.optimizers import RMSprop\n\nx = layers.Flatten()(last_output)\nx = layers.Dense(1024, activation='relu')(x)\nx = layers.Dropout(0.2)(x)                  \nx = layers.Dense  (5, activation='softmax')(x)           \n\nmodel = Model( pre_trained_model.input, x) \n\nmodel.compile(optimizer = RMSprop(lr=0.0001), \n              loss = 'sparse_categorical_crossentropy', \n              metrics = ['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.optimizers import RMSprop\n\nmodel.compile(loss='sparse_categorical_crossentropy',\n              optimizer=RMSprop(lr=1e-4),\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n      train_generator,\n      steps_per_epoch=8,  \n      epochs=1,\n      verbose=1,\n      validation_data=valid_generator,\n      validation_steps=8)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image\n\n\nfor file in os.listdir(\"/kaggle/input/cassava-leaf-disease-classification/test_images/\"):\n    img = image.load_img(\"/kaggle/input/cassava-leaf-disease-classification/test_images/\"+file, target_size=(500, 500))\n    x = image.img_to_array(img)\n    x = np.expand_dims(x, axis=0)\n    images = np.vstack([x])\n    classes = model.predict(images)\n    print(np.argmax(classes))\n    print(classes)\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}