{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import zipfile\nimport PIL\nimport os\nimport matplotlib.pyplot as plt\nimport json\nimport csv\nimport tensorflow as tf\nimport shutil\nimport pandas as pd\nimport numpy as np","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"f = open(\"../input/cassava-leaf-disease-classification/label_num_to_disease_map.json\",\"r\")\ndisease_names = json.load(f)\ndisease_names","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%rm -rf ./train_images\nshutil.copytree(\"../input/cassava-leaf-disease-classification/train_images\",\"./train_images\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_img_path = \"./train_images/\"\ntrain_img_list = os.listdir(train_img_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dict={}\nwith open(\"../input/cassava-leaf-disease-classification/train.csv\") as file:\n  reader = csv.reader(file,skipinitialspace=True)\n  next(reader)\n  for row in reader:\n    train_dict[row[0]] = row[1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(5):\n  path = train_img_path+str(i)\n  if os.path.isdir(path) != True:\n    os.mkdir(path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for name in train_img_list:\n  path = train_img_path+name\n  if os.path.isdir(path) != True:\n    final_path = train_img_path+train_dict[name]\n    shutil.move(path,final_path)\nos.listdir(train_img_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"height,width = 256,256\nbatch_size=32\nSTEPS_PER_EPOCH = len(train_img_list)*0.8 / batch_size\nVALIDATION_STEPS = len(train_img_list)*0.2 / batch_size\ntrain_datagen = tf.keras.preprocessing.image.ImageDataGenerator(\n        rescale=1./255,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True,\n        vertical_flip=True,\n        validation_split = 0.2,\n        rotation_range=25,\n        fill_mode=\"nearest\",\n        height_shift_range = 0.15,\n        width_shift_range = 0.15,\n)\n\ntrain_generator = train_datagen.flow_from_directory(\n    \"./train_images\",\n    target_size = (height,width),\n    batch_size=batch_size,\n    class_mode = \"sparse\",\n    shuffle = True,\n    subset = \"training\"\n)\n\n\nvalidation_generator = train_datagen.flow_from_directory(\n    \"./train_images\",\n    target_size = (height,width),\n    batch_size=batch_size,\n    class_mode = \"sparse\",\n    shuffle = True,\n    subset = \"validation\"\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with tf.device('/device:GPU:0'):\n    xception = tf.keras.applications.Xception(include_top = False, weights = None,\n                               input_shape = (height,width, 3))\n    model = xception.output\n    model = tf.keras.layers.GlobalAveragePooling2D()(model)\n    model = tf.keras.layers.Dense(5, activation = \"softmax\")(model)\n    model = tf.keras.models.Model(xception.input, model)\n\n    model.compile(optimizer =\"adam\",\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"accuracy\"])\n    \n    \n    checkpoint = tf.keras.callbacks.ModelCheckpoint(\n        filepath=\"./xception_best_model.h5\",\n        save_weights_only=False,\n        monitor='val_accuracy',\n        mode='max',\n        save_best_only=True\n    )\n    \n    history = model.fit(train_generator,\n                    epochs=30,\n                    steps_per_epoch = STEPS_PER_EPOCH,\n                    verbose=1,\n                    validation_data = validation_generator,\n                    validation_steps = VALIDATION_STEPS,\n                    callbacks=[checkpoint]\n                )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = tf.keras.models.load_model(\"./xception_best_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"acc=history.history['accuracy']\nval_acc=history.history['val_accuracy']\nloss=history.history['loss']\nval_loss=history.history['val_loss']\nepochs=range(len(acc))\nplt.plot(epochs, acc, 'r', \"Training Accuracy\")\nplt.plot(epochs, val_acc, 'b', \"Validation Accuracy\")\nplt.title('Training and validation accuracy')\nplt.figure()\nplt.plot(epochs, loss, 'r', \"Training Loss\")\nplt.plot(epochs, val_loss, 'b', \"Validation Loss\")\nplt.title('Training and validation loss')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"path = \"../input/cassava-leaf-disease-classification/test_images/\"\ntest_file_list = os.listdir(path)\npredictions=[]\nfor filename in test_file_list:\n  img = tf.keras.preprocessing.image.load_img(\n      path+filename,target_size = (height,width)\n  )\n  arr = tf.keras.preprocessing.image.img_to_array(img)\n  arr = tf.expand_dims(arr/255.,0)\n  predictions.append(np.argmax(model.predict(arr)[0]))\n\ndf = pd.DataFrame(zip(test_file_list,predictions),columns = [\"image_id\",\"label\"])\ndf.to_csv(\"./submission.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"shutil.rmtree(\"./train_images\")\nos.remove(\"./efficient_best_weight.h5\")","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}