{"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":"!pip install git+https://github.com/qubvel/efficientnet","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_dir = '/kaggle/input/cassava-leaf-disease-classification'\ntrain_dir = \"/kaggle/input/cassava-leaf-disease-classification/train_images\"\ntest_dir = \"/kaggle/input/cassava-leaf-disease-classification/test_images\"\nlabels = pd.read_csv(data_dir+\"/train.csv\")\nlabels['label'] = labels['label'].astype('str')\n\nprint(labels.shape)\nlabels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\n\nim = cv2.imread(train_dir+\"/1000201771.jpg\")\nplt.imshow(im)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"im2 = cv2.imread(train_dir+\"/1000812911.jpg\")\nplt.imshow(im2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_input_shape = (256,256,3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\ntrain_datagen = ImageDataGenerator(\n    rescale=1/255,\n    validation_split=0.25,\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'\n)\n\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe = labels,\n    directory = train_dir,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    target_size=user_input_shape[:2],\n    subset=\"training\",\n    batch_size=8,\n    shuffle=True,\n    class_mode=\"categorical\"\n)\n\nval_generator = train_datagen.flow_from_dataframe(\n    dataframe = labels,\n    directory = train_dir,\n    x_col=\"image_id\",\n    y_col=\"label\",\n    target_size=user_input_shape[:2],\n    subset=\"validation\",\n    batch_size=8,\n    shuffle=True,\n    class_mode=\"categorical\"\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from efficientnet.keras import EfficientNetB7\nfrom keras.layers import Dense\nfrom keras.models import Sequential\n\nefficient_net = EfficientNetB7(\n    weights='imagenet',\n    input_shape=user_input_shape,\n    include_top=False,\n    pooling='max'\n)\n# efficient_net.trainable=True # efficientnetb7의 학습을 허용\n\n\nmodel = Sequential()\nmodel.add(efficient_net)\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(5, activation='sigmoid'))\nmodel.summary()\n\nmodel.compile(loss='categorical_crossentropy', \n              optimizer='adam', \n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.callbacks import EarlyStopping # 조기 종료\nearly_stopping = EarlyStopping(\n    monitor='val_accuracy',\n    patience=10,\n    mode='auto',\n    verbose=2)\n\nhistory = model.fit(\n    train_generator,\n    epochs = 100,\n    # steps_per_epoch = 5,\n    validation_data = val_generator,\n    # validation_steps = 5,\n    verbose=1,\n    callbacks=[early_stopping]\n)\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc) + 1)\n\nplt.plot(epochs,acc,'bo',label = 'Training Accuracy')\nplt.plot(epochs,val_acc,'b',label = 'Validation Accuracy')\nplt.title('Training and Validation Accuracy')\nplt.legend()\nplt.figure()\n\nplt.plot(epochs,loss,'bo',label = 'Training loss')\nplt.plot(epochs,val_loss,'b',label = 'Validation Loss')\nplt.title('Training and Validation Loss')\nplt.legend()\n\nplt.show()","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}