{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":35332,"databundleVersionId":3723648,"sourceType":"competition"},{"sourceId":3739819,"sourceType":"datasetVersion","datasetId":2231132}],"dockerImageVersionId":30198,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## What the Challenge Is About\n**Goal:** Predict whether a customer will default on their credit card payments in the future.  \n**Context:** American Express (Amex) wants better machine learning models to manage risk → deciding who gets approved, how much credit to offer, etc.  \n**Impact:** Better models mean:\n* More customers get approved fairly.\n* Fewer defaults for Amex → better business.\n* A real-world ML problem at industrial scale.  \n\n## Key Challenges\n**Time-series data →** Each customer has multiple rows (monthly). You must aggregate or model sequences.  \n**Huge dataset →** Industrial scale (GBs). You’ll need memory-efficient pipelines (parquet files, groupby aggregation, etc.).  \n**Custom metric →** Not just accuracy or AUC. You need to optimize for Amex metric directly.  \n**Feature engineering →** Data is anonymized, so domain knowledge is limited. Success depends on smart transformations.","metadata":{}},{"cell_type":"markdown","source":"# Load Libraries","metadata":{}},{"cell_type":"code","source":"# LOAD LIBRARIES\nimport pandas as pd, numpy as np # CPU libraries\nimport cupy, cudf # GPU libraries\nimport matplotlib.pyplot as plt, gc, os\n\nprint('RAPIDS version',cudf.__version__)","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:01:19.491660Z","iopub.execute_input":"2025-09-09T09:01:19.492154Z","iopub.status.idle":"2025-09-09T09:01:22.946788Z","shell.execute_reply.started":"2025-09-09T09:01:19.492059Z","shell.execute_reply":"2025-09-09T09:01:22.945819Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"VER = 1 # VERSION NAME FOR SAVED MODEL FILES\nSEED = 42 # TRAIN RANDOM SEED\nNAN_VALUE = -127 # FILL NAN VALUE\nFOLDS = 5 # FOLDS PER MODEL","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:01:22.948932Z","iopub.execute_input":"2025-09-09T09:01:22.949331Z","iopub.status.idle":"2025-09-09T09:01:22.954032Z","shell.execute_reply.started":"2025-09-09T09:01:22.949292Z","shell.execute_reply":"2025-09-09T09:01:22.953166Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Process and Feature Engineer Train Data\nWe will load @raddar Kaggle dataset from [here][1] with discussion [here][2]. Then we will engineer features suggested by @huseyincot in his notebooks [here][3] and [here][4]. We will use [RAPIDS][5] and the GPU to create new features quickly.\n\n[1]: https://www.kaggle.com/datasets/raddar/amex-data-integer-dtypes-parquet-format\n[2]: https://www.kaggle.com/competitions/amex-default-prediction/discussion/328514\n[3]: https://www.kaggle.com/code/huseyincot/amex-catboost-0-793\n[4]: https://www.kaggle.com/code/huseyincot/amex-agg-data-how-it-created\n[5]: https://rapids.ai/","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":"2025-09-09T09:01:22.955399Z","iopub.execute_input":"2025-09-09T09:01:22.956379Z","iopub.status.idle":"2025-09-09T09:01:45.338061Z","shell.execute_reply.started":"2025-09-09T09:01:22.956336Z","shell.execute_reply":"2025-09-09T09:01:45.337171Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**5,531,451 rows** - Each row = one monthly record (statement) for one customer.  \n**190 columns** - Features: customer_ID, S_2(date), other variables (B_1, D_39, R_1, etc.)","metadata":{}},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:01:45.339939Z","iopub.execute_input":"2025-09-09T09:01:45.340260Z","iopub.status.idle":"2025-09-09T09:01:45.555600Z","shell.execute_reply.started":"2025-09-09T09:01:45.340232Z","shell.execute_reply":"2025-09-09T09:01:45.554741Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-09-09T09:01:45.556709Z","iopub.execute_input":"2025-09-09T09:01:45.557040Z","iopub.status.idle":"2025-09-09T09:01:46.695015Z","shell.execute_reply.started":"2025-09-09T09:01:45.557011Z","shell.execute_reply":"2025-09-09T09:01:46.694085Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**458,913 rows** - Each row corresponds to a unique customer_ID.  \n\n**918 columns** - New aggregating features :  \n* 1 cat feature x 3 (count,last,nunique) = 33  \n* 190 - 11cat - 2excluded x 5 (mean,std,min,max,last) = 885  \n* total = 885 + 33 = 918  ","metadata":{}},{"cell_type":"code","source":"# load label\ntargets = cudf.read_csv('../input/amex-default-prediction/train_labels.csv')\ntargets.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-09T09:01:46.696046Z","iopub.execute_input":"2025-09-09T09:01:46.696328Z","iopub.status.idle":"2025-09-09T09:01:47.215963Z","shell.execute_reply.started":"2025-09-09T09:01:46.696303Z","shell.execute_reply":"2025-09-09T09:01:47.215089Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"0 - Customer did not default (paid on time)  \n1 - Customer defaulted (missed payment / bad account behavior)","metadata":{}},{"cell_type":"code","source":"# ADD TARGETS\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]\n\ntrain.shape","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:01:47.217306Z","iopub.execute_input":"2025-09-09T09:01:47.217728Z","iopub.status.idle":"2025-09-09T09:01:48.034464Z","shell.execute_reply.started":"2025-09-09T09:01:47.217688Z","shell.execute_reply":"2025-09-09T09:01:48.033559Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"added 2 new columns (customer_ID and target)","metadata":{}},{"cell_type":"markdown","source":"# Train XGB\nWe will train using `DeviceQuantileDMatrix`. This has a very small GPU memory footprint.","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":"2025-09-09T09:01:48.035546Z","iopub.execute_input":"2025-09-09T09:01:48.035829Z","iopub.status.idle":"2025-09-09T09:01:48.125023Z","shell.execute_reply.started":"2025-09-09T09:01:48.035804Z","shell.execute_reply":"2025-09-09T09:01:48.124136Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-09-09T09:01:48.126003Z","iopub.execute_input":"2025-09-09T09:01:48.126285Z","iopub.status.idle":"2025-09-09T09:01:48.135133Z","shell.execute_reply.started":"2025-09-09T09:01:48.126259Z","shell.execute_reply":"2025-09-09T09:01:48.134180Z"},"trusted":true},"outputs":[],"execution_count":null},{"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":"2025-09-09T09:01:48.137313Z","iopub.execute_input":"2025-09-09T09:01:48.137634Z","iopub.status.idle":"2025-09-09T09:01:48.148508Z","shell.execute_reply.started":"2025-09-09T09:01:48.137605Z","shell.execute_reply":"2025-09-09T09:01:48.147578Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Training a Machine Learning Model**\n1. Load data - Features: Predictors, Labels: What you want to predict\n2. Choose Model and Parameters - eg EGBoost, Linear Regression..\n3. Spilt data for training - Training and validation sets\n5. Train and save model \n\n**Inference (Prediction)**\n1. Load trained model and new data\n2. Predict and save prediction","metadata":{}},{"cell_type":"markdown","source":"# Train Model","metadata":{}},{"cell_type":"code","source":"importances = []\noof = []\ntrain = train.to_pandas() # free GPU memory\nTRAIN_SUBSAMPLE = 0.1 # 1.0\ngc.collect()\n\nskf = KFold(n_splits=FOLDS, shuffle=True, random_state=SEED)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-09T09:01:48.149530Z","iopub.execute_input":"2025-09-09T09:01:48.149899Z","iopub.status.idle":"2025-09-09T09:01:53.556856Z","shell.execute_reply.started":"2025-09-09T09:01:48.149851Z","shell.execute_reply":"2025-09-09T09:01:53.555693Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for 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    del dtrain, Xy_train, dd, df\n    del X_valid, y_valid, dvalid, model\n    _ = gc.collect()\n    \nprint('#'*25)\noof = pd.concat(oof,axis=0,ignore_index=True).set_index('customer_ID')\nacc = amex_metric_mod(oof.target.values, oof.oof_pred.values)\nprint('OVERALL CV Kaggle Metric =',acc)","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2025-09-09T09:01:53.558173Z","iopub.execute_input":"2025-09-09T09:01:53.558490Z","iopub.status.idle":"2025-09-09T09:03:00.445839Z","shell.execute_reply.started":"2025-09-09T09:01:53.558461Z","shell.execute_reply":"2025-09-09T09:03:00.444809Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"* Lower logloss → better predictions  \n* Print every 100 round, stop if it stop improving","metadata":{}},{"cell_type":"code","source":"# CLEAN RAM\ndel train\n_ = gc.collect()","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:03:00.446893Z","iopub.execute_input":"2025-09-09T09:03:00.447216Z","iopub.status.idle":"2025-09-09T09:03:00.596760Z","shell.execute_reply.started":"2025-09-09T09:03:00.447188Z","shell.execute_reply":"2025-09-09T09:03:00.595797Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Save OOF Preds","metadata":{}},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\nthreshold = 0.5\noof_preds_binary = (oof['oof_pred'] > threshold).astype(int)\ncm_raw = confusion_matrix(oof['target'], oof_preds_binary) # Calculate the raw confusion matrix counts\ncm_row_percent = cm_raw.astype('float') / cm_raw.sum(axis=1)[:, np.newaxis] # Calculate the percentage of each cell relative to its row (true label)\nlabels = np.asarray([f'{raw}\\n({row_percent:.1%})' for raw, row_percent in zip(cm_raw.flatten(), cm_row_percent.flatten())]).reshape(2, 2) # Create a DataFrame for the annotations\n\nplt.figure(figsize=(10, 8))\nsns.heatmap(cm_raw, annot=labels, fmt='', cmap='Blues', xticklabels=['Predicted 0', 'Predicted 1'], yticklabels=['Actual 0', 'Actual 1'])\nplt.title('Confusion Matrix: Counts & Row Percentages')\nplt.xlabel('Predicted Label')\nplt.ylabel('True Label')\nplt.show()\n\ndel oof_preds_binary, cm_raw, cm_row_percent, labels, oof\n_ = gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-09T09:03:00.598124Z","iopub.execute_input":"2025-09-09T09:03:00.598590Z","iopub.status.idle":"2025-09-09T09:03:01.169643Z","shell.execute_reply.started":"2025-09-09T09:03:00.598556Z","shell.execute_reply":"2025-09-09T09:03:01.168597Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"**Overall Interpretation:** The model is highly accurate at identifying negative cases but has a significant number of false negatives, meaning it fails to identify a notable portion of positive cases.","metadata":{}},{"cell_type":"markdown","source":"# Feature Importance","metadata":{}},{"cell_type":"code","source":"df = importances[0].copy()\n\nfor k in range(1, FOLDS):\n    df = df.merge(importances[k], on='feature', how='left')\n\ndf['importance'] = df.iloc[:, 1:].mean(axis=1)\n\ndf = df.sort_values('importance', ascending=False)\n\nNUM_FEATURES = 20\nplt.figure(figsize=(10, 5 * NUM_FEATURES // 10))\nplt.barh(np.arange(NUM_FEATURES, 0, -1), df.importance.values[:NUM_FEATURES])\nplt.yticks(np.arange(NUM_FEATURES, 0, -1), df.feature.values[:NUM_FEATURES])\nplt.title(f'XGB Feature Importance - Top {NUM_FEATURES}')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:03:01.170985Z","iopub.execute_input":"2025-09-09T09:03:01.171373Z","iopub.status.idle":"2025-09-09T09:03:01.469227Z","shell.execute_reply.started":"2025-09-09T09:03:01.171344Z","shell.execute_reply":"2025-09-09T09:03:01.468542Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Process and Feature Engineer Test Data\nWe will load @raddar Kaggle dataset from [here][1] with discussion [here][2]. Then we will engineer features suggested by @huseyincot in his notebooks [here][1] and [here][4]. We will use [RAPIDS][5] and the GPU to create new features quickly.\n\n[1]: https://www.kaggle.com/datasets/raddar/amex-data-integer-dtypes-parquet-format\n[2]: https://www.kaggle.com/competitions/amex-default-prediction/discussion/328514\n[3]: https://www.kaggle.com/code/huseyincot/amex-catboost-0-793\n[4]: https://www.kaggle.com/code/huseyincot/amex-agg-data-how-it-created\n[5]: https://rapids.ai/","metadata":{}},{"cell_type":"code","source":"# CALCULATE SIZE OF EACH SEPARATE TEST PART\ndef get_rows(customers, test, NUM_PARTS = 4, verbose = ''):\n    chunk = len(customers)//NUM_PARTS\n    if verbose != '':\n        print(f'We will process {verbose} data as {NUM_PARTS} separate parts.')\n        print(f'There will be {chunk} customers in each part (except the last part).')\n        print('Below are number of rows in each part:')\n    rows = []\n\n    for k in range(NUM_PARTS):\n        if k==NUM_PARTS-1: cc = customers[k*chunk:]\n        else: cc = customers[k*chunk:(k+1)*chunk]\n        s = test.loc[test.customer_ID.isin(cc)].shape[0]\n        rows.append(s)\n    if verbose != '': print( rows )\n    return rows,chunk","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:03:01.470562Z","iopub.execute_input":"2025-09-09T09:03:01.471291Z","iopub.status.idle":"2025-09-09T09:03:01.478342Z","shell.execute_reply.started":"2025-09-09T09:03:01.471253Z","shell.execute_reply":"2025-09-09T09:03:01.477349Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# COMPUTE SIZE OF 4 PARTS FOR TEST DATA\nNUM_PARTS = 4\nTEST_PATH = '../input/amex-data-integer-dtypes-parquet-format/test.parquet'\n\nprint(f'Reading test data...')\ntest = read_file(path = TEST_PATH, usecols = ['customer_ID','S_2'])\ncustomers = test[['customer_ID']].drop_duplicates().sort_index().values.flatten()\nrows,num_cust = get_rows(customers, test[['customer_ID']], NUM_PARTS = NUM_PARTS, verbose = 'test')\n\nskip_rows = 0\nskip_cust = 0\ntest_preds = []","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-09T09:03:01.479403Z","iopub.execute_input":"2025-09-09T09:03:01.479745Z","iopub.status.idle":"2025-09-09T09:03:04.302523Z","shell.execute_reply.started":"2025-09-09T09:03:01.479718Z","shell.execute_reply":"2025-09-09T09:03:04.301595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# INFER TEST DATA IN PARTS\nfor k in range(NUM_PARTS):\n    \n    # READ PART OF TEST DATA\n    print(f'\\nReading test data...')\n    test = read_file(path = TEST_PATH)\n    test = test.iloc[skip_rows:skip_rows+rows[k]]\n    skip_rows += rows[k]\n    print(f'=> Test part {k+1} has shape', test.shape )\n    \n    # PROCESS AND FEATURE ENGINEER PART OF TEST DATA\n    test = process_and_feature_engineer(test)\n    if k==NUM_PARTS-1: test = test.loc[customers[skip_cust:]]\n    else: test = test.loc[customers[skip_cust:skip_cust+num_cust]]\n    skip_cust += num_cust\n    \n    # TEST DATA FOR XGB\n    X_test = test[FEATURES]\n    dtest = xgb.DMatrix(data=X_test)\n    test = test[['P_2_mean']] # reduce memory\n    del X_test\n    gc.collect()\n\n    # INFER XGB MODELS ON TEST DATA\n    model = xgb.Booster()\n    model.load_model(f'XGB_v{VER}_fold0.xgb')\n    preds = model.predict(dtest)\n    for f in range(1,FOLDS):\n        model.load_model(f'XGB_v{VER}_fold{f}.xgb')\n        preds += model.predict(dtest)\n    preds /= FOLDS\n    test_preds.append(preds)\n\n    # CLEAN MEMORY\n    del dtest, model\n    _ = gc.collect()","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:03:04.303874Z","iopub.execute_input":"2025-09-09T09:03:04.304302Z","iopub.status.idle":"2025-09-09T09:04:22.896060Z","shell.execute_reply.started":"2025-09-09T09:03:04.304262Z","shell.execute_reply":"2025-09-09T09:04:22.895355Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Create Submission CSV","metadata":{}},{"cell_type":"code","source":"# WRITE SUBMISSION FILE\ntest_preds = np.concatenate(test_preds)\ntest = cudf.DataFrame(index=customers,data={'prediction':test_preds})\nsub = cudf.read_csv('../input/amex-default-prediction/sample_submission.csv')[['customer_ID']]\nsub['customer_ID_hash'] = sub['customer_ID'].str[-16:].str.hex_to_int().astype('int64')\nsub = sub.set_index('customer_ID_hash')\nsub = sub.merge(test[['prediction']], left_index=True, right_index=True, how='left')\nsub = sub.reset_index(drop=True)\n\n# DISPLAY PREDICTIONS\nsub.to_csv(f'submission_xgb_v{VER}.csv',index=False)\nprint('Submission file shape is', sub.shape )\nsub.head()","metadata":{"execution":{"iopub.status.busy":"2025-09-09T09:04:22.897493Z","iopub.execute_input":"2025-09-09T09:04:22.897890Z","iopub.status.idle":"2025-09-09T09:04:24.570432Z","shell.execute_reply.started":"2025-09-09T09:04:22.897841Z","shell.execute_reply":"2025-09-09T09:04:24.569487Z"},"trusted":true},"outputs":[],"execution_count":null}]}