{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport os\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport cv2\nimport numpy as np\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nimport json\nimport random\nimport shutil\nfrom tensorflow.keras.applications.vgg16 import VGG16\nfrom tensorflow.keras.applications.inception_v3 import InceptionV3","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"source_dir = '../input/cassava-leaf-disease-classification/train_images'\nall_images = os.listdir(source_dir)\ndata_label =  pd.read_csv('../input/cassava-leaf-disease-classification/train.csv')\nlabel_name_path = '../input/cassava-leaf-disease-classification/label_num_to_disease_map.json'\nwith open(label_name_path) as f:\n    label_name = json.load(f)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def load_data(source_dir, img_height, img_width, train_size=0.9):\n    X_train = []\n    y_train = []\n    X_test = []\n    y_test = []\n    random.shuffle(all_images)\n    split_size = int(len(all_images)*train_size)\n    #split_size = 100\n    train_images = all_images[0:split_size]\n    test_images = all_images[split_size:]\n    for img in train_images:\n        x = cv2.resize(cv2.imread(os.path.join(source_dir, img)), (img_height, img_width))\n        X_train.append(x)\n        y_train.append(data_label[data_label['image_id'] == img]['label'].values[0])\n    for img in test_images:\n        x = cv2.resize(cv2.imread(os.path.join(source_dir, img)), (img_height, img_width))\n        X_test.append(x)\n        y_test.append(data_label[data_label['image_id'] == img]['label'].values[0])\n    X_train = np.array(X_train)\n    y_train = np.array(y_train)\n    X_test = np.array(X_test)\n    y_test = np.array(y_test)\n    return X_train, y_train, X_test, y_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train, y_train, X_test, y_test = load_data(source_dir, 100, 100, 1)\ny_train = to_categorical(y_train, 5)\ny_test = to_categorical(y_test, 5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(rescale=1/255.)\ntrain_generator = datagen.flow(X_train,y_train,\n                                batch_size=64)\n#datagen_test = ImageDataGenerator(rescale=1/255.)\n#test_generator = datagen_test.flow(X_test,y_test, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def define_directory():\n    os.mkdir('/kaggle/working/Training')\n    os.mkdir('/kaggle/working/Training/CBB')\n    os.mkdir('/kaggle/working/Training/CBSD')\n    os.mkdir('/kaggle/working/Training/CGM')\n    os.mkdir('/kaggle/working/Training/CMD')\n    os.mkdir('/kaggle/working/Training/Healthy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#define_directory()\n#target_path_dict = {0:'CBB', 1:'CBSD', 2:'CGM', 3:'CMD', 4:'Healthy'}\n#training_dir = '/kaggle/working/Training'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#for label in label_name:\n#    images = data_label[data_label['label'] == int(label)]['image_id'].values\n#    for img in images:\n#        source = os.path.join(source_dir, img)\n#        target = os.path.join(training_dir, target_path_dict[int(label)])\n#        shutil.copy(source, target)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#img_height = 150\n#img_width = 150\n#batch_size = 32\n#train_data_gen = ImageDataGenerator(rescale=1/255.)\n#train_generator = train_data_gen.flow_from_directory(training_dir,\n#                                                     target_size = (img_height, img_width),\n#                                                   batch_size=batch_size)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#pre_trained_model = VGG16(include_top=False, weights=None, input_shape=(100, 100, 3))\n#pre_trained_model.load_weights('../input/vgg-16-weight-file/vgg16_weight_file.h5')\npre_trained_model = InceptionV3(include_top=False, weights=None, input_shape=(100, 100, 3))\npre_trained_model.load_weights('../input/inceptionv3-weights/inception_v3_weights.h5')\nfor layer in pre_trained_model.layers:\n    layer.trainable = False\nlast_layer = pre_trained_model.get_layer('mixed7')\nlast_output = last_layer.output\n#Define model\nx = tf.keras.layers.Flatten()(last_output)\nx = tf.keras.layers.Dense(1024, activation='relu')(x)\nx = tf.keras.layers.Dropout(0.2)(x)\n#x = tf.keras.layers.Dense(2048, activation='relu')(x)\n#x = tf.keras.layers.Dropout(0.2)(x)\nx = tf.keras.layers.Dense(5, activation='softmax')(x)\nmodel = tf.keras.Model(pre_trained_model.input, x)\nmodel.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.004), loss='categorical_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(train_generator, epochs=30)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#plt.plot(history.history['accuracy'])\n#plt.plot(history.history['val_accuracy'])\n#plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Prediction"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dir = '../input/cassava-leaf-disease-classification/test_images'\ntest_images = os.listdir(test_dir)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_id = []\nlbl = []\nfor img in test_images:\n    x = cv2.resize(cv2.imread(os.path.join(test_dir, img)), (100, 100))\n    x = np.array(x)\n    x = x/255.\n    x = np.expand_dims(x, axis=0)\n    y = np.argmax(model.predict(x))\n    lbl.append(y)\n    img_id.append(img)\nsubmission_df = pd.DataFrame(columns=['image_id', 'label'])\nsubmission_df['image_id'] = img_id\nsubmission_df['label'] = lbl\nsubmission_df.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}