{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Permutation Feature Importance","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:19:26.660487Z","iopub.execute_input":"2022-07-07T15:19:26.661271Z","iopub.status.idle":"2022-07-07T15:19:26.684277Z","shell.execute_reply.started":"2022-07-07T15:19:26.661151Z","shell.execute_reply":"2022-07-07T15:19:26.683528Z"}}},{"cell_type":"markdown","source":"I found the discussion post on feature importance by @ambrosm very interesting. So I wanted to try to implement permutation feature importance. \n\nThe code below is derived from two notebooks by @cdeotte and I am using the dataset put together by @raddar. All links below\n\n1. https://www.kaggle.com/competitions/amex-default-prediction/discussion/331131\n2. https://www.kaggle.com/code/cdeotte/xgboost-starter-0-793\n3. https://www.kaggle.com/code/cdeotte/lstm-feature-importance\n4. https://www.kaggle.com/datasets/raddar/amex-data-integer-dtypes-parquet-format\n\nI truly appreciate their work, please check it out! :)\n\n","metadata":{}},{"cell_type":"markdown","source":"# Load libraries","metadata":{}},{"cell_type":"code","source":"# LOAD LIBRARIES\nimport pandas as pd, numpy as np # CPU libraries\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\n\nimport cupy, cudf # GPU libraries\nimport matplotlib.pyplot as plt, gc, os\nimport seaborn as sns\nfrom tqdm.notebook import tqdm\n\nprint('RAPIDS version',cudf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-07T20:17:06.821529Z","iopub.execute_input":"2022-07-07T20:17:06.82256Z","iopub.status.idle":"2022-07-07T20:17:06.846562Z","shell.execute_reply.started":"2022-07-07T20:17:06.822495Z","shell.execute_reply":"2022-07-07T20:17:06.845007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# VERSION NAME FOR SAVED MODEL FILES\nVER = 1\n\n# TRAIN RANDOM SEED\nSEED = 42\n\n# FILL NAN VALUE\nNAN_VALUE = -127 # will fit in int8\n\n# FOLDS PER MODEL\nFOLDS = 5","metadata":{"execution":{"iopub.status.busy":"2022-07-07T19:48:13.060141Z","iopub.status.idle":"2022-07-07T19:48:13.061313Z","shell.execute_reply.started":"2022-07-07T19:48:13.060969Z","shell.execute_reply":"2022-07-07T19:48:13.061004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Process train data","metadata":{}},{"cell_type":"code","source":"def read_file(path = '', usecols = None):\n    # LOAD DATAFRAME\n    if usecols is not None: df = cudf.read_parquet(path, columns=usecols)\n    else: df = cudf.read_parquet(path)\n    # REDUCE DTYPE FOR CUSTOMER AND DATE\n    df['customer_ID'] = df['customer_ID'].str[-16:].str.hex_to_int().astype('int64')\n    df.S_2 = cudf.to_datetime( df.S_2 )\n    # SORT BY CUSTOMER AND DATE (so agg('last') works correctly)\n    #df = df.sort_values(['customer_ID','S_2'])\n    #df = df.reset_index(drop=True)\n    # FILL NAN\n    df = df.fillna(NAN_VALUE) \n    print('shape of data:', df.shape)\n    \n    return df\n\nprint('Reading train data...')\nTRAIN_PATH = '../input/amex-data-integer-dtypes-parquet-format/train.parquet'\ntrain = read_file(path = TRAIN_PATH)","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:54:38.853153Z","iopub.execute_input":"2022-07-07T15:54:38.854288Z","iopub.status.idle":"2022-07-07T15:55:00.423536Z","shell.execute_reply.started":"2022-07-07T15:54:38.854239Z","shell.execute_reply":"2022-07-07T15:55:00.422347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def process_and_feature_engineer(df):\n    # FEATURE ENGINEERING FROM \n    # https://www.kaggle.com/code/huseyincot/amex-agg-data-how-it-created\n    all_cols = [c for c in list(df.columns) if c not in ['customer_ID','S_2']]\n    cat_features = [\"B_30\",\"B_38\",\"D_114\",\"D_116\",\"D_117\",\"D_120\",\"D_126\",\"D_63\",\"D_64\",\"D_66\",\"D_68\"]\n    num_features = [col for col in all_cols if col not in cat_features]\n\n    test_num_agg = df.groupby(\"customer_ID\")[num_features].agg(['mean', 'std', 'min', 'max', 'last'])\n    test_num_agg.columns = ['_'.join(x) for x in test_num_agg.columns]\n\n    test_cat_agg = df.groupby(\"customer_ID\")[cat_features].agg(['count', 'last', 'nunique'])\n    test_cat_agg.columns = ['_'.join(x) for x in test_cat_agg.columns]\n\n    df = cudf.concat([test_num_agg, test_cat_agg], axis=1)\n    del test_num_agg, test_cat_agg\n    print('shape after engineering', df.shape )\n    \n    return df\n\ntrain = process_and_feature_engineer(train)","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:00.426039Z","iopub.execute_input":"2022-07-07T15:55:00.426447Z","iopub.status.idle":"2022-07-07T15:55:01.749869Z","shell.execute_reply.started":"2022-07-07T15:55:00.426408Z","shell.execute_reply":"2022-07-07T15:55:01.747927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ADD TARGETS\ntargets = cudf.read_csv('../input/amex-default-prediction/train_labels.csv')\ntargets['customer_ID'] = targets['customer_ID'].str[-16:].str.hex_to_int().astype('int64')\ntargets = targets.set_index('customer_ID')\ntrain = train.merge(targets, left_index=True, right_index=True, how='left')\ntrain.target = train.target.astype('int8')\ndel targets\n\n# NEEDED TO MAKE CV DETERMINISTIC (cudf merge above randomly shuffles rows)\ntrain = train.sort_index().reset_index()\n\n# FEATURES\nFEATURES = train.columns[1:-1]\nprint(f'There are {len(FEATURES)} features!')","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:01.752238Z","iopub.execute_input":"2022-07-07T15:55:01.752948Z","iopub.status.idle":"2022-07-07T15:55:03.125266Z","shell.execute_reply.started":"2022-07-07T15:55:01.752903Z","shell.execute_reply":"2022-07-07T15:55:03.124066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setup for XGB Training","metadata":{}},{"cell_type":"code","source":"# LOAD XGB LIBRARY\nfrom sklearn.model_selection import KFold\nimport xgboost as xgb\nprint('XGB Version',xgb.__version__)\n\n# XGB MODEL PARAMETERS\nxgb_parms = { \n    'max_depth':4, \n    'learning_rate':0.05, \n    'subsample':0.8,\n    'colsample_bytree':0.6, \n    'eval_metric':'logloss',\n    'objective':'binary:logistic',\n    'tree_method':'gpu_hist',\n    'predictor':'gpu_predictor',\n    'random_state':SEED\n}","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:03.128643Z","iopub.execute_input":"2022-07-07T15:55:03.129109Z","iopub.status.idle":"2022-07-07T15:55:03.250931Z","shell.execute_reply.started":"2022-07-07T15:55:03.129049Z","shell.execute_reply":"2022-07-07T15:55:03.249883Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# NEEDED WITH DeviceQuantileDMatrix BELOW\nclass IterLoadForDMatrix(xgb.core.DataIter):\n    def __init__(self, df=None, features=None, target=None, batch_size=256*1024):\n        self.features = features\n        self.target = target\n        self.df = df\n        self.it = 0 # set iterator to 0\n        self.batch_size = batch_size\n        self.batches = int( np.ceil( len(df) / self.batch_size ) )\n        super().__init__()\n\n    def reset(self):\n        '''Reset the iterator'''\n        self.it = 0\n\n    def next(self, input_data):\n        '''Yield next batch of data.'''\n        if self.it == self.batches:\n            return 0 # Return 0 when there's no more batch.\n        \n        a = self.it * self.batch_size\n        b = min( (self.it + 1) * self.batch_size, len(self.df) )\n        dt = cudf.DataFrame(self.df.iloc[a:b])\n        input_data(data=dt[self.features], label=dt[self.target]) #, weight=dt['weight'])\n        self.it += 1\n        return 1","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:03.255243Z","iopub.execute_input":"2022-07-07T15:55:03.258245Z","iopub.status.idle":"2022-07-07T15:55:03.27298Z","shell.execute_reply.started":"2022-07-07T15:55:03.258201Z","shell.execute_reply":"2022-07-07T15:55:03.2718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# https://www.kaggle.com/kyakovlev\n# https://www.kaggle.com/competitions/amex-default-prediction/discussion/327534\ndef amex_metric_mod(y_true, y_pred):\n\n    labels     = np.transpose(np.array([y_true, y_pred]))\n    labels     = labels[labels[:, 1].argsort()[::-1]]\n    weights    = np.where(labels[:,0]==0, 20, 1)\n    cut_vals   = labels[np.cumsum(weights) <= int(0.04 * np.sum(weights))]\n    top_four   = np.sum(cut_vals[:,0]) / np.sum(labels[:,0])\n\n    gini = [0,0]\n    for i in [1,0]:\n        labels         = np.transpose(np.array([y_true, y_pred]))\n        labels         = labels[labels[:, i].argsort()[::-1]]\n        weight         = np.where(labels[:,0]==0, 20, 1)\n        weight_random  = np.cumsum(weight / np.sum(weight))\n        total_pos      = np.sum(labels[:, 0] *  weight)\n        cum_pos_found  = np.cumsum(labels[:, 0] * weight)\n        lorentz        = cum_pos_found / total_pos\n        gini[i]        = np.sum((lorentz - weight_random) * weight)\n\n    return 0.5 * (gini[1]/gini[0] + top_four)","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:03.278556Z","iopub.execute_input":"2022-07-07T15:55:03.281783Z","iopub.status.idle":"2022-07-07T15:55:03.296495Z","shell.execute_reply.started":"2022-07-07T15:55:03.281739Z","shell.execute_reply":"2022-07-07T15:55:03.295246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train XGB for single fold; Compute Permutation importance","metadata":{}},{"cell_type":"code","source":"COMPUTE_PERM_IMPORTANCE = True\nONE_FOLD_ONLY = True","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:03.302015Z","iopub.execute_input":"2022-07-07T15:55:03.305055Z","iopub.status.idle":"2022-07-07T15:55:03.311736Z","shell.execute_reply.started":"2022-07-07T15:55:03.305017Z","shell.execute_reply":"2022-07-07T15:55:03.310554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"importances = []\noof = []\ntrain = train.to_pandas() # free GPU memory\nTRAIN_SUBSAMPLE = 1.0\ngc.collect()\n\nskf = KFold(n_splits=FOLDS, shuffle=True, random_state=SEED)\nfor fold,(train_idx, valid_idx) in enumerate(skf.split(\n            train, train.target )):\n    \n    # TRAIN WITH SUBSAMPLE OF TRAIN FOLD DATA\n    if TRAIN_SUBSAMPLE<1.0:\n        np.random.seed(SEED)\n        train_idx = np.random.choice(train_idx, \n                       int(len(train_idx)*TRAIN_SUBSAMPLE), replace=False)\n        np.random.seed(None)\n    \n    print('#'*25)\n    print('### Fold',fold+1)\n    print('### Train size',len(train_idx),'Valid size',len(valid_idx))\n    print(f'### Training with {int(TRAIN_SUBSAMPLE*100)}% fold data...')\n    print('#'*25)\n    \n    # TRAIN, VALID, TEST FOR FOLD K\n    Xy_train = IterLoadForDMatrix(train.loc[train_idx], FEATURES, 'target')\n    X_valid = train.loc[valid_idx, FEATURES]\n    y_valid = train.loc[valid_idx, 'target']\n    \n    dtrain = xgb.DeviceQuantileDMatrix(Xy_train, max_bin=256)\n    dvalid = xgb.DMatrix(data=X_valid, label=y_valid)\n    \n    # TRAIN MODEL FOLD K\n    model = xgb.train(xgb_parms, \n                dtrain=dtrain,\n                evals=[(dtrain,'train'),(dvalid,'valid')],\n                num_boost_round=9999,\n                early_stopping_rounds=100,\n                verbose_eval=100)\n    model.save_model(f'XGB_v{VER}_fold{fold}.xgb')\n    \n    # GET FEATURE IMPORTANCE FOR FOLD K\n    dd = model.get_score(importance_type='weight')\n    df = pd.DataFrame({'feature':dd.keys(),f'importance_{fold}':dd.values()})\n    importances.append(df)\n            \n    # INFER OOF FOLD K\n    oof_preds = model.predict(dvalid)\n    acc = amex_metric_mod(y_valid.values, oof_preds)\n    print('Kaggle Metric =',acc,'\\n')\n    \n    # SAVE OOF\n    df = train.loc[valid_idx, ['customer_ID','target'] ].copy()\n    df['oof_pred'] = oof_preds\n    oof.append( df )\n    \n    \n    if COMPUTE_PERM_IMPORTANCE:\n            results = []\n            print(' Computing Permutation feature importance...')\n            \n            # COMPUTE BASELINE (NO SHUFFLE)\n            oof_preds = model.predict(dvalid)\n            baseline_acc = amex_metric_mod(y_valid.values, oof_preds)\n            results.append({'feature':'BASELINE','metric':baseline_acc})           \n\n            for k in tqdm(range(len(FEATURES))):\n                \n                # SHUFFLE FEATURE K\n                save_col = X_valid.iloc[:,k].copy()\n                X_valid.iloc[:,k] = np.random.permutation(X_valid.iloc[:,k])\n                \n                dvalid = xgb.DMatrix(data=X_valid, label=y_valid)\n                        \n                # COMPUTE OOF MAE WITH FEATURE K SHUFFLED\n                oof_preds = model.predict(dvalid)\n                acc = amex_metric_mod(y_valid.values, oof_preds)\n                results.append({'feature':FEATURES[k],'metric':acc})\n                X_valid.iloc[:,k] = save_col\n         \n            # DISPLAY XGB FEATURE IMPORTANCE\n            print()\n            df = pd.DataFrame(results)\n            df = df.sort_values('metric', ascending = False)\n            # SAVE XGB FEATURE IMPORTANCE\n            df.to_csv(f'perm_feature_importance_fold_{fold+1}.csv',index=False)\n            \n            df = df.head(50)\n            \n            plt.figure(figsize=(10,20))\n            plt.barh(np.arange(50),df.metric)\n            plt.yticks(np.arange(50),df.feature.values)\n            plt.title('XGB Permutation Feature Importance: Top 50',size=16)\n            plt.xlim(0.7915, 0.7925)\n            plt.ylim((-1,50))\n            plt.plot([baseline_acc,baseline_acc],[-1,50], '--', color='orange',\n                     label=f'Baseline OOF\\nKaggle Metric={baseline_acc:.3f}')\n            plt.xlabel(f'Fold {fold+1} OOF Kaggle Metric with feature permuted',size=14)\n            plt.ylabel('Feature',size=14)\n            plt.legend()\n            plt.show()\n\n    \n    del dtrain, Xy_train, dd, df\n    del X_valid, y_valid, dvalid, model\n    _ = gc.collect()\n    \n    if ONE_FOLD_ONLY: break","metadata":{"execution":{"iopub.status.busy":"2022-07-07T15:55:03.317319Z","iopub.execute_input":"2022-07-07T15:55:03.317597Z","iopub.status.idle":"2022-07-07T16:00:59.363737Z","shell.execute_reply.started":"2022-07-07T15:55:03.31755Z","shell.execute_reply":"2022-07-07T16:00:59.361715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Interesting results, definitely looks there is room for improvement from the baseline by eliminating some features from the model ","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv(f'perm_feature_importance_fold_{fold+1}.csv')\nprint(df)","metadata":{},"execution_count":null,"outputs":[]}]}