{"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":11,"outputs":[{"output_type":"stream","text":"['xception', 'imet-2019-fgvc6']\n","name":"stdout"}]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import os, sys\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport skimage.io\nfrom skimage.transform import resize\nfrom imgaug import augmenters as iaa\nfrom tqdm import tqdm\nimport PIL\nfrom PIL import Image\nimport cv2\nfrom sklearn.utils import class_weight, shuffle\nfrom keras.losses import binary_crossentropy\nimport keras.backend as K\nimport tensorflow as tf\nfrom sklearn.metrics import f1_score, fbeta_score\nfrom keras.utils import Sequence\nWORKERS = 2\nCHANNEL = 3\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nSIZE = 156\nNUM_CLASSES = 1103\nbeta_f2=2","execution_count":12,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load dataset info\npath_to_train = '../input/imet-2019-fgvc6/train/'\ndata = pd.read_csv('../input/imet-2019-fgvc6/train.csv')\n\ntrain_dataset_info = []\nfor name, labels in zip(data['id'], data['attribute_ids'].str.split(' ')):\n    train_dataset_info.append({\n        'path':os.path.join(path_to_train, name),\n        'labels':np.array([int(label) for label in labels])})\ntrain_dataset_info = np.array(train_dataset_info)","execution_count":13,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gamma = 2.0\nepsilon = K.epsilon()\ndef focal_loss(y_true, y_pred):\n    pt = y_pred * y_true + (1-y_pred) * (1-y_true)\n    pt = K.clip(pt, epsilon, 1-epsilon)\n    CE = -K.log(pt)\n    FL = K.pow(1-pt, gamma) * CE\n    loss = K.sum(FL, axis=1)\n    return loss","execution_count":14,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sometimes = lambda aug: iaa.Sometimes(0.5, aug)\n\nclass data_generator(Sequence):\n    \n    def create_train(dataset_info, batch_size, shape, augument=True):\n        assert shape[2] == 3\n        while True:\n            dataset_info = shuffle(dataset_info)\n            for start in range(0, len(dataset_info), batch_size):\n                end = min(start + batch_size, len(dataset_info))\n                batch_images = []\n                X_train_batch = dataset_info[start:end]\n                batch_labels = np.zeros((len(X_train_batch), NUM_CLASSES))\n                for i in range(len(X_train_batch)):\n                    image = data_generator.load_image(\n                        X_train_batch[i]['path'], shape)   \n                    if augument:\n                        image = data_generator.augment(image)\n                    batch_images.append(image/255.)\n                    batch_labels[i][X_train_batch[i]['labels']] = 1\n                    \n                yield np.array(batch_images, np.float32), batch_labels\n\n    def create_valid(dataset_info, batch_size, shape, augument=False):\n        assert shape[2] == 3\n        while True:\n            # dataset_info = shuffle(dataset_info)\n            for start in range(0, len(dataset_info), batch_size):\n                end = min(start + batch_size, len(dataset_info))\n                batch_images = []\n                X_train_batch = dataset_info[start:end]\n                batch_labels = np.zeros((len(X_train_batch), NUM_CLASSES))\n                for i in range(len(X_train_batch)):\n                    image = data_generator.load_image(\n                        X_train_batch[i]['path'], shape)   \n                    if augument:\n                        image = data_generator.augment(image)\n                    batch_images.append(image/255.)\n                    batch_labels[i][X_train_batch[i]['labels']] = 1\n                yield np.array(batch_images, np.float32), batch_labels\n\n\n    def load_image(path, shape):\n        image = cv2.imread(path+'.png')\n        image = cv2.resize(image, (SIZE, SIZE))\n        return image\n\n    def augment(image):\n        augment_img = iaa.Sequential([\n            iaa.OneOf([\n                iaa.Affine(rotate=0),\n                iaa.Affine(rotate=(-15,15)),\n                iaa.Crop(px=(0, 16)),\n                iaa.Affine(shear=(-5, 5)),\n                iaa.GaussianBlur(sigma=(0, 0.5)),\n                iaa.Fliplr(0.5),\n            ])], random_order=True)\n\n        image_aug = augment_img.augment_image(image)\n        return image_aug\n","execution_count":15,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential, load_model\nfrom keras.layers import *\nfrom keras.applications import *\nfrom keras.callbacks import ModelCheckpoint\nfrom keras import metrics\nfrom keras.optimizers import Adam \nfrom keras import backend as K\nimport keras\nfrom keras.models import Model","execution_count":16,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# reference link: https://gist.github.com/drscotthawley/d1818aabce8d1bf082a6fb37137473ae\nfrom keras.callbacks import Callback\n\ndef get_1cycle_schedule(lr_max=1e-3, n_data_points=8000, epochs=200, batch_size=40, verbose=0):          \n    \"\"\"\n    Creates a look-up table of learning rates for 1cycle schedule with cosine annealing\n    See @sgugger's & @jeremyhoward's code in fastai library: https://github.com/fastai/fastai/blob/master/fastai/train.py\n    Wrote this to use with my Keras and (non-fastai-)PyTorch codes.\n    Note that in Keras, the LearningRateScheduler callback (https://keras.io/callbacks/#learningratescheduler) only operates once per epoch, not per batch\n      So see below for Keras callback\n\n    Keyword arguments:\n    lr_max            chosen by user after lr_finder\n    n_data_points     data points per epoch (e.g. size of training set)\n    epochs            number of epochs\n    batch_size        batch size\n    Output:  \n    lrs               look-up table of LR's, with length equal to total # of iterations\n    Then you can use this in your PyTorch code by counting iteration number and setting\n          optimizer.param_groups[0]['lr'] = lrs[iter_count]\n    \"\"\"\n    if verbose > 0:\n        print(\"Setting up 1Cycle LR schedule...\")\n    pct_start, div_factor = 0.3, 25.        # @sgugger's parameters in fastai code\n    lr_start = lr_max/div_factor\n    lr_end = lr_start/1e4\n    n_iter = (n_data_points * epochs // batch_size) + 1    # number of iterations\n    a1 = int(n_iter * pct_start)\n    a2 = n_iter - a1\n\n    # make look-up table\n    lrs_first = np.linspace(lr_start, lr_max, a1)            # linear growth\n    lrs_second = (lr_max-lr_end)*(1+np.cos(np.linspace(0,np.pi,a2)))/2 + lr_end  # cosine annealing\n    lrs = np.concatenate((lrs_first, lrs_second))\n    return lrs\n\n\nclass OneCycleScheduler(Callback):\n    \"\"\"My modification of Keras' Learning rate scheduler to do 1Cycle learning\n       which increments per BATCH, not per epoch\n    Keyword arguments\n        **kwargs:  keyword arguments to pass to get_1cycle_schedule()\n        Also, verbose: int. 0: quiet, 1: update messages.\n\n    Sample usage (from my train.py):\n        lrsched = OneCycleScheduler(lr_max=1e-4, n_data_points=X_train.shape[0],\n        epochs=epochs, batch_size=batch_size, verbose=1)\n    \"\"\"\n    def __init__(self, **kwargs):\n        super(OneCycleScheduler, self).__init__()\n        self.verbose = kwargs.get('verbose', 0)\n        self.lrs = get_1cycle_schedule(**kwargs)\n        self.iteration = 0\n\n    def on_batch_begin(self, batch, logs=None):\n        lr = self.lrs[self.iteration]\n        K.set_value(self.model.optimizer.lr, lr)         # here's where the assignment takes place\n        if self.verbose > 0:\n            print('\\nIteration %06d: OneCycleScheduler setting learning '\n                  'rate to %s.' % (self.iteration, lr))\n        self.iteration += 1\n\n    def on_epoch_end(self, epoch, logs=None):  # this is unchanged from Keras LearningRateScheduler\n        logs = logs or {}\n        logs['lr'] = K.get_value(self.model.optimizer.lr)\n        self.iteration = 0\n\n","execution_count":17,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model(input_shape, n_out):\n    input_tensor = Input(shape=input_shape)\n    base_model = Xception(include_top=False,\n                   weights=None,\n                   input_tensor=input_tensor)\n    base_model.load_weights('../input/xception/xception_weights_tf_dim_ordering_tf_kernels_notop.h5')\n#     x = Conv2D(32, kernel_size=(1,1), activation='relu')(base_model.output)\n#     x = Flatten()(x)\n    x = GlobalAveragePooling2D()(base_model.output)\n    x = Dropout(0.5)(x)\n    x = Dense(1024, activation='relu')(x)\n    x = Dropout(0.5)(x)\n    final_output = Dense(n_out, activation='sigmoid', name='final_output')(x)\n    model = Model(input_tensor, final_output)\n    \n    return model","execution_count":18,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# create callbacks list\nfrom keras.callbacks import (ModelCheckpoint, LearningRateScheduler,\n                             EarlyStopping, ReduceLROnPlateau,CSVLogger)\n                             \nfrom sklearn.model_selection import train_test_split\n\nepochs = 35; batch_size = 64\ncheckpoint = ModelCheckpoint('../working/Resnet50_focal.h5', monitor='val_loss', verbose=1, \n                             save_best_only=True, mode='min', save_weights_only = True)\nreduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=4, \n                                   verbose=1, mode='auto', epsilon=0.0001)\nearly = EarlyStopping(monitor=\"val_loss\", \n                      mode=\"min\", \n                      patience=9)\n\ncsv_logger = CSVLogger(filename='../working/training_log.csv',\n                       separator=',',\n                       append=True)\n\n\n# split data into train, valid\nindexes = np.arange(train_dataset_info.shape[0])\ntrain_indexes, valid_indexes = train_test_split(indexes, test_size=0.15, random_state=8)\n\n# create train and valid datagens\ntrain_generator = data_generator.create_train(\n    train_dataset_info[train_indexes], batch_size, (SIZE,SIZE,3), augument=True)\ntrain_generator_warmup = data_generator.create_train(\n    train_dataset_info[train_indexes], batch_size, (SIZE,SIZE,3), augument=False)\nvalidation_generator = data_generator.create_valid(\n    train_dataset_info[valid_indexes], batch_size, (SIZE,SIZE,3), augument=False)\n\nlrsched = OneCycleScheduler(lr_max=1e-4, n_data_points=len(train_indexes),\n        epochs=1, batch_size=batch_size, verbose=0)\n# callbacks_list = [checkpoint, csv_logger, lrsched]\ncallbacks_list = [checkpoint, csv_logger, reduceLROnPlat]","execution_count":19,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# warm up model\nmodel = create_model(\n    input_shape=(SIZE,SIZE,3), \n    n_out=NUM_CLASSES)\n\nfor layer in model.layers:\n    layer.trainable = False\n\nfor i in range(-5,0):\n    model.layers[i].trainable = True\n\nmodel.compile(\n    loss='binary_crossentropy',\n    optimizer=Adam(1e-3))\n\n# model.summary()\n\nmodel.fit_generator(\n    train_generator_warmup,\n    steps_per_epoch=np.ceil(float(len(train_indexes)) / float(batch_size)),\n    epochs=2,\n    max_queue_size=16, workers=WORKERS, use_multiprocessing=True,\n    verbose=1)","execution_count":null,"outputs":[{"output_type":"stream","text":"Epoch 1/2\n 616/1451 [===========>..................] - ETA: 4:16 - loss: 0.0243","name":"stdout"}]},{"metadata":{"trusted":true},"cell_type":"code","source":"# train all layers\nfor layer in model.layers:\n    layer.trainable = True\n\nmodel.compile(loss='binary_crossentropy',\n            # loss=focal_loss,\n            optimizer=Adam(lr=0.0003))\n\ncheckpoint = ModelCheckpoint('../working/Resnet50_focal.h5', monitor='val_loss', verbose=1, \n                             save_best_only=True, mode='min', save_weights_only = True)\nreduceLROnPlat = ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=1, \n                                   verbose=1, mode='auto', epsilon=0.0001)\nearly = EarlyStopping(monitor=\"val_loss\", \n                      mode=\"min\", \n                      patience=9)\ncallbacks_list = [checkpoint, csv_logger, reduceLROnPlat]\n\nmodel.fit_generator(\n    train_generator,\n    steps_per_epoch=np.ceil(float(len(train_indexes)) / float(batch_size)),\n    validation_data=validation_generator,\n    validation_steps=np.ceil(float(len(valid_indexes)) / float(batch_size)),\n    epochs=(epochs*0.9),\n    verbose=1,\n    max_queue_size=16, workers=WORKERS, use_multiprocessing=True,\n    callbacks=callbacks_list)\n\nmodel.compile(loss='binary_crossentropy',\n            # loss=focal_loss,\n            optimizer=SGD(0.0001,0.9))\nmodel.fit_generator(\n    train_generator,\n    steps_per_epoch=np.ceil(float(len(train_indexes)) / float(batch_size)),\n    validation_data=validation_generator,\n    validation_steps=np.ceil(float(len(valid_indexes)) / float(batch_size)),\n    epochs=(epochs*0.1),\n    verbose=1,\n    max_queue_size=16, workers=WORKERS, use_multiprocessing=True,\n    callbacks=callbacks_list)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('../working/'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit = pd.read_csv('../input/imet-2019-fgvc6/sample_submission.csv')\nmodel.load_weights('../working/Resnet50_focal.h5')\npredicted = []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''Search for the best threshold regarding the validation set'''\n\nBATCH = 512\nfullValGen = data_generator.create_valid(\n    train_dataset_info[valid_indexes], BATCH, (SIZE,SIZE,3))\n\nn_val = round(train_dataset_info.shape[0]*0.15)//BATCH\nprint(n_val)\n\nlastFullValPred = np.empty((0, NUM_CLASSES))\nlastFullValLabels = np.empty((0, NUM_CLASSES))\nfor i in tqdm(range(n_val+1)): \n    im, lbl = next(fullValGen)\n    scores = model.predict(im)\n    lastFullValPred = np.append(lastFullValPred, scores, axis=0)\n    lastFullValLabels = np.append(lastFullValLabels, lbl, axis=0)\nprint(lastFullValPred.shape, lastFullValLabels.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def my_f2(y_true, y_pred):\n    assert y_true.shape[0] == y_pred.shape[0]\n\n    tp = np.sum((y_true == 1) & (y_pred == 1))\n    tn = np.sum((y_true == 0) & (y_pred == 0))\n    fp = np.sum((y_true == 0) & (y_pred == 1))\n    fn = np.sum((y_true == 1) & (y_pred == 0))\n    \n    p = tp / (tp + fp + K.epsilon())\n    r = tp / (tp + fn + K.epsilon())\n\n    f2 = (1+beta_f2**2)*p*r / (p*beta_f2**2 + r + 1e-15)\n\n    return f2\n\ndef find_best_fixed_threshold(preds, targs, do_plot=True):\n    score = []\n    thrs = np.arange(0, 0.5, 0.01)\n    for thr in tqdm(thrs):\n        score.append(my_f2(targs, (preds > thr).astype(int) ))\n    score = np.array(score)\n    pm = score.argmax()\n    best_thr, best_score = thrs[pm], score[pm].item()\n    print(f'thr={best_thr:.3f}', f'F2={best_score:.3f}')\n    if do_plot:\n        plt.plot(thrs, score)\n        plt.vlines(x=best_thr, ymin=score.min(), ymax=score.max())\n        plt.text(best_thr+0.03, best_score-0.01, f'$F_{2}=${best_score:.3f}', fontsize=14);\n        plt.show()\n    return best_thr, best_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"best_thr, best_score = find_best_fixed_threshold(lastFullValPred, lastFullValLabels, do_plot=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfor i, name in tqdm(enumerate(submit['id'])):\n    path = os.path.join('../input/imet-2019-fgvc6/test/', name)\n    image = data_generator.load_image(path, (SIZE,SIZE,3))\n    score_predict = model.predict(image[np.newaxis]/255.)\n    # print(score_predict)\n    label_predict = np.arange(NUM_CLASSES)[score_predict[0]>=best_thr]\n    # print(label_predict)\n    str_predict_label = ' '.join(str(l) for l in label_predict)\n    predicted.append(str_predict_label)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submit['attribute_ids'] = predicted\nsubmit.to_csv('submission.csv', index=False)","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}