{"cells":[{"metadata":{"id":"XDivAOqN5_2i","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 tos 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":{"id":"lTGTA4r5Z6Vz","trusted":true},"cell_type":"code","source":"import glob\nimport shutil\nimport cv2\nimport os\nfrom keras_preprocessing import image\nfrom keras_preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, TensorBoard\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Dropout, Activation, GlobalAveragePooling2D, Dense\nfrom tensorflow.keras.losses import CategoricalCrossentropy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import Accuracy\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras import Input\n\n%matplotlib inline\nplt.rcParams[\"figure.figsize\"] = (17, 6) # (w, h)","execution_count":null,"outputs":[]},{"metadata":{"id":"XGmNjgqo73eK","trusted":true},"cell_type":"code","source":"TRAINING_DIR = \"../input/cassava-leaf-disease-classification/train_images\"\nTRAINING_CSV = \"../input/cassava-leaf-disease-classification/train.csv\"\nJSON_LABELS = \"../input/cassava-leaf-disease-classification/label_num_to_disease_map.json\"\n#PRETRAINED_MODEL = \"../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\"","execution_count":null,"outputs":[]},{"metadata":{"id":"f1j0idwX8B0y","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(TRAINING_CSV)\ntrain_df[\"label\"] = train_df[\"label\"].astype(\"string\") # for Keras flow_from_dataframe","execution_count":null,"outputs":[]},{"metadata":{"id":"d0JuIPT1fkLH","outputId":"808d0b79-6abd-43d3-e759-a75475d2156c","trusted":true},"cell_type":"code","source":"total_images_count = len(train_df.index)\ntotal_train_img_count = int(len(train_df.index) * 0.8)\ntotal_val_img_count = total_images_count - total_train_img_count\nprint(\"Expected images coutns:\")\nprint(\"\\nTotal Images from original directory: {}\".format(total_images_count))\nprint(\"Training Images: {}\".format(total_train_img_count))\nprint(\"Validation Images: {}\".format(total_val_img_count))","execution_count":null,"outputs":[]},{"metadata":{"id":"xVMD1A2dftQQ","outputId":"d264a2a8-dcb1-4e52-8197-1cff0d41d7bb","trusted":true},"cell_type":"code","source":"label_df = pd.read_json(JSON_LABELS, orient = 'index')\nlabel_df = label_df.values.flatten().tolist()\nlabel_df","execution_count":null,"outputs":[]},{"metadata":{"id":"Qqa7wVpMXT2l","outputId":"f2ecc8d6-c996-43d7-839a-4363634d944f","trusted":true},"cell_type":"code","source":"train_label_0 = train_df[train_df[\"label\"]== \"0\"]\ntrain_label_1 = train_df[train_df[\"label\"]== \"1\"]\ntrain_label_2 = train_df[train_df[\"label\"]== \"2\"]\ntrain_label_3 = train_df[train_df[\"label\"]== \"3\"]\ntrain_label_4 = train_df[train_df[\"label\"]== \"4\"]\nlen(train_label_4)","execution_count":null,"outputs":[]},{"metadata":{"id":"09XLztmGXU5b","outputId":"24888fe6-7d69-4a40-ade9-fa9be18ec08d","trusted":true},"cell_type":"code","source":"training_images_dir = TRAINING_DIR + \"/*.jpg\"\nprint(training_images_dir)\ntraining_images = glob.glob(training_images_dir)\nplt.figure(figsize=(12, 12))    \nfor i in range(1, 10):\n    training_image = np.random.choice(training_images)\n    training_image_RGB = cv2.imread(training_image)[...,::-1]\n    print(training_image_RGB.shape)\n    plt.subplot(3, 3, i)\n    plt.imshow(training_image_RGB)\n    plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{"id":"u_fMqQVrTV4U","trusted":true},"cell_type":"code","source":"training_datagen = ImageDataGenerator(\n    rescale = 1/255,\n    rotation_range = 100,\n    width_shift_range = 0.2,\n    height_shift_range = 0.2,\n    shear_range = 0.2,\n    zoom_range = 0.3,\n    brightness_range = [0.7, 1.4],\n    horizontal_flip = True,\n    vertical_flip=True,\n    fill_mode = \"nearest\",\n    validation_split=0.2\n)\n\nvalidation_datagen = ImageDataGenerator(\n    rescale = 1/255,\n    validation_split=0.2\n)","execution_count":null,"outputs":[]},{"metadata":{"id":"i4bk5kUHTarF","outputId":"b9d4abe6-ddc6-46d6-a9d5-607857717b14","trusted":true},"cell_type":"code","source":"BATCH_SIZE = 24\nIMG_WIDTH = 300\nIMG_HEIGHT = 300\nCHANNEL = 3\n\nprint(\"\\nTraining Dataset\")\ntrain_ds = training_datagen.flow_from_dataframe(\n    train_df,\n    TRAINING_DIR,\n    target_size = (IMG_WIDTH, IMG_HEIGHT),\n    class_mode = \"categorical\",\n    batch_size = BATCH_SIZE,\n    x_col = \"image_id\",\n    y_col = \"label\",\n    shuffle = True,\n    subset = \"training\"\n\n)\nprint(\"\\nValidation Dataset\")\nvalidation_ds = validation_datagen.flow_from_dataframe(\n    train_df,\n    TRAINING_DIR,\n    target_size = (IMG_WIDTH, IMG_HEIGHT),\n    class_mode = \"categorical\",\n    batch_size = BATCH_SIZE,\n    x_col = \"image_id\",\n    y_col = \"label\",\n    shuffle = False,\n    subset = \"validation\"\n)\nprint(\"\\nClass Indices:\")\nprint(train_ds.class_indices)","execution_count":null,"outputs":[]},{"metadata":{"id":"gzuTM_A9Tfp9","trusted":true},"cell_type":"code","source":"class theCallBacks(Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if((logs.get(\"val_accuracy\")>0.92) and (logs.get(\"accuracy\")>0.92)): \n            print(\"\\Training Accuracy> 0.92 & Validation Accuracy> 0.92\\nCancelling training!\")\n            self.model.stop_training = True\n\n            \ncallback_on_metrics = theCallBacks() #Instantiate theCallBacks\n\nreduce_lr = ReduceLROnPlateau(\n                    monitor='val_loss', \n                    factor=0.5,\n                    patience= 2, \n                    verbose = 1,\n                    cooldown = 1,\n                    min_lr=0.0001)","execution_count":null,"outputs":[]},{"metadata":{"id":"TdPazInOak25","trusted":true},"cell_type":"code","source":"loss_func = CategoricalCrossentropy()\n#optimizer = Adam(learning_rate=0.001)","execution_count":null,"outputs":[]},{"metadata":{"id":"IoyomLFka5jT","trusted":true},"cell_type":"code","source":"import datetime\nclass LearningRateLogger(Callback):\n     def __init__(self):\n         super().__init__()\n         self._supports_tf_logs = True\n\n     def on_epoch_end(self, epoch, logs=None):\n         if logs is None or \"learning_rate\" in logs:\n             return\n         logs[\"learning_rate\"] = self.model.optimizer.lr\n        \nlog_dir = \"logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\ntensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)     \n","execution_count":null,"outputs":[]},{"metadata":{"id":"M-1GVfB5bbnA","trusted":true},"cell_type":"code","source":"new_input = Input(shape=(IMG_WIDTH, IMG_HEIGHT, CHANNEL))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install git+https://github.com/rcmalli/keras-vggface.git","execution_count":null,"outputs":[]},{"metadata":{"id":"4PlIsGnWeFf3","outputId":"17daa409-1552-49a2-87ca-41860594c9fe","trusted":true},"cell_type":"code","source":"!pip install keras_applications","execution_count":null,"outputs":[]},{"metadata":{"id":"d53qUS5Ddi0J","trusted":true},"cell_type":"code","source":"import keras\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard\nfrom keras.models import load_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras_vggface.vggface import VGGFace\nfrom tensorflow.keras.layers import Flatten, Dense, Activation, Conv2D, MaxPool2D, BatchNormalization, Dropout, MaxPooling2D\nfrom keras.engine import Model","execution_count":null,"outputs":[]},{"metadata":{"id":"bcJDGdKrbexw","outputId":"54bb1b7e-efc0-4ec6-dc48-6cf3d1c6b022","trusted":true},"cell_type":"code","source":"DROPOUT_RATE = 0.5\nFROZEN_LAYER_NUM = 201\nbase_model = VGGFace(model='senet50', include_top=False,input_tensor=new_input, pooling='avg')\nlast_layer = base_model.get_layer('avg_pool').output\nx = Flatten(name='flatten')(last_layer)\nx = Dropout(DROPOUT_RATE)(x)\nx = Dense(4096, activation='relu', name='fc6')(x)\nx = Dropout(DROPOUT_RATE)(x)\nx = Dense(1024, activation='relu', name='fc7')(x)\nx = Dropout(DROPOUT_RATE)(x)\n# l=0\n# for layer in vgg_notop.layers:\n#     print(layer,\"[\"+str(l)+\"]\")\n#     l=l+1\n\nbatch_norm_indices = [2, 6, 9, 12, 21, 25, 28, 31, 42, 45, 48, 59, 62, 65, 74, 78, 81, 84, 95, 98, 101, 112, 115, 118, 129, 132, 135, 144, 148, 151, 154, 165, 168, 171, 182, 185, 188, 199, 202, 205, 216, 219, 222, 233, 236, 239, 248, 252, 255, 258, 269, 272, 275]\nfor i in range(FROZEN_LAYER_NUM):\n    if i not in batch_norm_indices:\n        base_model.layers[i].trainable = False\n# print('vgg layer 2 is trainable: ' + str(vgg_notop.layers[2].trainable))\n# print('vgg layer 3 is trainable: ' + str(vgg_notop.layers[3].trainable))\n\nout = Dense(5, activation='softmax', name='classifier')(x)\n\nmodel = Model(base_model.input, out)\n\nSGD_LEARNING_RATE = 0.01\nSGD_DECAY = 0.0001\n#optim = keras.optimizers.Adam(lr=ADAM_LEARNING_RATE, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n#optim = keras.optimizers.Adam(lr=0.0005, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nsgd = keras.optimizers.SGD(lr=SGD_LEARNING_RATE, momentum=0.9, decay=SGD_DECAY, nesterov=True)\n#rlrop = keras.callbacks.ReduceLROnPlateau(monitor='val_acc',mode='max',factor=0.5, patience=10, min_lr=0.00001, verbose=1)\n\nmodel.compile(optimizer=sgd, loss='categorical_crossentropy', metrics=['accuracy'])\n#Name = \"tf-SeNet50cs230{}\".format(int(time.time()))\n#tensorboard= TensorBoard(log_dir='logs/{}'.format(Name))\n# plot_model(model, to_file='model2.png', show_shapes=True)","execution_count":null,"outputs":[]},{"metadata":{"id":"Te-Gormnc9Ot","trusted":true},"cell_type":"code","source":"num_epochs = 10\nsteps_per_epoch = total_train_img_count // BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{"id":"yt8-V2cSdo5X","trusted":true},"cell_type":"code","source":"model_checkpoint_path=\"../input/cassava-model\"\n\ncheckpoint = ModelCheckpoint(model_checkpoint_path, monitor='val_accuracy', verbose=1, save_best_only=True,mode='max')","execution_count":null,"outputs":[]},{"metadata":{"id":"lcU_1vUigDD2","trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nmodel = tf.keras.models.load_model(\"../input/cassava-model/cassava_Model_Senet.h5\")\npredicted = []\nsample_submission = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n\nfor image in sample_submission.image_id:\n    img = tf.keras.preprocessing.image.load_img('../input/cassava-leaf-disease-classification/test_images/2216849948.jpg')\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = tf.keras.preprocessing.image.smart_resize(img, (IMG_WIDTH, IMG_HEIGHT))\n    img = tf.reshape(img, (-1, IMG_WIDTH, IMG_HEIGHT, CHANNEL))\n    prediction = model.predict(img/255)  \n    predicted.append(np.argmax(prediction))\n\nsubmission = pd.DataFrame({'image_id': sample_submission.image_id, 'label': predicted})\nsubmission.to_csv('submission.csv', index=False) ","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}