{"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\n# import os\n# for 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport shutil\nimport json\nfrom PIL import Image","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.applications.resnet import preprocess_input","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_path = '/kaggle/input/cassava-leaf-disease-classification/train_images/'","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_to_disease = json.load(open('/kaggle/input/cassava-leaf-disease-classification/label_num_to_disease_map.json'))\ntrain['disease'] = train.label.map(label_to_disease)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label_to_disease","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.label.value_counts()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image.open(os.path.join(image_path, train[train.label == 0].image_id.iloc[0]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image.open(os.path.join(image_path, train[train.label == 1].image_id.iloc[0]))","metadata":{"execution":{"iopub.status.busy":"2021-05-29T15:38:08.174711Z","iopub.execute_input":"2021-05-29T15:38:08.175021Z","iopub.status.idle":"2021-05-29T15:38:08.212105Z","shell.execute_reply.started":"2021-05-29T15:38:08.174982Z","shell.execute_reply":"2021-05-29T15:38:08.21031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image.open(os.path.join(image_path, train[train.label == 2].image_id.iloc[0]))","metadata":{"execution":{"iopub.status.busy":"2021-05-29T15:38:08.315074Z","iopub.execute_input":"2021-05-29T15:38:08.315458Z","iopub.status.idle":"2021-05-29T15:38:08.331963Z","shell.execute_reply.started":"2021-05-29T15:38:08.315424Z","shell.execute_reply":"2021-05-29T15:38:08.329547Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image.open(os.path.join(image_path, train[train.label == 3].image_id.iloc[0]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Image.open(os.path.join(image_path, train[train.label == 4].image_id.iloc[0]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.label = train.label.astype(str)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_generator = ImageDataGenerator(\n    rotation_range=45,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    zoom_range=0.2,\n    horizontal_flip=True,\n    vertical_flip=True,\n    preprocessing_function=preprocess_input,\n    validation_split=0.25,\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data_loader = data_generator.flow_from_dataframe(\n    train,\n    directory=image_path,\n    classes=['0', '1', '2', '3', '4'],\n    x_col=\"image_id\",\n    y_col=\"label\",\n    target_size=(224, 224),\n    subset='training'\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_data_loader = data_generator.flow_from_dataframe(\n    train,\n    directory=image_path,\n    classes=['0', '1', '2', '3', '4'],\n    x_col=\"image_id\",\n    y_col=\"label\",\n    target_size=(224, 224),\n    subset='validation'\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential([\n    ResNet50(\n        include_top=False, \n        weights='/kaggle/input/tf-keras-pretrained-models/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', \n        pooling='avg', \n        input_shape=(224, 224, 3)\n    ),\n    \n    layers.Dense(5, activation='softmax')\n])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [ReduceLROnPlateau(factor=0.5, patience=5, verbose=1)]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(train_data_loader, \n          validation_data=val_data_loader, \n          batch_size=256, epochs=50, \n          callbacks=callbacks)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_images = os.listdir('/kaggle/input/cassava-leaf-disease-classification/test_images/')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predict = []\n\nfor i in test_images:\n    image = Image.open(f'/kaggle/input/cassava-leaf-disease-classification/test_images/{i}')\n    image = image.resize((224, 224))\n    \n    image = preprocess_input(np.asarray(image))\n    image = np.expand_dims(image, axis=0)\n    \n    predict.append(np.argmax(model.predict(image)))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame({'image_id': test_images, 'label': predict})","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=None)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}