{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Keras, How to use pretrained model?\n\npretrained 모델을 하는 법을 소개합니다.\n\n대부분의 소스코드는 다른 코드를 참고하여서 제가 수정한 코드만 설명을 드리도록하겠습니다.\n\n만약 캐글에서 제공하는 커널을 사용하신다면,  \n꼭 우측 `Settings`에서 `GPU` 와 `Internet` 항목을 `On`으로 활성화 해주시길 바랍니다.\n\n## References\n\n대부분의 코드는 김태진님 베이스라인 코드와 허태명님의 이미지 Cropping 코드를 사용하였습니다.  \n좋은 자료 제공해주셔서 감사합니다!\n\n* [Applications - Keras Documentation](https://keras.io/applications/)\n* [김태진님 커널: [3rd ML Month] Car Model Classification Baseline](https://www.kaggle.com/fulrose/3rd-ml-month-car-model-classification-baseline)\n* [허태명님 커널: [3rd ML Month] Car Image Cropping](https://www.kaggle.com/tmheo74/3rd-ml-month-car-image-cropping)\n\n## Introduction\n\nKeras Documentation에서는 Pretrained 모델에 대해선 다음과 같이 말하고 있습니다.\n> The top-1 and top-5 accuracy refers to the model's performance on the ImageNet validation dataset.\n\n이는 ImageNet 데이터셋을 사용해서 학습을 시킨 weights라는 것을 알 수 있습니다.\n\n## What is a pretrained model?\n\n미리잘 학습된 모델 파일을 다운받아, 해당 파일로 Weight를 초기화 시키는 것을 Pretrained 모델이라 하고,\n\n이러한 학습법을 **Transfer Learning(전이학습)** 이라 합니다.\n\n다음부터 전이 학습에 필요한 코드 수정 부분만 설명해 드리도록 하겠습니다.\n"},{"metadata":{},"cell_type":"markdown","source":"# Cropped Image Dataset"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import gc\nimport os\nimport glob\nimport zipfile\nimport warnings\nimport numpy as np \nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nimport cv2\nimport PIL\nfrom PIL import ImageOps, ImageFilter, ImageDraw","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/'\nos.listdir(DATA_PATH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 이미지 폴더 경로\nTRAIN_CROP_PATH = \"./train_crop\"\nTEST_CROP_PATH = \"./test_crop\"\nTRAIN_IMG_PATH = os.path.join(DATA_PATH, 'train')\nTEST_IMG_PATH = os.path.join(DATA_PATH, 'test')\n\n# CSV 파일 경로\ndf_train = pd.read_csv(os.path.join(DATA_PATH, 'train.csv'))\ndf_test = pd.read_csv(os.path.join(DATA_PATH, 'test.csv'))\ndf_class = pd.read_csv(os.path.join(DATA_PATH, 'class.csv'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_test.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"태명님이 작성하신 함수에서 Resize 기능을 추가하였습니다.\n\n공인된 CNN 네트워크의 Input shape을 보시면 `224 * 224`, `299 * 299` 와 같은 shape으로 이루어져 있기 때문에,  \n미리 데이터를 준비하는 단계에서 shape을 지정하고 reshape(resize)을 하고 저장할 것 입니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_resize_boxing_img(img_name, margin=16, size=(224, 224)) :\n    if img_name.split('_')[0] == \"train\" :\n        PATH = TRAIN_IMG_PATH\n        data = df_train\n    elif img_name.split('_')[0] == \"test\" :\n        PATH = TEST_IMG_PATH\n        data = df_test\n        \n    img = PIL.Image.open(os.path.join(PATH, img_name))\n    pos = data.loc[data[\"img_file\"] == img_name, \\\n                   ['bbox_x1','bbox_y1', 'bbox_x2', 'bbox_y2']].values.reshape(-1)\n\n    width, height = img.size\n    x1 = max(0, pos[0] - margin)\n    y1 = max(0, pos[1] - margin)\n    x2 = min(pos[2] + margin, width)\n    y2 = min(pos[3] + margin, height)\n\n    return img.crop((x1,y1,x2,y2)).resize(size)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Process Train Image Data Crop"},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir {TRAIN_CROP_PATH}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfor i, row in df_train.iterrows():\n    cropped = crop_resize_boxing_img(row['img_file'])\n    cropped.save(f\"{TRAIN_CROP_PATH}/{row['img_file']}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Process Test Image Data Crop"},{"metadata":{"trusted":true},"cell_type":"code","source":"!mkdir {TEST_CROP_PATH}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfor i, row in df_test.iterrows():\n    cropped = crop_resize_boxing_img(row['img_file'])\n    cropped.save(f\"{TEST_CROP_PATH}/{row['img_file']}\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Cropped Image Eye Checking"},{"metadata":{"trusted":true},"cell_type":"code","source":"tmp_imgs = df_train['img_file'][100:105]\nplt.figure(figsize=(12,20))\n\nfor num, f_name in enumerate(tmp_imgs):\n    img = PIL.Image.open(os.path.join(TRAIN_IMG_PATH, f_name))\n    plt.subplot(5, 2, 2*num + 1)\n    plt.title(f_name)\n    plt.imshow(img)\n    plt.axis('off')\n    \n    img_crop = PIL.Image.open(f\"train_crop/{f_name}\")\n    plt.subplot(5, 2, 2*num + 2)\n    plt.title(f_name + ' cropped')\n    plt.imshow(img_crop)\n    plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ndf_train[\"class\"] = df_train[\"class\"].astype('str')\n\ndf_train = df_train[['img_file', 'class']]\ndf_test = df_test[['img_file']]\n\nits = np.arange(df_train.shape[0])\ntrain_idx, val_idx = train_test_split(its, train_size = 0.8, random_state=42)\n\nX_train = df_train.iloc[train_idx, :]\nX_val = df_train.iloc[val_idx, :]\n\nprint(X_train.shape)\nprint(X_val.shape)\nprint(df_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.applications.mobilenet import preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Parameter\nimg_size = (224, 224)\nnb_train_samples = len(X_train)\nnb_validation_samples = len(X_val)\nnb_test_samples = len(df_test)\nepochs = 20\nbatch_size = 32\n\n# Define Generator config\ntrain_datagen = ImageDataGenerator(\n    horizontal_flip = True, \n    vertical_flip = False,\n    preprocessing_function=preprocess_input\n)\nval_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\ntest_datagen = ImageDataGenerator(preprocessing_function=preprocess_input)\n\n# Make Generator\ntrain_generator = train_datagen.flow_from_dataframe(\n    dataframe=X_train, \n    directory=TRAIN_CROP_PATH,\n    x_col = 'img_file',\n    y_col = 'class',\n    target_size = img_size,\n    color_mode='rgb',\n    class_mode='categorical',\n    batch_size=batch_size,\n    seed=42\n)\n\nvalidation_generator = val_datagen.flow_from_dataframe(\n    dataframe=X_val, \n    directory=TRAIN_CROP_PATH,\n    x_col='img_file',\n    y_col='class',\n    target_size=img_size,\n    color_mode='rgb',\n    class_mode='categorical',\n    batch_size=batch_size,\n    shuffle=False\n)\n\ntest_generator = test_datagen.flow_from_dataframe(\n    dataframe=df_test,\n    directory=TEST_CROP_PATH,\n    x_col='img_file',\n    y_col=None,\n    target_size= img_size,\n    color_mode='rgb',\n    class_mode=None,\n    batch_size=batch_size,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"저 같은 경우 모델을 `MobileNet` 으로 사용하였는데,  \n모델이 가볍고 빠르게 학습되서, 테스트에 용이해 많이 사용하고있습니다.\n\n모델을 교체하면서 가장 좋은 아키텍쳐를 찾는 작업도 좋은 스코어를 얻는데 좋을 것 같습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications.mobilenet import MobileNet, preprocess_input\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import Dense, Dropout, Flatten, Activation, Conv2D, GlobalAveragePooling2D","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"CNN 모델을 초기화 할때 다음과 같이 `weights='imagenet'`을 Keras에서 모델을 자동으로 다운받아 로딩합니다.\n\npretrained 모델의 top layer는 Fully connected layer로 1000개를 분류하는 용도입니다.\n\n이 문제에서는 196가지의 분류를 학습시켜야 하기때문에  \n`inclue_top=False` 옵션으로 해당 레이어를 분리시킨 후,\n`Dense(196)`을 추가하셔야 합니다.\n\n태진님의 기본 코드구조가 이미 그렇게 되어있기 때문에 옵션만 추가하시면 됩니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"# for layer in resNet_model.layers:\n#     layer.trainable = False\n#     print(layer,layer.trainable)\n\nmobileNetModel = MobileNet(weights='imagenet', include_top=False)\n\nmodel = Sequential()\nmodel.add(mobileNetModel)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(196, activation='softmax', kernel_initializer='he_normal'))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import f1_score\n\ndef micro_f1(y_true, y_pred):\n    return f1_score(y_true, y_pred, average='micro')\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_steps(num_samples, batch_size):\n    if (num_samples % batch_size) > 0 :\n        return (num_samples // batch_size) + 1\n    else :\n        return num_samples // batch_size","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Validation score가 가장 좋은 모델을 사용하기 위해 `ModelCheckpoint`를 사용하였습니다.\n\n이를 사용하면 `monitor`옵션에 지정된 스코어가 가장 좋을 때 모델 파일(weights)을 저장합니다.\n\n다음과 같이 사용하실 수 있습니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping\n\nfilepath = \"my_mobilenet_model_{val_acc:.2f}_{val_loss:.4f}.h5\"\n\nckpt = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True)\nes = EarlyStopping(monitor='val_acc', min_delta=0, patience=3, verbose=1, mode='auto')\n\ncallbackList = [ckpt]\n\nhistory = model.fit_generator(\n    train_generator,\n    steps_per_epoch = get_steps(nb_train_samples, batch_size),\n    epochs=epochs,\n    validation_data = validation_generator,\n    validation_steps = get_steps(nb_validation_samples, batch_size),\n    callbacks = callbackList\n)\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot training & validation accuracy values\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot training & validation loss values\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Submission"},{"metadata":{},"cell_type":"markdown","source":"먼저 가장 좋은 모델을 로딩하기 위해 따로 파일을 정렬해주고,  \n마지막 인덱스 파일을 모델에 로딩합니다."},{"metadata":{"trusted":true},"cell_type":"code","source":"model_list = sorted([i for i in os.listdir() if \"my_\" in i])\nmodel_list","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.load_weights(model_list[-1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\ntest_generator.reset()\nprediction = model.predict_generator(\n    generator = test_generator,\n    steps = get_steps(nb_test_samples, batch_size),\n    verbose=1\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predicted_class_indices=np.argmax(prediction, axis=1)\n\n# Generator class dictionary mapping\nlabels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\npredictions = [labels[k] for k in predicted_class_indices]\n\nsubmission = pd.read_csv(os.path.join(DATA_PATH, 'sample_submission.csv'))\nsubmission[\"class\"] = predictions\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm -rf *_crop","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 끝까지 봐주셔서 감사합니다!\n\n**좋은 대회와 자료를 공유해 주신 캐글 코리아 분들께 감사드립니다.**\n\n**재밌게 캐글해요^^**"}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}