{"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":"code","source":"# If you like, upvote beezus666's script and the ensemeble sources\n#https://www.kaggle.com/code/beezus666/ensemble-weighted-average","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-06-04T05:50:10.710081Z","iopub.execute_input":"2022-06-04T05:50:10.710992Z","iopub.status.idle":"2022-06-04T05:50:18.306822Z","shell.execute_reply.started":"2022-06-04T05:50:10.710954Z","shell.execute_reply":"2022-06-04T05:50:18.305766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier\nimport gc; gc.enable()\nfrom sklearn import *\nimport pandas as pd\nimport numpy as np\nimport numba, os\n\nsub1 = pd.read_csv('../input/ensemble-weighted-average/submission.csv')\ntraini = pd.read_csv('/kaggle/input/amex-default-prediction/train_data.csv', parse_dates=['S_2'], chunksize=400_000, iterator=True)\ntesti = pd.read_csv('/kaggle/input/amex-default-prediction/test_data.csv', parse_dates=['S_2'], chunksize=400_000, iterator=True) \nlabels = pd.read_csv('/kaggle/input/amex-default-prediction/train_labels.csv')","metadata":{"execution":{"iopub.status.busy":"2022-06-04T05:50:22.324284Z","iopub.execute_input":"2022-06-04T05:50:22.324835Z","iopub.status.idle":"2022-06-04T05:50:22.328484Z","shell.execute_reply.started":"2022-06-04T05:50:22.324797Z","shell.execute_reply":"2022-06-04T05:50:22.327687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ntrain = []\nfor df in traini:\n    if len(train)>0: train = pd.concat([train, df])\n    else: train = df[:]\n    train.sort_values(by=['S_2'], inplace=True)\n    train.reset_index(drop=True, inplace=True)\n    train.drop_duplicates(subset=['customer_ID'], keep='last', inplace=True)\n    del df; gc.collect()\ntrain = pd.merge(train, labels, how='inner', on=['customer_ID'])\ndel labels; gc.collect()\ncol = [c for c in train if c not in ['customer_ID', 'target','S_2']]\ntrain.fillna(0).to_csv('train.csv', index=False)\ndel train; del traini; gc.collect()\n\ntest = []\nfor df in testi:\n    if len(test)>0: test = pd.concat([test, df])\n    else: test = df[:]\n    test.sort_values(by=['S_2'], inplace=True)\n    test.reset_index(drop=True, inplace=True)\n    test.drop_duplicates(subset=['customer_ID'], keep='last', inplace=True)\n    del df; gc.collect()\ntest.fillna(0).to_csv('test.csv', index=False)\ndel test; del testi; gc.collect()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# https://www.kaggle.com/competitions/amex-default-prediction/discussion/328020\n# https://www.kaggle.com/code/rohanrao/amex-competition-metric-implementations\nclass CB_Amex_Metric(object):\n    def get_final_error(self, error, weight):\n        return error\n    def is_max_optimal(self):\n        return True\n    def evaluate(self, y_pred, y_true, weight):\n        y_pred = y_pred[0]\n        indices = np.argsort(y_pred)[::-1]\n        preds, target = y_pred[indices], y_true[indices]\n        weight = 20.0 - target * 19.0\n        cum_norm_weight = (weight / weight.sum()).cumsum()\n        four_pct_mask = cum_norm_weight <= 0.04\n        d = np.sum(target[four_pct_mask]) / np.sum(target)\n        weighted_target = target * weight\n        lorentz = (weighted_target / weighted_target.sum()).cumsum()\n        gini = ((lorentz - cum_norm_weight) * weight).sum()\n        n_pos = np.sum(target)\n        n_neg = target.shape[0] - n_pos\n        gini_max = 10 * n_neg * (n_pos + 20 * n_neg - 19) / (n_pos + 20 * n_neg)\n        g = gini / gini_max\n        return 0.5 * (g + d), 0","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('train.csv')\ncat_features = ['B_30', 'B_31', 'B_38', 'D_114', 'D_116', 'D_117', 'D_120', 'D_126', 'D_63', 'D_64', 'D_66', 'D_68']\nfor c in cat_features: train[c] = train[c].astype(str)\n\nx1, x2, y1, y2 = model_selection.train_test_split(train[col], train.target, test_size=0.20, random_state=22)\ndel train; gc.collect()\nos.remove ('train.csv')\n\nclf = CatBoostClassifier(iterations=1000, random_state=22, nan_mode='Min', eval_metric=CB_Amex_Metric())\nclf.fit(x1, y1, eval_set=[(x2, y2)], cat_features=cat_features,  verbose=50)\npreds = clf.predict_proba(x2)[:, 1]","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv('test.csv')\nfor c in cat_features: test[c] = test[c].astype(str)\ntest['prediction'] = clf.predict_proba(test[col])[:, 1]\nsub2 = test[['customer_ID', 'prediction']]\ndel test;  gc.collect()\nos.remove ('test.csv')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub2.columns = ['customer_ID', 'prediction2']\nblend = pd.merge(sub1, sub2, how='inner', on='customer_ID')\nblend.prediction = (blend.prediction * 0.955 + blend.prediction2 * 0.045)\nblend[['customer_ID', 'prediction']].to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]}]}