{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":67223,"databundleVersionId":7463838,"sourceType":"competition"}],"dockerImageVersionId":30626,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Benchmarking GBDT for tabular data\n\nTabular data benchmark: ensemble of 5 un-tuned catboost.\nCatboost has been choosen for: best performance out of the box and easy handling of categorical data.","metadata":{}},{"cell_type":"code","source":"import numpy as np, pandas as pd\nimport os\nimport json\nfrom xgboost import XGBRegressor, XGBClassifier\nfrom sklearn.metrics import log_loss, mean_squared_error\nfrom sklearn.preprocessing import OneHotEncoder","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-01-24T08:03:48.231778Z","iopub.execute_input":"2024-01-24T08:03:48.232243Z","iopub.status.idle":"2024-01-24T08:03:48.238386Z","shell.execute_reply.started":"2024-01-24T08:03:48.232209Z","shell.execute_reply":"2024-01-24T08:03:48.237166Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path = '/kaggle/input/bench-tab-v1/'\n\ntasks = json.load(open(f'{path}train/dict_task.json'))\nsuits = json.load(open(f'{path}train/dict_suit.json'))\n\nDEBUG = False\nsuits = {'334': [361110, 361111], '335': [361093]} if DEBUG else suits\nn_seeds = 2 if DEBUG else 5\n\ndef prepare_sub(data, identifier):\n    data = pd.DataFrame(data)\n    data.columns = ['target']\n    data['ID'] =  identifier + '_' + data.index.astype(str)\n    columns = ['ID','target']\n    return data[columns]\n\nres_gbdt = {}\nsub = []\n\nparams = {\n    'boosting_type':'gbdt'\n}\n\nfor t in suits:\n    print(t)\n    for suit in suits[t]:\n        \n        identifier = f'{t}_{suit}'\n        task_type = tasks[t]\n        var_type = task_type['features']\n        target_type = task_type['target']\n\n        X = pd.read_parquet(f'{path}train/{identifier}/data_train.parquet')\n        X_test = pd.read_parquet(f'{path}train/{identifier}/data_test.parquet')\n        y = pd.read_parquet(f'{path}train/{identifier}/target_train.parquet')\n        test_idx = X_test.index.copy()\n        \n        names = json.load(open(f'{path}train/{identifier}/attribute_names.json'))\n        cat_indicator = json.load(open(f'{path}train/{identifier}/categorical_indicator.json'))\n        \n        X.columns = [c.replace(':','') for c in X.columns]\n        X_test.columns = [c.replace(':','') for c in X_test.columns]\n        \n        preds = []\n        \n        if var_type == 'num+cat':\n            enc = OneHotEncoder(handle_unknown='ignore')\n            X_cat = enc.fit_transform(X.loc[:,cat_indicator].copy())\n            X_test_cat = enc.transform(X_test.loc[:,cat_indicator].copy())            \n            X = pd.concat([X.loc[:,[not c for c in cat_indicator]].reset_index(drop=True).copy(), pd.DataFrame(X_cat.toarray())],axis=1)\n            X_test = pd.concat([X_test.loc[:,[not c for c in cat_indicator]].reset_index(drop=True).copy(), pd.DataFrame(X_test_cat.toarray())],axis=1)\n            X.columns = X.columns.astype(str)\n            X_test.columns = X_test.columns.astype(str)\n        \n        \n        for seed in range(n_seeds):\n        \n            gbdt_model = XGBRegressor(random_seed=seed, **params) if target_type=='num' else XGBClassifier(random_seed=seed, **params)  \n            gbdt_model = gbdt_model.fit(X, y.values)\n            \n            if target_type=='num':\n                preds.append(gbdt_model.predict(X_test))\n            else:\n                preds.append(gbdt_model.predict_proba(X_test)[:,1])\n            \n        preds = np.mean(np.array(preds),axis=0)\n\n        preds = pd.DataFrame(preds)\n        preds.index = test_idx\n        \n        # appends empty tests / solutions\n        sub.append(prepare_sub(preds, identifier))\n        \n        print('')\n        print(f'{identifier=} {var_type=} {target_type=}')","metadata":{"execution":{"iopub.status.busy":"2024-01-24T08:03:48.243513Z","iopub.execute_input":"2024-01-24T08:03:48.243881Z","iopub.status.idle":"2024-01-24T08:03:54.513023Z","shell.execute_reply.started":"2024-01-24T08:03:48.243850Z","shell.execute_reply":"2024-01-24T08:03:54.511804Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub = pd.concat(sub).reset_index(drop=True)\ndisplay(sub.head())\nsub.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2024-01-24T08:03:54.518574Z","iopub.execute_input":"2024-01-24T08:03:54.520480Z","iopub.status.idle":"2024-01-24T08:03:54.634441Z","shell.execute_reply.started":"2024-01-24T08:03:54.520410Z","shell.execute_reply":"2024-01-24T08:03:54.632819Z"},"trusted":true},"execution_count":null,"outputs":[]}]}