{"cells":[{"metadata":{},"cell_type":"markdown","source":"based on [General base model stratifiedkfold ensemble w/test](https://www.kaggle.com/meditech101/general-base-model-stratifiedkfold-ensemble-w-test) kernel.\n\nF1 score and Cutout Augmentation are applied."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\nimport os\nimport warnings\nimport seaborn as sns\nimport matplotlib.pylab as plt\nimport PIL\nfrom sklearn.model_selection import StratifiedKFold, KFold\nfrom sklearn.metrics import f1_score\nfrom keras import backend as K\nfrom keras import layers, models, optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications import *\nfrom keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint\nfrom keras.optimizers import Adam,RMSprop,SGD,Nadam\n\nwarnings.filterwarnings('ignore')\nK.image_data_format()","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"BATCH_SIZE = 32\nEPOCHS = 200\nk_folds = 3\nPATIENCE = 3\nSEED = 777\nBASE_MODEL = Xception\nIMAGE_SIZE = 299","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('../input')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_PATH = '../input/2019-3rd-ml-month-with-kakr'\n\nTRAIN_IMG_PATH = os.path.join(DATA_PATH, 'train')\nTEST_IMG_PATH = os.path.join(DATA_PATH, 'test')\n\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'))\n\nmodel_path = './'\nif not os.path.exists(model_path):\n    os.mkdir(model_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def crop_boxing_img(img_name, margin=0, 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":"import os\nos.listdir('../input/3rd-ml-month-car-image-cropping-dataset')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nTRAIN_CROPPED_PATH = '../input/3rd-ml-month-car-image-cropping-dataset/train_crop'\nTEST_CROPPED_PATH = '../input/3rd-ml-month-car-image-cropping-dataset/test_crop'\n\n# if (os.path.isdir(TRAIN_CROPPED_PATH) == False):\n#     os.mkdir(TRAIN_CROPPED_PATH)\n\n# if (os.path.isdir(TEST_CROPPED_PATH) == False):\n#     os.mkdir(TEST_CROPPED_PATH)\n\n# for 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\n# for 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":"def recall_m(y_true, y_pred):\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n        recall = true_positives / (possible_positives + K.epsilon())\n        return recall\n\ndef precision_m(y_true, y_pred):\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n        precision = true_positives / (predicted_positives + K.epsilon())\n        return precision\n\ndef f1_m(y_true, y_pred):\n    precision = precision_m(y_true, y_pred)\n    recall = recall_m(y_true, y_pred)\n    return 2*((precision*recall)/(precision+recall+K.epsilon()))","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":"#efficientnet download\n!pip install -U efficientnet==0.0.4\nfrom efficientnet import EfficientNetB3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model(model_name, iamge_size):\n    base_model = EfficientNetB3(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(2048, activation='relu', kernel_initializer='he_normal'))\n    model.add(layers.Dropout(0.25))\n \n    model.add(layers.Dense(196, activation='softmax', kernel_initializer='lecun_normal'))\n    model.summary()\n\n    optimizer = optimizers.Nadam(lr=0.00015)\n    #optimizer = optimizers.SGD(momentum=0.9)\n    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['acc', f1_m, precision_m, recall_m])\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ref: https://github.com/yu4u/cutout-random-erasing/blob/master/cifar10_resnet.py\ndef get_random_eraser(p=0.5, s_l=0.02, s_h=0.4, r_1=0.3, r_2=1/0.3, v_l=0, v_h=255, pixel_level=False):\n    def eraser(input_img):\n        img_h, img_w, img_c = input_img.shape\n        p_1 = np.random.rand()\n\n        if p_1 > p:\n            return input_img\n\n        while True:\n            s = np.random.uniform(s_l, s_h) * img_h * img_w\n            r = np.random.uniform(r_1, r_2)\n            w = int(np.sqrt(s / r))\n            h = int(np.sqrt(s * r))\n            left = np.random.randint(0, img_w)\n            top = np.random.randint(0, img_h)\n\n            if left + w <= img_w and top + h <= img_h:\n                break\n\n        if pixel_level:\n            c = np.random.uniform(v_l, v_h, (h, w, img_c))\n        else:\n            c = np.random.uniform(v_l, v_h)\n\n        input_img[top:top + h, left:left + w, :] = c\n\n        return input_img\n\n    return eraser","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=20,\n    width_shift_range=0.2,\n    height_shift_range=0.2,\n    horizontal_flip=True,\n    vertical_flip=False,\n    zoom_range=0.2,\n    #shear_range=0.2,\n    #brightness_range=(1, 1.2),\n    fill_mode='nearest',\n    preprocessing_function = get_random_eraser(v_l=0, v_h=255),\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=SEED)\n#skf = KFold(n_splits=k_folds, random_state=SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"j = 1\nmodel_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=SEED,\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=SEED,\n        shuffle=True\n        )\n    \n    model_name = model_path + str(j) + '_' + 'Xception' + '.hdf5'\n    model_names.append(model_name)\n    \n    model = get_model(BASE_MODEL, IMAGE_SIZE)\n    \n    try:\n        model.load_weights(model_name)\n    except:\n        pass\n        \n    history = model.fit_generator(\n        train_generator,\n        steps_per_epoch=len(traindf.index) / BATCH_SIZE,\n        epochs=150, #########################################################\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, PATIENCE)\n        )\n        \n    j+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_generator = test_datagen.flow_from_dataframe(\n    dataframe=df_test,\n    directory=TEST_CROPPED_PATH,\n    x_col='img_file',\n    y_col=None,\n    target_size= (IMAGE_SIZE, IMAGE_SIZE),\n    color_mode='rgb',\n    class_mode=None,\n    batch_size=BATCH_SIZE,\n    shuffle=False\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"prediction = []\nfor i, name in enumerate(model_names):\n    model = get_model(BASE_MODEL, IMAGE_SIZE)\n    model.load_weights(name)\n    \n    test_generator.reset()\n    pred = model.predict_generator(\n        generator=test_generator,\n        steps = len(df_test)/BATCH_SIZE,\n        verbose=1\n    )\n    prediction.append(pred)\n\ny_pred = np.mean(prediction, axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"preds_class_indices=np.argmax(y_pred, axis=1)","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 preds_class_indices]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv(os.path.join(DATA_PATH, 'sample_submission.csv'))\n# if(JUST_FOR_TESTING):\n#     submission=submission[:10]\nsubmission[\"class\"] = final_pred\nsubmission.to_csv(\"submission.csv\", index=False)\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}