{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":81933,"databundleVersionId":9643020,"sourceType":"competition"},{"sourceId":9682055,"sourceType":"datasetVersion","datasetId":5918194}],"dockerImageVersionId":30787,"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-26T16:32:18.208569Z","iopub.execute_input":"2024-11-26T16:32:18.209452Z","iopub.status.idle":"2024-11-26T16:32:35.436762Z","shell.execute_reply.started":"2024-11-26T16:32:18.209403Z","shell.execute_reply":"2024-11-26T16:32:35.435857Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nimport polars as pl\nfrom os.path import join\nimport os\nfrom tqdm import tqdm\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import LabelEncoder, StandardScaler\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.model_selection import train_test_split, StratifiedKFold, KFold\nfrom sklearn.base import clone\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\nfrom sklearn.neighbors import KNeighborsRegressor\n\nfrom seglearn.feature_functions import base_features, emg_features\nfrom tsflex.features import FeatureCollection, MultipleFeatureDescriptors\nfrom tsflex.features.integrations import seglearn_feature_dict_wrapper\n\nfrom lightgbm import LGBMRegressor\nfrom xgboost import XGBRegressor\nfrom catboost import CatBoostRegressor\nfrom sklearn.metrics import cohen_kappa_score\nfrom sklearn.metrics import make_scorer, cohen_kappa_score\nfrom sklearn.ensemble import VotingRegressor\nfrom sklearn.impute import SimpleImputer\nfrom IPython.display import clear_output\nfrom scipy.optimize import minimize\nfrom colorama import Fore, Style\n\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-11-26T16:32:35.438592Z","iopub.execute_input":"2024-11-26T16:32:35.438896Z","iopub.status.idle":"2024-11-26T16:32:39.335894Z","shell.execute_reply.started":"2024-11-26T16:32:35.438866Z","shell.execute_reply":"2024-11-26T16:32:39.335198Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"base_dir = \"/kaggle/input/child-mind-institute-problematic-internet-use\"\ntrain_dir = join(base_dir, \"train.csv\")\ntest_dir = join(base_dir, \"test.csv\")\nsample_dir = join(base_dir, \"sample_submission.csv\")\n\ntrain_parquet = join(base_dir, \"series_train.parquet/\")\ntest_parquet = join(base_dir, \"series_test.parquet/\")","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:32:39.336830Z","iopub.execute_input":"2024-11-26T16:32:39.337242Z","iopub.status.idle":"2024-11-26T16:32:39.341487Z","shell.execute_reply.started":"2024-11-26T16:32:39.337216Z","shell.execute_reply":"2024-11-26T16:32:39.340767Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:32:39.343362Z","iopub.execute_input":"2024-11-26T16:32:39.343609Z","iopub.status.idle":"2024-11-26T16:32:39.353357Z","shell.execute_reply.started":"2024-11-26T16:32:39.343585Z","shell.execute_reply":"2024-11-26T16:32:39.352677Z"},"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-26T16:32:39.354246Z","iopub.execute_input":"2024-11-26T16:32:39.354472Z","iopub.status.idle":"2024-11-26T16:32:39.365627Z","shell.execute_reply.started":"2024-11-26T16:32:39.354449Z","shell.execute_reply":"2024-11-26T16:32:39.365008Z"},"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-26T16:32:39.366693Z","iopub.execute_input":"2024-11-26T16:32:39.367021Z","iopub.status.idle":"2024-11-26T16:32:39.373198Z","shell.execute_reply.started":"2024-11-26T16:32:39.366987Z","shell.execute_reply":"2024-11-26T16:32:39.372404Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_time_series_store = load_time_series(train_parquet)\ntrain_time_series_store = pd.DataFrame(train_time_series_store).T\ntrain_time_series_store.columns = [f'f{i}' for i in range(train_time_series_store.shape[1])]\ntrain_time_series_store = train_time_series_store.reset_index()\ntrain_time_series_store.rename(columns={'index': 'id'}, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:32:39.374167Z","iopub.execute_input":"2024-11-26T16:32:39.374476Z","iopub.status.idle":"2024-11-26T16:43:08.493148Z","shell.execute_reply.started":"2024-11-26T16:32:39.374439Z","shell.execute_reply":"2024-11-26T16:43:08.492266Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_time_series_store = load_time_series(test_parquet)\ntest_time_series_store = pd.DataFrame(test_time_series_store).T\ntest_time_series_store.columns = [f'f{i}' for i in range(test_time_series_store.shape[1])]\ntest_time_series_store = test_time_series_store.reset_index()\ntest_time_series_store.rename(columns={'index': 'id'}, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:43:08.495021Z","iopub.execute_input":"2024-11-26T16:43:08.495296Z","iopub.status.idle":"2024-11-26T16:43:09.277254Z","shell.execute_reply.started":"2024-11-26T16:43:08.495268Z","shell.execute_reply":"2024-11-26T16:43:09.276236Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv(train_dir)\ntest = pd.read_csv(test_dir)\nsample = pd.read_csv(sample_dir)","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:43:47.183116Z","iopub.execute_input":"2024-11-26T16:43:47.183479Z","iopub.status.idle":"2024-11-26T16:43:47.254472Z","shell.execute_reply.started":"2024-11-26T16:43:47.183445Z","shell.execute_reply":"2024-11-26T16:43:47.253525Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sii_count = train['sii'].isna().replace({True: 'NaN', False: 'Number'})\nsii_count.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:44:01.699413Z","iopub.execute_input":"2024-11-26T16:44:01.700497Z","iopub.status.idle":"2024-11-26T16:44:01.715182Z","shell.execute_reply.started":"2024-11-26T16:44:01.700459Z","shell.execute_reply":"2024-11-26T16:44:01.714235Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"missing_percent = train.isnull().mean() * 100 \nmissing_percent = missing_percent.to_frame().reset_index() \nmissing_percent.columns = ['columns_name', 'missing_percentage'] \nmissing_percent = missing_percent[missing_percent['missing_percentage'] > 50] \nmissing_percent","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:44:04.476005Z","iopub.execute_input":"2024-11-26T16:44:04.476317Z","iopub.status.idle":"2024-11-26T16:44:04.496938Z","shell.execute_reply.started":"2024-11-26T16:44:04.476291Z","shell.execute_reply":"2024-11-26T16:44:04.495943Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = train.dropna(subset=['sii'])\n\nfeatures_cols = list(set(train.columns).intersection(set(test.columns)))  \n\ntest = test[features_cols]\ntrain = train[features_cols + ['sii']]\n\nnumeric_columns = train.select_dtypes(include = ['float64', 'int64']).columns\ncategorical_columns = train.select_dtypes(include=['category', 'object']).columns","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:44:07.711272Z","iopub.execute_input":"2024-11-26T16:44:07.712050Z","iopub.status.idle":"2024-11-26T16:44:07.723912Z","shell.execute_reply.started":"2024-11-26T16:44:07.712015Z","shell.execute_reply":"2024-11-26T16:44:07.723176Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class PreprocessingHelper(BaseEstimator, TransformerMixin):   \n    def __init__(self): \n        self.attribute_deleted = []                \n        self.base_num_algoritm_predict = {}\n        self.base_cat_algoritm_predict = {}\n        self.mapping_cat_storage = {}\n        self.label_encoder = LabelEncoder()     \n        \n    def base_num_algoritm(self, y) -> float:\n        return np.mean(y, axis = 0)\n\n    def base_cat_algoritm(self, y) -> str:\n        return y.mode()[0]     \n    \n    def fit(self, X, y=None):\n        X_num, X_cat, X_df = X   \n        new_cat_columns = []\n        missing_percent = X_df.isnull().mean() * 100 \n        missing_percent = missing_percent.to_frame().reset_index() \n        missing_percent.columns = ['columns_name', 'missing_percentage'] \n        missing_percent = missing_percent[missing_percent['missing_percentage'] > 50] \n        self.attribute_deleted  = list(missing_percent.columns_name)\n       \n        for columns in X_num:\n            if columns not in self.attribute_deleted:\n                feature_with_isna = X_num[columns].dropna()  \n                base_pred = self.base_num_algoritm(feature_with_isna) \n                self.base_num_algoritm_predict[columns] = base_pred\n                \n                if len(set(feature_with_isna)) <= 7:\n                    new_cat_columns.append(columns)\n\n        # с учетом колонок которые переходят в категориальные переменные\n        for columns in X_cat.columns.to_list() + new_cat_columns:\n            if columns not in self.attribute_deleted:\n                feature_with_isna = X_df[columns].dropna()  \n                base_pred = self.base_cat_algoritm(feature_with_isna)\n                self.base_cat_algoritm_predict[columns] = base_pred\n                feature_with_isna = self.label_encoder.fit_transform(feature_with_isna)\n                classes = self.label_encoder.classes_\n                encoded_values = self.label_encoder.transform(classes)\n                mapping_cat =  dict(zip(classes, encoded_values))\n                self.mapping_cat_storage[columns] = mapping_cat\n                      \n        return self\n    \n    def transform(self, X, training = True) -> pd.DataFrame:\n        \n        X_num, X_cat, X_df = X \n        if training:\n            X_num = X_num.columns.to_list()\n            X_cat = X_cat.columns.to_list()\n            \n        upd_attribute_deleted = [col for col in self.attribute_deleted if col in X_df.columns]\n        X_df = X_df.drop(upd_attribute_deleted, axis=1)\n        \n        X_new_cat_columns = []\n        \n        x_columns_isna = X_df.columns[X_df.isna().any()].tolist()      \n        \n        for columns in X_num:\n\n            if columns in x_columns_isna:\n                unic_column_meanings = X_df[columns].dropna()\n\n                if len(set(unic_column_meanings)) <= 7:\n                    \n                    # TODO попробуй подобную систему добавить в ПОЛНЫЙ вариант (добавление найденных категориальных столбцов)\n                    if training:\n                        X_new_cat_columns.append(columns)\n                        X_num.remove(columns)\n                    \n                    for ind, _ in X_df.iterrows():\n                        if pd.isna(X_df.loc[ind, columns]):\n                            X_df.loc[ind, columns] = self.base_cat_algoritm(unic_column_meanings)\n                else:\n                    for ind, _ in X_df.iterrows():\n                        if pd.isna(X_df.loc[ind, columns]):\n                            X_df.loc[ind, columns] = self.base_num_algoritm_predict[columns]\n\n        for columns in X_cat:\n            if columns in x_columns_isna:\n                for ind, _ in X_df.iterrows():\n                    if pd.isna(X_df.loc[ind, columns]):\n                        X_df.loc[ind, columns] = self.base_cat_algoritm_predict[columns]\n\n        if training:\n            X_cat = [c for c in X_df.columns if c in X_cat and c not in ['id', 'sii']]\n            X_cat+=X_new_cat_columns\n\n        for columns in X_cat:\n            X_df[columns] = X_df[columns].replace(\n                self.mapping_cat_storage[columns])\n        \n        return X_df, X_num, X_cat","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:44:50.525952Z","iopub.execute_input":"2024-11-26T16:44:50.526634Z","iopub.status.idle":"2024-11-26T16:44:50.540413Z","shell.execute_reply.started":"2024-11-26T16:44:50.526599Z","shell.execute_reply":"2024-11-26T16:44:50.539534Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class DataFrameSelector(BaseEstimator, TransformerMixin):\n    \n    def __init__(self, numeric_columns: pd.Series, categorical_columns: pd.Series):\n        self.numeric_columns = numeric_columns\n        self.categorical_columns = categorical_columns\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def transform(self, X: pd.DataFrame) -> tuple:\n        self.numeric_columns = [i for i in self.numeric_columns if i in X.columns]\n        self.categorical_columns = [i for i in self.categorical_columns if i in X.columns]\n        return X[self.numeric_columns], X[self.categorical_columns], X","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:45:06.871093Z","iopub.execute_input":"2024-11-26T16:45:06.871760Z","iopub.status.idle":"2024-11-26T16:45:06.877252Z","shell.execute_reply.started":"2024-11-26T16:45:06.871704Z","shell.execute_reply":"2024-11-26T16:45:06.876385Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"metadata_pipeline = Pipeline(steps=[\n    ('selector', DataFrameSelector(numeric_columns, categorical_columns)),\n    ('Preprocessing', PreprocessingHelper())\n    ])","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:45:29.051240Z","iopub.execute_input":"2024-11-26T16:45:29.051612Z","iopub.status.idle":"2024-11-26T16:45:29.055708Z","shell.execute_reply.started":"2024-11-26T16:45:29.051579Z","shell.execute_reply":"2024-11-26T16:45:29.054817Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train, numeric_columns, categorical_columns = metadata_pipeline.fit_transform(train)\ntrain, numeric_columns, categorical_columns = metadata_pipeline.named_steps['Preprocessing'].transform(\n    (numeric_columns, categorical_columns, train), training = False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-26T16:45:39.513198Z","iopub.execute_input":"2024-11-26T16:45:39.513526Z","iopub.status.idle":"2024-11-26T16:45:53.166208Z","shell.execute_reply.started":"2024-11-26T16:45:39.513496Z","shell.execute_reply":"2024-11-26T16:45:53.165269Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test, _, _ = metadata_pipeline.named_steps['Preprocessing'].transform(\n    (numeric_columns, categorical_columns, test), training = False)","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:46:10.704607Z","iopub.execute_input":"2024-11-26T16:46:10.705444Z","iopub.status.idle":"2024-11-26T16:46:10.878580Z","shell.execute_reply.started":"2024-11-26T16:46:10.705405Z","shell.execute_reply":"2024-11-26T16:46:10.877895Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Merge datasets","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:46:40.966293Z","iopub.execute_input":"2024-11-26T16:46:40.967242Z","iopub.status.idle":"2024-11-26T16:46:40.971291Z","shell.execute_reply.started":"2024-11-26T16:46:40.967191Z","shell.execute_reply":"2024-11-26T16:46:40.970364Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"time_series_cols = train_time_series_store.columns.tolist()\ntime_series_cols.remove(\"id\")\n\ntrain = pd.merge(train, train_time_series_store, how=\"left\", on='id')\ntest = pd.merge(test, test_time_series_store, how=\"left\", on='id')\n\ntrain = train.drop('id', axis=1)\ntest = test.drop('id', axis=1)\n\ntrain[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-26T16:47:18.655588Z","iopub.execute_input":"2024-11-26T16:47:18.655954Z","iopub.status.idle":"2024-11-26T16:47:18.706831Z","shell.execute_reply.started":"2024-11-26T16:47:18.655922Z","shell.execute_reply":"2024-11-26T16:47:18.706181Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Scaling","metadata":{"execution":{"iopub.status.busy":"2024-11-24T19:04:14.591462Z","iopub.execute_input":"2024-11-24T19:04:14.591807Z","iopub.status.idle":"2024-11-24T19:04:14.614296Z","shell.execute_reply.started":"2024-11-24T19:04:14.591777Z","shell.execute_reply":"2024-11-24T19:04:14.613312Z"},"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])\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":{"execution":{"iopub.status.busy":"2024-11-26T16:49:10.901911Z","iopub.execute_input":"2024-11-26T16:49:10.902682Z","iopub.status.idle":"2024-11-26T16:49:11.166681Z","shell.execute_reply.started":"2024-11-26T16:49:10.902635Z","shell.execute_reply":"2024-11-26T16:49:11.165789Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for i in categorical_columns:\n    train[i] = train[i].astype(int) \n    test[i] = test[i].astype(int) ","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:49:47.168674Z","iopub.execute_input":"2024-11-26T16:49:47.169460Z","iopub.status.idle":"2024-11-26T16:49:47.181643Z","shell.execute_reply.started":"2024-11-26T16:49:47.169427Z","shell.execute_reply":"2024-11-26T16:49:47.180787Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Models Param","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-26T16:50:07.999445Z","iopub.execute_input":"2024-11-26T16:50:07.999807Z","iopub.status.idle":"2024-11-26T16:50:08.003765Z","shell.execute_reply.started":"2024-11-26T16:50:07.999772Z","shell.execute_reply":"2024-11-26T16:50:08.002797Z"}},"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],\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-26T16:50:10.054878Z","iopub.execute_input":"2024-11-26T16:50:10.055214Z","iopub.status.idle":"2024-11-26T16:50:10.061938Z","shell.execute_reply.started":"2024-11-26T16:50:10.055187Z","shell.execute_reply":"2024-11-26T16:50:10.061070Z"},"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],\n    'n_estimators': list(range(10, 350, 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-26T16:50:12.800602Z","iopub.execute_input":"2024-11-26T16:50:12.801505Z","iopub.status.idle":"2024-11-26T16:50:12.806932Z","shell.execute_reply.started":"2024-11-26T16:50:12.801468Z","shell.execute_reply":"2024-11-26T16:50:12.805951Z"},"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-26T16:50:15.297935Z","iopub.execute_input":"2024-11-26T16:50:15.298282Z","iopub.status.idle":"2024-11-26T16:50:15.303456Z","shell.execute_reply.started":"2024-11-26T16:50:15.298250Z","shell.execute_reply":"2024-11-26T16:50:15.302526Z"}},"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-26T16:50:24.183492Z","iopub.execute_input":"2024-11-26T16:50:24.183846Z","iopub.status.idle":"2024-11-26T16:50:24.188426Z","shell.execute_reply.started":"2024-11-26T16:50:24.183815Z","shell.execute_reply":"2024-11-26T16:50:24.187464Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def search_optimal_param(X: pd.DataFrame, model, param: dict = {}, best = True):\n    \n    skfolds = StratifiedKFold(n_splits=5, 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        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        \n        if best:\n            search = model_fold\n        else:\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            print('fold: ', num_fold+1)\n            best_model_score = kappa_fold\n            if not best:\n                best_model = search.best_estimator_  \n                best_params = search.best_params_\n                print('best_params:', best_params)\n            print('kappa: ', kappa_fold)\n            \n        elif kappa_fold > best_model_score:\n            print('fold: ', num_fold+1)\n            best_model_score = kappa_fold\n            if not best:\n                best_model = search.best_estimator_  \n                best_params = search.best_params_\n                print('best_params:', best_params)\n            print('kappa: ', kappa_fold)\n\n    if best:\n        return search, best_model_score\n    \n    return best_model, best_params, best_model_score","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:50:28.505495Z","iopub.execute_input":"2024-11-26T16:50:28.505856Z","iopub.status.idle":"2024-11-26T16:50:28.514532Z","shell.execute_reply.started":"2024-11-26T16:50:28.505822Z","shell.execute_reply":"2024-11-26T16:50:28.513585Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"xgb = XGBRegressor()\n\nxgb_best_params = {'tree_method': 'hist', \n                   'subsample': 0.3500000000000001, \n                   'reg_lambda': 5.1, \n                   'reg_alpha': 1.1, \n                   'random_state': 42, \n                   'n_estimators': 230, \n                   'max_depth': 3, \n                   'learning_rate': 0.030000000000000006, \n                   'device': 'cuda', \n                   'colsample_bytree': 0.6000000000000002}\nxgb_best_model = XGBRegressor(**xgb_best_params)\nxgb_best_score = 0\n\nBOLD = '\\033[1m'\nRESET = '\\033[0m'\n\nepoch = 3\nfor i in range(epoch):\n    print(f\"{BOLD}{'epoch: '}{i+1}{RESET}\")\n    if i == 0:\n        xgb_best_model, xgb_best_score = search_optimal_param(train, xgb_best_model)\n        print('xgb_best_score from default param', xgb_best_score)\n        \n    else:\n        xgb_batch_model, xgb_batch_params, xgb_batch_score = search_optimal_param(train, xgb, xgb_params, False)\n        if xgb_batch_score > xgb_best_score:\n            \n            xgb_best_model = xgb_batch_model\n            xgb_best_params = xgb_batch_params\n            xgb_best_score = xgb_batch_score\n            \n            print(f\"{BOLD}{'new best_batch kappa: ' + str(xgb_best_score)}{RESET}\")\n            print(f\"{BOLD}{'new_best_batch_params:'}{RESET}\", xgb_best_params)","metadata":{"execution":{"iopub.status.busy":"2024-11-26T16:54:41.996835Z","iopub.execute_input":"2024-11-26T16:54:41.997748Z","iopub.status.idle":"2024-11-26T17:06:47.197722Z","shell.execute_reply.started":"2024-11-26T16:54:41.997692Z","shell.execute_reply":"2024-11-26T17:06:47.196826Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lgb = LGBMRegressor(verbose=-1)\n\nlgb_best_params = {'num_leaves': 140,\n                   'n_estimators': 90,\n                   'min_data_in_leaf': 16,\n                   'max_depth': 3,\n                   'learning_rate': 0.07272727272727272,\n                   'lambda_l2': 4.615384615384615,\n                   'lambda_l1': 3.846153846153846,\n                   'feature_fraction': 0.713,\n                   'device': 'gpu',\n                   'bagging_freq': 30,\n                   'bagging_fraction': 0.731}\nlgb_best_model = LGBMRegressor(**lgb_best_params, verbose=-1)\nlgb_best_score = 0\n\nBOLD = '\\033[1m'\nRESET = '\\033[0m'\n\nepoch = 3    \nfor i in range(epoch):\n    print(f\"{BOLD}{'epoch: '}{i+1}{RESET}\")\n    if i == 0:\n        lgb_best_model, lgb_best_score = search_optimal_param(train, lgb_best_model)\n        print('lgb_best_score from default param', lgb_best_score)\n    else:\n        lgb_batch_model, lgb_batch_params, lgb_batch_score = search_optimal_param(train, lgb, lgb_params, False)\n        if lgb_batch_score > lgb_best_score:\n            \n            lgb_best_model = lgb_batch_model\n            lgb_best_params = lgb_batch_params\n            lgb_best_score = lgb_batch_score\n            \n            print(f\"{BOLD}{'new best_batch kappa: ' + str(lgb_best_score)}{RESET}\")\n            print(f\"{BOLD}{'new_best_batch_params:'}{RESET}\", lgb_best_params)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T20:15:54.671044Z","iopub.execute_input":"2024-11-24T20:15:54.671379Z","iopub.status.idle":"2024-11-24T20:22:50.458996Z","shell.execute_reply.started":"2024-11-24T20:15:54.671353Z","shell.execute_reply":"2024-11-24T20:22:50.458215Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cat_boost = CatBoostRegressor(cat_features = categorical_columns)\n\ncb_best_params = {'verbose': 0, \n                  'task_type': 'GPU', \n                  'random_seed': 42, \n                  'learning_rate': 0.022727272727272728, \n                  'l2_leaf_reg': 10, \n                  'iterations': 240, \n                  'depth': 4}\ncb_best_model = CatBoostRegressor(**cb_best_params, cat_features = categorical_columns)\ncb_best_score = 0\n\nBOLD = '\\033[1m'\nRESET = '\\033[0m'\n\nepoch = 3     \nfor i in range(epoch):\n    print(f\"{BOLD}{'epoch: '}{i+1}{RESET}\")\n    if i == 0:\n        cb_best_model, cb_best_score = search_optimal_param(train, cb_best_model)\n        print('cb_best_score from default param', cb_best_score)\n    else:\n        cb_batch_model, cb_batch_params, cb_batch_score = search_optimal_param(train, cat_boost, cat_boost_params, False)\n        if cb_batch_score > cb_best_score:\n            \n            cb_best_model = cb_batch_model\n            cb_best_params = cb_batch_params\n            cb_best_score = cb_batch_score\n            \n            print(f\"{BOLD}{'new best_batch kappa: ' + str(cb_best_score)}{RESET}\")\n            print(f\"{BOLD}{'new_best_batch_params:'}{RESET}\", cb_best_params)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T20:37:17.600632Z","iopub.execute_input":"2024-11-24T20:37:17.601459Z","iopub.status.idle":"2024-11-24T20:51:13.280191Z","shell.execute_reply.started":"2024-11-24T20:37:17.601426Z","shell.execute_reply":"2024-11-24T20:51:13.279251Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"SEED = 42\nn_splits = 5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-26T17:10:30.969553Z","iopub.execute_input":"2024-11-26T17:10:30.969929Z","iopub.status.idle":"2024-11-26T17:10:30.974182Z","shell.execute_reply.started":"2024-11-26T17:10:30.969896Z","shell.execute_reply":"2024-11-26T17:10:30.973173Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lgb_best_params","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"xgb_best_params","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cb_best_params","metadata":{"trusted":true},"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-24T20:53:23.079077Z","iopub.execute_input":"2024-11-24T20:53:23.079409Z","iopub.status.idle":"2024-11-24T20:53:23.084587Z","shell.execute_reply.started":"2024-11-24T20:53:23.079373Z","shell.execute_reply":"2024-11-24T20:53:23.083502Z"},"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","metadata":{"execution":{"iopub.status.busy":"2024-11-24T20:53:25.838038Z","iopub.execute_input":"2024-11-24T20:53:25.838421Z","iopub.status.idle":"2024-11-24T20:53:25.848496Z","shell.execute_reply.started":"2024-11-24T20:53:25.838373Z","shell.execute_reply":"2024-11-24T20:53:25.847594Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create model instances\nLight = LGBMRegressor(**lgb_best_params, verbose=-1)  \nXGB_Model = XGBRegressor(**xgb_best_params)\nCatBoost_Model = CatBoostRegressor(**cb_best_params, cat_features = categorical_columns)\n\n# 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-24T20:54:36.888582Z","iopub.execute_input":"2024-11-24T20:54:36.888877Z","iopub.status.idle":"2024-11-24T20:54:36.894172Z","shell.execute_reply.started":"2024-11-24T20:54:36.888852Z","shell.execute_reply":"2024-11-24T20:54:36.893254Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = TrainML(voting_model, test)","metadata":{"execution":{"iopub.status.busy":"2024-11-24T20:54:47.067714Z","iopub.execute_input":"2024-11-24T20:54:47.068337Z","iopub.status.idle":"2024-11-24T20:55:02.743224Z","shell.execute_reply.started":"2024-11-24T20:54:47.068304Z","shell.execute_reply":"2024-11-24T20:55:02.742282Z"},"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-24T20:55:06.462045Z","iopub.execute_input":"2024-11-24T20:55:06.462614Z","iopub.status.idle":"2024-11-24T20:55:06.470395Z","shell.execute_reply.started":"2024-11-24T20:55:06.462578Z","shell.execute_reply":"2024-11-24T20:55:06.469633Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-11-24T20:55:09.228560Z","iopub.execute_input":"2024-11-24T20:55:09.229397Z","iopub.status.idle":"2024-11-24T20:55:09.238855Z","shell.execute_reply.started":"2024-11-24T20:55:09.229347Z","shell.execute_reply":"2024-11-24T20:55:09.237912Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{},"outputs":[],"execution_count":null}]}