{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":81933,"databundleVersionId":9643020,"sourceType":"competition"},{"sourceId":9682055,"sourceType":"datasetVersion","datasetId":5918194}],"dockerImageVersionId":30776,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install tsflex --no-index --find-links=file:///kaggle/input/cmi-time-series-tools \n!pip install seglearn --no-index --find-links=file:///kaggle/input/cmi-time-series-tools  ","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:56:14.268763Z","iopub.execute_input":"2024-11-05T18:56:14.269076Z","iopub.status.idle":"2024-11-05T18:56:39.664933Z","shell.execute_reply.started":"2024-11-05T18:56:14.269042Z","shell.execute_reply":"2024-11-05T18:56:39.663966Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport polars as pl\nfrom seglearn.feature_functions import base_features, emg_features\nfrom tsflex.features import FeatureCollection, MultipleFeatureDescriptors\nfrom tsflex.features.integrations import seglearn_feature_dict_wrapper\nimport os\nimport random\nfrom sklearn.base import clone\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom scipy.optimize import minimize\nfrom concurrent.futures import ThreadPoolExecutor\nfrom tqdm import tqdm\nfrom colorama import Fore, Style\nfrom IPython.display import clear_output\nimport warnings\nfrom lightgbm import LGBMRegressor\nfrom xgboost import XGBRegressor\nfrom catboost import CatBoostRegressor\nfrom sklearn.ensemble import VotingRegressor\nfrom sklearn.impute import SimpleImputer\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:57:16.378257Z","iopub.execute_input":"2024-11-05T18:57:16.378764Z","iopub.status.idle":"2024-11-05T18:57:22.924003Z","shell.execute_reply.started":"2024-11-05T18:57:16.378711Z","shell.execute_reply":"2024-11-05T18:57:22.923014Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Set random seeds for reproducibility\nSEED = 42\nnp.random.seed(SEED)\nrandom.seed(SEED)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:57:34.174220Z","iopub.execute_input":"2024-11-05T18:57:34.175389Z","iopub.status.idle":"2024-11-05T18:57:34.180052Z","shell.execute_reply.started":"2024-11-05T18:57:34.175345Z","shell.execute_reply":"2024-11-05T18:57:34.178926Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Suppress warnings\nwarnings.filterwarnings('ignore')\n\n# Pandas option for displaying all columns\npd.options.display.max_columns = None","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:57:36.868587Z","iopub.execute_input":"2024-11-05T18:57:36.869004Z","iopub.status.idle":"2024-11-05T18:57:36.873656Z","shell.execute_reply.started":"2024-11-05T18:57:36.868949Z","shell.execute_reply":"2024-11-05T18:57:36.872583Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Constants\nn_splits = 5","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:23.116097Z","iopub.execute_input":"2024-11-05T18:58:23.116448Z","iopub.status.idle":"2024-11-05T18:58:23.120968Z","shell.execute_reply.started":"2024-11-05T18:58:23.116415Z","shell.execute_reply":"2024-11-05T18:58:23.119958Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load datasets\ntrain = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/train.csv')\ntest = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/test.csv')\nsample = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/sample_submission.csv')\n\nnumeric_columns = train.select_dtypes(include = ['float64', 'int64']).columns","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:35.131927Z","iopub.execute_input":"2024-11-05T18:58:35.132275Z","iopub.status.idle":"2024-11-05T18:58:35.266427Z","shell.execute_reply.started":"2024-11-05T18:58:35.132241Z","shell.execute_reply":"2024-11-05T18:58:35.265414Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class TSPipeline:\n    @staticmethod\n    def build_tsflex_features(df: pd.DataFrame):\n\n        df = df.to_pandas()\n        len = df.shape[0]\n\n        basic_feats = MultipleFeatureDescriptors(\n            functions=seglearn_feature_dict_wrapper(base_features()),\n            series_names=['X', 'Y', 'Z', 'enmo', 'anglez', 'light', 'battery_voltage'],\n            windows=[len],\n            strides=[len],\n        )\n        \n        emg_feats = emg_features()\n        del emg_feats['simple square integral']\n        \n        emg_feats = MultipleFeatureDescriptors(\n            functions=seglearn_feature_dict_wrapper(emg_feats),\n            series_names=['X', 'Y', 'Z', 'enmo', 'anglez', 'light', 'battery_voltage'],\n            windows=[len],\n            strides=[len],\n        )\n        \n        fc = FeatureCollection([basic_feats, emg_feats])\n        \n        df = fc.calculate(df,\n                          return_df=True, \n                          include_final_window=True, \n                          approve_sparsity=True, \n                          window_idx=\"begin\").astype(np.float32)\n\n        return df\n","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:42.889116Z","iopub.execute_input":"2024-11-05T18:58:42.889965Z","iopub.status.idle":"2024-11-05T18:58:42.897464Z","shell.execute_reply.started":"2024-11-05T18:58:42.889926Z","shell.execute_reply":"2024-11-05T18:58:42.896585Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def read_file(path) -> np.ndarray: \n    df = pl.read_parquet(path)\n    df = df.pipe(TSPipeline.build_tsflex_features)\n    return df.to_numpy().flatten()","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:46.617477Z","iopub.execute_input":"2024-11-05T18:58:46.618415Z","iopub.status.idle":"2024-11-05T18:58:46.623034Z","shell.execute_reply.started":"2024-11-05T18:58:46.618374Z","shell.execute_reply":"2024-11-05T18:58:46.621948Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def load_time_series(dir_path: str) -> dict:\n    time_series_store = {}\n    file_ind = os.listdir(dir_path)\n    for file_name in tqdm(file_ind):\n        file_id = file_name.split('=')[1]\n        file_path = os.path.join(dir_path + file_name, 'part-0.parquet')\n        df = read_file(file_path)\n        time_series_store[file_id] = df\n        \n    return time_series_store","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:50.218407Z","iopub.execute_input":"2024-11-05T18:58:50.218801Z","iopub.status.idle":"2024-11-05T18:58:50.224860Z","shell.execute_reply.started":"2024-11-05T18:58:50.218757Z","shell.execute_reply":"2024-11-05T18:58:50.223742Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Load time series data\ntrain_ts = load_time_series(\"/kaggle/input/child-mind-institute-problematic-internet-use/series_train.parquet/\")\ntest_ts = load_time_series(\"/kaggle/input/child-mind-institute-problematic-internet-use/series_test.parquet/\")","metadata":{"execution":{"iopub.status.busy":"2024-11-05T18:58:53.294683Z","iopub.execute_input":"2024-11-05T18:58:53.295084Z","iopub.status.idle":"2024-11-05T19:09:59.942947Z","shell.execute_reply.started":"2024-11-05T18:58:53.295047Z","shell.execute_reply":"2024-11-05T19:09:59.941817Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_ts = pd.DataFrame(train_ts).T\ntrain_ts.columns = [f'f{i}' for i in range(train_ts.shape[1])]\ntrain_ts = train_ts.reset_index()\ntrain_ts.rename(columns={'index': 'id'}, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:10:03.463625Z","iopub.execute_input":"2024-11-05T19:10:03.464565Z","iopub.status.idle":"2024-11-05T19:10:03.489201Z","shell.execute_reply.started":"2024-11-05T19:10:03.464505Z","shell.execute_reply":"2024-11-05T19:10:03.488360Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_ts = pd.DataFrame(test_ts).T\ntest_ts.columns = [f'f{i}' for i in range(test_ts.shape[1])]\ntest_ts = test_ts.reset_index()\ntest_ts.rename(columns={'index': 'id'}, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:10:13.824458Z","iopub.execute_input":"2024-11-05T19:10:13.825431Z","iopub.status.idle":"2024-11-05T19:10:13.835314Z","shell.execute_reply.started":"2024-11-05T19:10:13.825380Z","shell.execute_reply":"2024-11-05T19:10:13.834413Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Merge datasets\ntime_series_cols = train_ts.columns.tolist()\ntime_series_cols.remove(\"id\")\ntrain = pd.merge(train, train_ts, how=\"left\", on='id')\ntest = pd.merge(test, test_ts, how=\"left\", on='id')\ntrain = train.drop('id', axis=1)\ntest = test.drop('id', axis=1)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:10:34.997808Z","iopub.execute_input":"2024-11-05T19:10:34.998199Z","iopub.status.idle":"2024-11-05T19:10:35.046921Z","shell.execute_reply.started":"2024-11-05T19:10:34.998162Z","shell.execute_reply":"2024-11-05T19:10:35.046032Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train[time_series_cols] = train[time_series_cols].fillna(value=0)  \ntest[time_series_cols] = test[time_series_cols].fillna(value=0)  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T19:10:43.925911Z","iopub.execute_input":"2024-11-05T19:10:43.926289Z","iopub.status.idle":"2024-11-05T19:10:43.977416Z","shell.execute_reply.started":"2024-11-05T19:10:43.926252Z","shell.execute_reply":"2024-11-05T19:10:43.976391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Define feature columns\nfeaturesCols = ['Basic_Demos-Enroll_Season', 'Basic_Demos-Age', 'Basic_Demos-Sex', 'CGAS-Season', 'CGAS-CGAS_Score',\n                'Physical-Season', 'Physical-BMI', 'Physical-Height', 'Physical-Weight', 'Physical-Waist_Circumference',\n                'Physical-Diastolic_BP', 'Physical-HeartRate', 'Physical-Systolic_BP', 'Fitness_Endurance-Season',\n                'Fitness_Endurance-Max_Stage', 'Fitness_Endurance-Time_Mins', 'Fitness_Endurance-Time_Sec', 'FGC-Season',\n                'FGC-FGC_CU', 'FGC-FGC_CU_Zone', 'FGC-FGC_GSND', 'FGC-FGC_GSND_Zone', 'FGC-FGC_GSD', 'FGC-FGC_GSD_Zone',\n                'FGC-FGC_PU', 'FGC-FGC_PU_Zone', 'FGC-FGC_SRL', 'FGC-FGC_SRL_Zone', 'FGC-FGC_SRR', 'FGC-FGC_SRR_Zone',\n                'FGC-FGC_TL', 'FGC-FGC_TL_Zone', 'BIA-Season', 'BIA-BIA_Activity_Level_num', 'BIA-BIA_BMC', 'BIA-BIA_BMI',\n                'BIA-BIA_BMR', 'BIA-BIA_DEE', 'BIA-BIA_ECW', 'BIA-BIA_FFM', 'BIA-BIA_FFMI', 'BIA-BIA_FMI', 'BIA-BIA_Fat',\n                'BIA-BIA_Frame_num', 'BIA-BIA_ICW', 'BIA-BIA_LDM', 'BIA-BIA_LST', 'BIA-BIA_SMM', 'BIA-BIA_TBW',\n                'PAQ_A-Season', 'PAQ_A-PAQ_A_Total', 'PAQ_C-Season', 'PAQ_C-PAQ_C_Total', 'SDS-Season', 'SDS-SDS_Total_Raw',\n                'SDS-SDS_Total_T', 'PreInt_EduHx-Season', 'PreInt_EduHx-computerinternet_hoursday', 'sii']\nfeaturesCols += time_series_cols\ntrain = train[featuresCols]\ntrain = train.dropna(subset=['sii'])","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:10:49.559127Z","iopub.execute_input":"2024-11-05T19:10:49.559835Z","iopub.status.idle":"2024-11-05T19:10:49.584887Z","shell.execute_reply.started":"2024-11-05T19:10:49.559792Z","shell.execute_reply":"2024-11-05T19:10:49.584028Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cat_c = ['Basic_Demos-Enroll_Season', 'CGAS-Season', 'Physical-Season', 'Fitness_Endurance-Season', 'FGC-Season',\n         'BIA-Season', 'PAQ_A-Season', 'PAQ_C-Season', 'SDS-Season', 'PreInt_EduHx-Season']\n\ndef update(df):\n    global cat_c\n    for c in cat_c:\n        df[c] = df[c].fillna('Missing')\n        df[c] = df[c].astype('category')\n    return df\n\ntrain = update(train)\ntest = update(test)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:10:56.668743Z","iopub.execute_input":"2024-11-05T19:10:56.669105Z","iopub.status.idle":"2024-11-05T19:10:56.704412Z","shell.execute_reply.started":"2024-11-05T19:10:56.669073Z","shell.execute_reply":"2024-11-05T19:10:56.703658Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_mapping(column, dataset):\n    unique_values = dataset[column].unique()\n    return {value: idx for idx, value in enumerate(unique_values)}\n\nfor col in cat_c:\n    mapping = create_mapping(col, train)\n    train[col] = train[col].replace(mapping).astype(int)\n    test[col] = test[col].replace(create_mapping(col, test)).astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:11:00.107394Z","iopub.execute_input":"2024-11-05T19:11:00.107775Z","iopub.status.idle":"2024-11-05T19:11:00.160571Z","shell.execute_reply.started":"2024-11-05T19:11:00.107739Z","shell.execute_reply":"2024-11-05T19:11:00.159657Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sii = train['sii']\ntrain = train.drop(['sii'], axis=1)\n\ncol_features_imp = [item for item in featuresCols if item != 'sii']\nimputer = SimpleImputer(strategy='mean')\n\ntrain = imputer.fit_transform(train)                          \ntrain = pd.DataFrame(data = train, columns = col_features_imp)\n\ntest = imputer.transform(test)\ntest = pd.DataFrame(data = test, columns = col_features_imp)\n\ntrain['sii'] = sii.to_list()","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:11:14.085379Z","iopub.execute_input":"2024-11-05T19:11:14.085791Z","iopub.status.idle":"2024-11-05T19:11:14.143276Z","shell.execute_reply.started":"2024-11-05T19:11:14.085750Z","shell.execute_reply":"2024-11-05T19:11:14.142332Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"scaler = StandardScaler()\n\nnum_columns = [c for c in train.columns if c in numeric_columns and c not in ['sii']] \nnum_columns = num_columns + time_series_cols\n\ntrain_scalar = scaler.fit_transform(train[num_columns])  \ntest_scalar = scaler.transform(test[num_columns])\n\ntrain_scalar = pd.DataFrame(data = train_scalar, columns = num_columns)\ntest_scalar = pd.DataFrame(data = test_scalar, columns = num_columns)\n\nfor col in num_columns:\n    train.loc[:, col] = train_scalar[col].values\n    test.loc[:, col] = test_scalar[col].values","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T19:12:47.240390Z","iopub.execute_input":"2024-11-05T19:12:47.241283Z","iopub.status.idle":"2024-11-05T19:12:47.330373Z","shell.execute_reply.started":"2024-11-05T19:12:47.241242Z","shell.execute_reply":"2024-11-05T19:12:47.329613Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in cat_c:\n    train[i] = train[i].astype(int) \n    test[i] = test[i].astype(int) ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T19:13:04.357821Z","iopub.execute_input":"2024-11-05T19:13:04.358183Z","iopub.status.idle":"2024-11-05T19:13:04.371118Z","shell.execute_reply.started":"2024-11-05T19:13:04.358149Z","shell.execute_reply":"2024-11-05T19:13:04.370372Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lgb_params = {\n    'learning_rate': np.linspace(0.01, 0.1, num=100).tolist(),  \n    'max_depth': [3, 5, 8, 10, 12, 14],\n    'n_estimators': list(range(10, 400, 5)),\n    'num_leaves': list(range(10, 500, 5)),\n    'min_data_in_leaf': list(range(10, 50, 3)),\n    'feature_fraction': [round(x, 3) for x in np.linspace(0.3, 1.0, num=40)],  \n    'bagging_fraction': [round(x, 3) for x in np.linspace(0.3, 1.0, num=40)],  \n    'bagging_freq': list(range(2, 60, 2)),\n    'lambda_l1': np.linspace(0, 5, num=40).tolist(),\n    'lambda_l2': np.linspace(0, 5, num=40).tolist(),\n    'device': ['gpu']\n}","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:13:48.865415Z","iopub.execute_input":"2024-11-05T19:13:48.866331Z","iopub.status.idle":"2024-11-05T19:13:48.874656Z","shell.execute_reply.started":"2024-11-05T19:13:48.866289Z","shell.execute_reply":"2024-11-05T19:13:48.873578Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"xgb_params = {\n    'learning_rate': np.linspace(0.01, 0.1, num=100).tolist(),\n    'max_depth': [3, 5, 8, 10, 12, 14],\n    'n_estimators': list(range(10, 400, 5)),\n    'subsample': np.arange(0.1, 1.01, 0.05).tolist(),\n    'colsample_bytree': np.arange(0.1, 1.01, 0.05).tolist(),\n    'reg_alpha': np.arange(0.1, 10, 0.5).tolist(), \n    'reg_lambda': np.arange(0.1, 10, 0.5).tolist(),\n    'random_state': [42],\n    'tree_method': ['hist', 'approx', 'gpu_hist'],\n    'device': ['cuda']\n}","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:13:51.239844Z","iopub.execute_input":"2024-11-05T19:13:51.240221Z","iopub.status.idle":"2024-11-05T19:13:51.248188Z","shell.execute_reply.started":"2024-11-05T19:13:51.240186Z","shell.execute_reply":"2024-11-05T19:13:51.246476Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cat_boost_params = {\n    'learning_rate': np.linspace(0.01, 0.1, num=100).tolist(),\n    'depth': [3, 4, 5, 6, 7],\n    'iterations': list(range(10, 250, 10)),\n    'random_seed': [42],\n    'verbose': [0],\n    'l2_leaf_reg': list(range(10, 50, 10)),\n    'task_type': ['GPU']\n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T19:13:55.262097Z","iopub.execute_input":"2024-11-05T19:13:55.262837Z","iopub.status.idle":"2024-11-05T19:13:55.268345Z","shell.execute_reply.started":"2024-11-05T19:13:55.262794Z","shell.execute_reply":"2024-11-05T19:13:55.267279Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def quadratic_weighted_kappa(y_true, y_pred):\n    return cohen_kappa_score(y_true, y_pred, weights='quadratic')","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:13:58.578422Z","iopub.execute_input":"2024-11-05T19:13:58.579283Z","iopub.status.idle":"2024-11-05T19:13:58.583365Z","shell.execute_reply.started":"2024-11-05T19:13:58.579241Z","shell.execute_reply":"2024-11-05T19:13:58.582445Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def search_optimal_param(X: pd.DataFrame, model, param: dict):\n    \n    skfolds = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n    \n    x = X.copy()\n    y = x['sii']\n    _ = x.pop('sii') \n    \n    for num_fold, (train_index, val_index) in enumerate(skfolds.split(x, y)):\n        print('fold: ', num_fold+1)\n        X_train, X_val = x.iloc[train_index], x.iloc[val_index]\n        y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n        \n        model_fold = clone(model)\n        kappa_scorer = make_scorer(cohen_kappa_score)\n        search = RandomizedSearchCV(model_fold, param, scoring = kappa_scorer)\n        \n        search.fit(X_train, y_train)\n        predictions = search.predict(X_val)  \n        predictions = np.round(predictions)\n        \n        kappa_fold = quadratic_weighted_kappa(y_val, predictions)\n        \n        if num_fold == 0:\n            best_model_score = kappa_fold\n            best_model = search.best_estimator_  \n            best_params = search.best_params_\n            print('kappa: ', kappa_fold)\n            print('best_params:', best_params)\n            \n        elif kappa_fold > best_model_score:\n            best_model_score = kappa_fold\n            best_model = search.best_estimator_  \n            best_params = search.best_params_\n            print('kappa: ', kappa_fold)\n            print('best_params:', best_params)\n            \n    return best_model, best_params, best_model_score","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:14:49.366358Z","iopub.execute_input":"2024-11-05T19:14:49.367215Z","iopub.status.idle":"2024-11-05T19:14:49.376460Z","shell.execute_reply.started":"2024-11-05T19:14:49.367171Z","shell.execute_reply":"2024-11-05T19:14:49.375542Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# lgb = LGBMRegressor(verbose=-1)\n\n# lgb_best_model, lgb_best_params, lgb_best_score = search_optimal_param(train, lgb, lgb_params)\n# lgb_best_score = 0.4449055632128198\n\nlgb_best_params = {'num_leaves': 70,\n                   'n_estimators': 110,\n                   'min_data_in_leaf': 10,\n                   'max_depth': 3,\n                   'learning_rate': 0.07272727272727272,\n                   'lambda_l2': 3.7179487179487176,\n                   'lambda_l1': 0.641025641025641,\n                   'feature_fraction': 0.803,\n                   'device': 'gpu',\n                   'bagging_freq': 2,\n                   'bagging_fraction': 0.569}","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:15:31.059940Z","iopub.execute_input":"2024-11-05T19:15:31.060855Z","iopub.status.idle":"2024-11-05T19:15:31.065886Z","shell.execute_reply.started":"2024-11-05T19:15:31.060812Z","shell.execute_reply":"2024-11-05T19:15:31.064959Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# xgb = XGBRegressor()\n\n# xgb_best_model, xgb_best_params, xgb_best_score = search_optimal_param(train, xgb, xgb_params)\n# xgb_best_score = 0.46584022243922796\n\nxgb_best_params = {'tree_method': 'gpu_hist',\n                   'subsample': 0.3500000000000001,\n                   'reg_lambda': 5.6,\n                   'reg_alpha': 6.6,\n                   'random_state': 42,\n                   'n_estimators': 365,\n                   'max_depth': 12,\n                   'learning_rate': 0.024545454545454547,\n                   'device': 'cuda',\n                   'colsample_bytree': 0.7000000000000002}","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:16:12.361015Z","iopub.execute_input":"2024-11-05T19:16:12.361628Z","iopub.status.idle":"2024-11-05T19:16:12.366868Z","shell.execute_reply.started":"2024-11-05T19:16:12.361590Z","shell.execute_reply":"2024-11-05T19:16:12.365691Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# cat_boost = CatBoostRegressor(cat_features = cat_c)\n\n# cb_best_model, cb_best_params, cb_best_score = search_optimal_param(train, cat_boost, cat_boost_params)\n# cb_best_score = 0.4500549273522687\n\ncb_best_params = {'verbose': 0,\n                  'task_type': 'GPU',\n                  'random_seed': 42,\n                  'learning_rate': 0.07454545454545455,\n                  'l2_leaf_reg': 20,\n                  'iterations': 180,\n                  'depth': 3}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-05T19:17:04.907180Z","iopub.execute_input":"2024-11-05T19:17:04.907820Z","iopub.status.idle":"2024-11-05T19:17:04.912777Z","shell.execute_reply.started":"2024-11-05T19:17:04.907777Z","shell.execute_reply":"2024-11-05T19:17:04.911824Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def threshold_Rounder(oof_non_rounded, thresholds):\n    return np.where(oof_non_rounded < thresholds[0], 0,\n                    np.where(oof_non_rounded < thresholds[1], 1,\n                             np.where(oof_non_rounded < thresholds[2], 2, 3)))\n\ndef evaluate_predictions(thresholds, y_true, oof_non_rounded):\n    rounded_p = threshold_Rounder(oof_non_rounded, thresholds)\n    return -quadratic_weighted_kappa(y_true, rounded_p)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:17:23.465687Z","iopub.execute_input":"2024-11-05T19:17:23.466588Z","iopub.status.idle":"2024-11-05T19:17:23.472275Z","shell.execute_reply.started":"2024-11-05T19:17:23.466546Z","shell.execute_reply":"2024-11-05T19:17:23.471219Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def TrainML(model_class, test_data):\n    \n    X = train.drop(['sii'], axis=1)    \n    y = train['sii']   \n\n    X_res, y_res = X, y\n\n    SKF = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED)\n    train_S = []\n    test_S = []\n    oof_non_rounded = np.zeros(len(y_res), dtype=float)\n    oof_rounded = np.zeros(len(y_res), dtype=int)\n    test_preds = np.zeros((len(test_data), n_splits))\n\n    for fold, (train_idx, val_idx) in enumerate(SKF.split(X_res, y_res)):\n        X_train, X_val = X_res.iloc[train_idx], X_res.iloc[val_idx]\n        y_train, y_val = y_res.iloc[train_idx], y_res.iloc[val_idx]\n\n        model = clone(model_class)\n        model.fit(X_train, y_train)\n        y_train_pred = model.predict(X_train)\n        y_val_pred = model.predict(X_val)\n\n        oof_non_rounded[val_idx] = y_val_pred\n        y_val_pred_rounded = np.round(y_val_pred).astype(int)\n        oof_rounded[val_idx] = y_val_pred_rounded\n\n        train_kappa = quadratic_weighted_kappa(y_train, np.round(y_train_pred).astype(int))\n        val_kappa = quadratic_weighted_kappa(y_val, y_val_pred_rounded)\n        train_S.append(train_kappa)\n        test_S.append(val_kappa)\n\n        test_preds[:, fold] = model.predict(test_data)\n\n        print(f\"Fold {fold + 1} - Train QWK: {train_kappa:.4f}, Validation QWK: {val_kappa:.4f}\")\n        clear_output(wait=True)\n\n    print(f\"Mean Train QWK --> {np.mean(train_S):.4f}\")\n    print(f\"Mean Validation QWK ---> {np.mean(test_S):.4f}\")\n\n    # Optimize thresholds with Nelder-Mead method\n    KappaOptimizer = minimize(evaluate_predictions, x0=[0.5, 1.5, 2.5], args=(y_res, oof_non_rounded), method='Nelder-Mead')\n    assert KappaOptimizer.success, \"Optimization did not converge.\"\n    oof_tuned = threshold_Rounder(oof_non_rounded, KappaOptimizer.x)\n    tKappa = quadratic_weighted_kappa(y_res, oof_tuned)\n    print(f\"----> || Optimized QWK SCORE :: {Fore.CYAN}{Style.BRIGHT} {tKappa:.3f}{Style.RESET_ALL}\")\n\n    tpm = test_preds.mean(axis=1)\n    tpTuned = threshold_Rounder(tpm, KappaOptimizer.x)\n    submission = pd.DataFrame({\n        'id': sample['id'],\n        'sii': tpTuned\n    })\n\n    return submission\n","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:18:31.393678Z","iopub.execute_input":"2024-11-05T19:18:31.394345Z","iopub.status.idle":"2024-11-05T19:18:31.407167Z","shell.execute_reply.started":"2024-11-05T19:18:31.394302Z","shell.execute_reply":"2024-11-05T19:18:31.406099Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create model instances\nLight = LGBMRegressor(**lgb_best_params, verbose=-1)\n\nXGB_Model = XGBRegressor(**xgb_best_params)\n\nCatBoost_Model = CatBoostRegressor(**cb_best_params, cat_features = cat_c)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:18:37.692017Z","iopub.execute_input":"2024-11-05T19:18:37.692899Z","iopub.status.idle":"2024-11-05T19:18:37.702975Z","shell.execute_reply.started":"2024-11-05T19:18:37.692858Z","shell.execute_reply":"2024-11-05T19:18:37.701995Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Combine models using Voting Regressor\nvoting_model = VotingRegressor(estimators=[\n    ('lightgbm', Light),\n    ('xgboost', XGB_Model),\n    ('catboost', CatBoost_Model)\n], weights=[20, 10, 20])","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:18:41.930005Z","iopub.execute_input":"2024-11-05T19:18:41.930942Z","iopub.status.idle":"2024-11-05T19:18:41.936019Z","shell.execute_reply.started":"2024-11-05T19:18:41.930891Z","shell.execute_reply":"2024-11-05T19:18:41.935080Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Train the ensemble model\nSubmission = TrainML(voting_model, test)","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:18:45.063300Z","iopub.execute_input":"2024-11-05T19:18:45.064200Z","iopub.status.idle":"2024-11-05T19:19:36.553256Z","shell.execute_reply.started":"2024-11-05T19:18:45.064157Z","shell.execute_reply":"2024-11-05T19:19:36.552289Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Save submission\nSubmission.to_csv('submission.csv', index=False)\nprint(Submission['sii'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2024-11-05T19:19:57.941347Z","iopub.execute_input":"2024-11-05T19:19:57.942133Z","iopub.status.idle":"2024-11-05T19:19:57.958361Z","shell.execute_reply.started":"2024-11-05T19:19:57.942088Z","shell.execute_reply":"2024-11-05T19:19:57.957449Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null}]}