{"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import warnings\nimport PIL\n\nwarnings.filterwarnings('ignore')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import layers, models, optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import *\nfrom keras.models import model_from_json","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\nK.image_data_format()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_CROPPED_PATH = '../input/car-image-cropping-dataset-size-299/train_crop'\nTEST_CROPPED_PATH = '../input/car-image-cropping-dataset-size-299/test_crop'\n\ndf_train = pd.read_csv('../input/2019-3rd-ml-month-with-kakr/train.csv')\ndf_test = pd.read_csv('../input/2019-3rd-ml-month-with-kakr/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['class'] = df_train['class'].astype('str')\ndf_train = df_train[['img_file', 'class']]\ndf_test = df_test[['img_file']]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Generator"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(rescale = 1./255)\n\ntest_datagen = ImageDataGenerator(rescale = 1./255)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_generator = train_datagen.flow_from_dataframe(dataframe = df_train, directory = TRAIN_CROPPED_PATH, x_col='img_file', y_col = 'class')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 함수 정의"},{"metadata":{"trusted":true},"cell_type":"code","source":"def predict_model(model_name, IMAGE_SIZE, BATCH_SIZE):\n    test_generator = test_datagen.flow_from_dataframe(dataframe = df_test, directory = TEST_CROPPED_PATH, x_col = 'img_file', y_col = None,\n                                                  target_size = (IMAGE_SIZE, IMAGE_SIZE), color_mode ='rgb', class_mode = None,\n                                                  batch_size = BATCH_SIZE, shuffle = False)\n    \n    model_path = \"../input/pretrained-models/\" + model_name\n    \n    json_file = open(model_path + '/' + model_name + '.json', \"r\")         \n    model_json = json_file.read()\n\n    prediction = []\n\n    for i in os.listdir(model_path):\n        if i[-4:] == 'json':\n            continue\n\n        model = model_from_json(model_json)\n        print('loaded model json')\n\n        model.load_weights(model_path + '/' + i)\n        print('loaded model weight:' + i)\n        preds = []\n        for j in range(5):\n            test_generator.reset()\n            pred = model.predict_generator(generator = test_generator, steps = len(df_test) / BATCH_SIZE, verbose = 1)\n            preds.append(pred)\n        pred_tta = np.mean(preds, axis = 0)\n        prediction.append(pred_tta)\n    json_file.close()\n    y_pred = np.mean(prediction, axis = 0)\n    \n    return y_pred","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 예측"},{"metadata":{},"cell_type":"markdown","source":"### densenet201"},{"metadata":{"trusted":true},"cell_type":"code","source":"densenet201_pred = predict_model(model_name = 'densenet201', IMAGE_SIZE = 224, BATCH_SIZE = 32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### inception_v3"},{"metadata":{"trusted":true},"cell_type":"code","source":"inception_pred = predict_model(model_name = 'inception_v3', IMAGE_SIZE = 299, BATCH_SIZE = 32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### xception"},{"metadata":{"trusted":true},"cell_type":"code","source":"xception_pred = predict_model(model_name = 'xception', IMAGE_SIZE = 299, BATCH_SIZE = 32)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 앙상블"},{"metadata":{"trusted":true},"cell_type":"code","source":"ensemble_pred = (densenet201_pred + xception_pred + inception_pred) / 3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = (train_generator.class_indices)\nlabels = dict((v,k) for k,v in labels.items())\nfinal_pred = [labels[k] for k in np.argmax(ensemble_pred, axis = 1)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/2019-3rd-ml-month-with-kakr/sample_submission.csv')\nsubmission[\"class\"] = final_pred\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from IPython.display import FileLink\nFileLink('submission.csv')","execution_count":null,"outputs":[]}],"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}