{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import warnings\nimport seaborn as sns\nimport matplotlib.pylab as plt\nimport PIL\nfrom sklearn.model_selection import StratifiedKFold, KFold\n\nfrom keras import backend as K\nfrom keras.preprocessing.image import ImageDataGenerator\n\nfrom keras.applications import Xception\n\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom keras import layers, models, optimizers","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"warnings.filterwarnings('ignore')\nK.image_data_format()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = 299\nBATCH_SIZE = 32\nEPOCHS = 100\nk_folds=5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/2019-3rd-ml-month-with-kakr'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_IMG_PATH = os.path.join(DATA_PATH, 'train')\nTEST_IMG_PATH = os.path.join(DATA_PATH, 'test')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_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":"plt.figure(figsize=(15,6))\nsns.countplot('class', data=df_train)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['class'].value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['class'].value_counts().mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train['class'].value_counts().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_boxing_img(img_name, margin=-4, size=(IMAGE_SIZE,IMAGE_SIZE)):\n    if img_name.split('_')[0] == 'train':\n        PATH = TRAIN_IMG_PATH\n        data = df_train\n    else:\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, ['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":{"trusted":true},"cell_type":"code","source":"TRAIN_CROPPED_PATH = '../cropped_train'\nTEST_CROPPED_PATH = '../cropped_test'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"if (os.path.isdir(TRAIN_CROPPED_PATH) == False):\n    os.mkdir(TRAIN_CROPPED_PATH)\n\nif (os.path.isdir(TEST_CROPPED_PATH) == False):\n    os.mkdir(TEST_CROPPED_PATH)\n\nfor i, row in df_train.iterrows():\n    cropped = crop_boxing_img(row['img_file'])\n    cropped.save(os.path.join(TRAIN_CROPPED_PATH, row['img_file']))\n\nfor i, row in df_test.iterrows():\n    cropped = crop_boxing_img(row['img_file'])\n    cropped.save(os.path.join(TEST_CROPPED_PATH, row['img_file']))","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":{"trusted":true},"cell_type":"code","source":"model_path = './'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_callback(model_name, patient):\n    ES = EarlyStopping(\n        monitor='val_loss', \n        patience=patient, \n        mode='min', \n        verbose=1)\n    RR = ReduceLROnPlateau(\n        monitor = 'val_loss', \n        factor = 0.5, \n        patience = patient / 2, \n        min_lr=0.000001, \n        verbose=1, \n        mode='min')\n    MC = ModelCheckpoint(\n        filepath=model_name, \n        monitor='val_loss', \n        verbose=1, \n        save_best_only=True, \n        mode='min')\n\n    return [ES, RR, MC]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model(model_name, iamge_size):\n    base_model = model_name(weights='imagenet', input_shape=(iamge_size,iamge_size,3), include_top=False)\n    #base_model.trainable = False\n    model = models.Sequential()\n    model.add(base_model)\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dense(1024, activation='relu'))\n    model.add(layers.Dropout(0.25))\n    model.add(layers.Dense(1024, activation='relu'))\n    model.add(layers.Dropout(0.25))\n \n    model.add(layers.Dense(196, activation='softmax'))\n    model.summary()\n\n    optimizer = optimizers.RMSprop(lr=0.0001)\n    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc'])\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_datagen = ImageDataGenerator(\n    rescale=1./255,\n    #featurewise_center= True,  # set input mean to 0 over the dataset\n    #samplewise_center=True,  # set each sample mean to 0\n    #featurewise_std_normalization= True,  # divide inputs by std of the dataset\n    #samplewise_std_normalization=True,  # divide each input by its std\n    rotation_range=30,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True,\n    vertical_flip=False,\n    zoom_range=0.3,\n    shear_range=0.3,\n    #brightness_range=(1, 1.2),\n    fill_mode='nearest'\n    )\n\nvalid_datagen = ImageDataGenerator(\n    rescale=1./255,\n    #featurewise_center= True,  # set input mean to 0 over the dataset\n    #samplewise_center=True,  # set each sample mean to 0\n    #featurewise_std_normalization= True,  # divide inputs by std of the dataset\n    #samplewise_std_normalization=True  # divide each input by its std\n    )\ntest_datagen = ImageDataGenerator(\n    rescale=1./255\n    #featurewise_center= True,  # set input mean to 0 over the dataset\n    #samplewise_center=True,  # set each sample mean to 0\n    #featurewise_std_normalization= True,  # divide inputs by std of the dataset\n    #samplewise_std_normalization=True,  # divide each input by its std\n    )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"skf = StratifiedKFold(n_splits=k_folds, random_state=2019)\n#skf = KFold(n_splits=k_folds, random_state=2019)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"j = 1\nmodel_xception_names = []\nfor (train_index, valid_index) in skf.split(\n    df_train['img_file'], \n    df_train['class']):\n\n    traindf = df_train.iloc[train_index, :].reset_index()\n    validdf = df_train.iloc[valid_index, :].reset_index()\n\n    print(\"=========================================\")\n    print(\"====== K Fold Validation step => %d/%d =======\" % (j,k_folds))\n    print(\"=========================================\")\n    \n    train_generator = train_datagen.flow_from_dataframe(\n        dataframe=traindf,\n        directory=TRAIN_CROPPED_PATH,\n        x_col='img_file',\n        y_col='class',\n        target_size= (IMAGE_SIZE, IMAGE_SIZE),\n        color_mode='rgb',\n        class_mode='categorical',\n        batch_size=BATCH_SIZE,\n        seed=2019,\n        shuffle=True\n        )\n\n    valid_generator = valid_datagen.flow_from_dataframe(\n        dataframe=validdf,\n        directory=TRAIN_CROPPED_PATH,\n        x_col='img_file',\n        y_col='class',\n        target_size= (IMAGE_SIZE, IMAGE_SIZE),\n        color_mode='rgb',\n        class_mode='categorical',\n        batch_size=BATCH_SIZE,\n        seed=2019,\n        shuffle=True\n        )\n\n    model_name = model_path + str(j) + '_xception.hdf5'\n    model_xception_names.append(model_name)\n    \n    model_xception = get_model(Xception, IMAGE_SIZE)\n    \n    try:\n        model_xception.load_weights(model_name)\n    except:\n        pass\n        \n    history = model_xception.fit_generator(\n        train_generator,\n        steps_per_epoch=len(traindf.index) / BATCH_SIZE,\n        epochs=EPOCHS,\n        validation_data=valid_generator,\n        validation_steps=len(validdf.index) / BATCH_SIZE,\n        verbose=1,\n        shuffle=False,\n        callbacks = get_callback(model_name, 6)\n        )\n        \n    j+=1","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":1}