{"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"}],"dockerImageVersionId":30787,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport pyarrow.parquet as pq\nimport matplotlib.pyplot as plt\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.decomposition import PCA\nfrom sklearn.cluster import KMeans\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom sklearn.metrics import accuracy_score, classification_report\n\n# Load data\ntrain_data = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/test.csv')\ntest_data = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/test.csv')\n\n\n# Check the first few rows\nprint(train_data.head())\nprint(test_data.head())","metadata":{"execution":{"iopub.status.busy":"2024-12-11T17:49:09.449172Z","iopub.execute_input":"2024-12-11T17:49:09.450129Z","iopub.status.idle":"2024-12-11T17:49:12.878051Z","shell.execute_reply.started":"2024-12-11T17:49:09.450071Z","shell.execute_reply":"2024-12-11T17:49:12.876872Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Check for missing values\nmissing_values_train = train_data.isnull().sum() / len(train_data)\n\n\n# print(missing_values_train)\nprint(missing_values_train)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:49:12.880381Z","iopub.execute_input":"2024-12-11T17:49:12.881373Z","iopub.status.idle":"2024-12-11T17:49:12.892628Z","shell.execute_reply.started":"2024-12-11T17:49:12.881314Z","shell.execute_reply":"2024-12-11T17:49:12.891244Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Ref > [Ensemble Model](https://www.kaggle.com/code/abdullah0a/ensamble-models) ","metadata":{}},{"cell_type":"code","source":"import numpy as np\n\nimport pandas as pd\n\nimport os\n\nimport numpy as np\n\nimport pandas as pd\n\nimport os\n\nimport re\n\nfrom sklearn.base import clone\n\nfrom sklearn.metrics import cohen_kappa_score\n\nfrom sklearn.model_selection import StratifiedKFold\n\nfrom scipy.optimize import minimize\n\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom tqdm import tqdm\n\nimport polars as pl\n\nimport polars.selectors as cs\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.ticker import MaxNLocator, FormatStrFormatter, PercentFormatter\n\nimport seaborn as sns\n\n\n\nfrom sklearn.preprocessing import StandardScaler\n\nimport matplotlib.pyplot as plt\n\nfrom keras.models import Model\n\nfrom keras.layers import Input, Dense\n\nfrom keras.optimizers import Adam\n\nimport torch\n\nimport torch.nn as nn\n\nimport torch.optim as optim\n\n\n\nfrom colorama import Fore, Style\n\nfrom IPython.display import clear_output\n\nimport warnings\n\nfrom lightgbm import LGBMRegressor\n\nfrom xgboost import XGBRegressor\n\nfrom catboost import CatBoostRegressor\n\nfrom sklearn.ensemble import VotingRegressor, RandomForestRegressor, GradientBoostingRegressor\n\nfrom sklearn.impute import SimpleImputer, KNNImputer\n\nfrom sklearn.pipeline import Pipeline\n\nwarnings.filterwarnings('ignore')\n\npd.options.display.max_columns = None\n\nSEED = 42\n\nn_splits = 5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:49:12.894228Z","iopub.execute_input":"2024-12-11T17:49:12.894741Z","iopub.status.idle":"2024-12-11T17:49:33.26637Z","shell.execute_reply.started":"2024-12-11T17:49:12.894663Z","shell.execute_reply":"2024-12-11T17:49:33.265101Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/train.csv')\n\ntest = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/test.csv')\n\nsample = pd.read_csv('/kaggle/input/child-mind-institute-problematic-internet-use/sample_submission.csv')\n\n\n\ndef process_file(filename, dirname):\n\n    df = pd.read_parquet(os.path.join(dirname, filename, 'part-0.parquet'))\n\n    df.drop('step', axis=1, inplace=True)\n\n    return df.describe().values.reshape(-1), filename.split('=')[1]\n\n\n\ndef load_time_series(dirname) -> pd.DataFrame:\n\n    ids = os.listdir(dirname)\n\n    \n\n    with ThreadPoolExecutor() as executor:\n\n        results = list(tqdm(executor.map(lambda fname: process_file(fname, dirname), ids), total=len(ids)))\n\n    \n\n    stats, indexes = zip(*results)\n\n    \n\n    df = pd.DataFrame(stats, columns=[f\"stat_{i}\" for i in range(len(stats[0]))])\n\n    df['id'] = indexes\n\n    return df\n\n        \n\ntrain_ts = load_time_series(\"/kaggle/input/child-mind-institute-problematic-internet-use/series_train.parquet\")\n\ntest_ts = load_time_series(\"/kaggle/input/child-mind-institute-problematic-internet-use/series_test.parquet\")\n\n\n\ntime_series_cols = train_ts.columns.tolist()\n\ntime_series_cols.remove(\"id\")\n\n\n\ntrain = pd.merge(train, train_ts, how=\"left\", on='id')\n\ntest = pd.merge(test, test_ts, how=\"left\", on='id')\n\n\n\ntrain = train.drop('id', axis=1)\n\ntest = test.drop('id', axis=1)  ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:49:33.269239Z","iopub.execute_input":"2024-12-11T17:49:33.270197Z","iopub.status.idle":"2024-12-11T17:51:08.525144Z","shell.execute_reply.started":"2024-12-11T17:49:33.270136Z","shell.execute_reply":"2024-12-11T17:51:08.523861Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"featuresCols = ['Basic_Demos-Enroll_Season', 'Basic_Demos-Age', 'Basic_Demos-Sex',\n\n                'CGAS-Season', 'CGAS-CGAS_Score', 'Physical-Season', 'Physical-BMI',\n\n                'Physical-Height', 'Physical-Weight', 'Physical-Waist_Circumference',\n\n                'Physical-Diastolic_BP', 'Physical-HeartRate', 'Physical-Systolic_BP',\n\n                'Fitness_Endurance-Season', 'Fitness_Endurance-Max_Stage',\n\n                'Fitness_Endurance-Time_Mins', 'Fitness_Endurance-Time_Sec',\n\n                'FGC-Season', 'FGC-FGC_CU', 'FGC-FGC_CU_Zone', 'FGC-FGC_GSND',\n\n                'FGC-FGC_GSND_Zone', 'FGC-FGC_GSD', 'FGC-FGC_GSD_Zone', 'FGC-FGC_PU',\n\n                'FGC-FGC_PU_Zone', 'FGC-FGC_SRL', 'FGC-FGC_SRL_Zone', 'FGC-FGC_SRR',\n\n                'FGC-FGC_SRR_Zone', 'FGC-FGC_TL', 'FGC-FGC_TL_Zone', 'BIA-Season',\n\n                'BIA-BIA_Activity_Level_num', 'BIA-BIA_BMC', 'BIA-BIA_BMI',\n\n                'BIA-BIA_BMR', 'BIA-BIA_DEE', 'BIA-BIA_ECW', 'BIA-BIA_FFM',\n\n                'BIA-BIA_FFMI', 'BIA-BIA_FMI', 'BIA-BIA_Fat', 'BIA-BIA_Frame_num',\n\n                'BIA-BIA_ICW', 'BIA-BIA_LDM', 'BIA-BIA_LST', 'BIA-BIA_SMM',\n\n                'BIA-BIA_TBW', 'PAQ_A-Season', 'PAQ_A-PAQ_A_Total', 'PAQ_C-Season',\n\n                'PAQ_C-PAQ_C_Total', 'SDS-Season', 'SDS-SDS_Total_Raw',\n\n                'SDS-SDS_Total_T', 'PreInt_EduHx-Season',\n\n                'PreInt_EduHx-computerinternet_hoursday', 'sii']\n\nprint(len(featuresCols))\n\n\n\nfeaturesCols += time_series_cols\n\n\n\ntrain = train[featuresCols]\n\ntrain = train.dropna(subset='sii')\n\n\n\n\n\ncat_c = ['Basic_Demos-Enroll_Season', 'CGAS-Season', 'Physical-Season', \n\n          'Fitness_Endurance-Season', 'FGC-Season', 'BIA-Season', \n\n          'PAQ_A-Season', 'PAQ_C-Season', 'SDS-Season', 'PreInt_EduHx-Season']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:51:08.526635Z","iopub.execute_input":"2024-12-11T17:51:08.527051Z","iopub.status.idle":"2024-12-11T17:51:08.545541Z","shell.execute_reply.started":"2024-12-11T17:51:08.527013Z","shell.execute_reply":"2024-12-11T17:51:08.544102Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def update(df):\n\n    global cat_c\n\n    for c in cat_c: \n\n        df[c] = df[c].fillna('Missing')\n\n        df[c] = df[c].astype('category')\n\n    return df\n\n        \n\ntrain = update(train)\n\ntest = update(test)\n\n\n\ndef create_mapping(column, dataset):\n\n    unique_values = dataset[column].unique()\n\n    return {value: idx for idx, value in enumerate(unique_values)}\n\n\n\nfor col in cat_c:\n\n    mapping = create_mapping(col, train)\n\n    mappingTe = create_mapping(col, test)\n\n    \n\n    train[col] = train[col].replace(mapping).astype(int)\n\n    test[col] = test[col].replace(mappingTe).astype(int)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:51:08.547462Z","iopub.execute_input":"2024-12-11T17:51:08.547866Z","iopub.status.idle":"2024-12-11T17:51:08.644998Z","shell.execute_reply.started":"2024-12-11T17:51:08.547829Z","shell.execute_reply":"2024-12-11T17:51:08.643891Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate Acc Score\ndef quadratic_weighted_kappa(y_true, y_pred):\n\n    return cohen_kappa_score(y_true, y_pred, weights='quadratic')\n\n\n\ndef threshold_Rounder(oof_non_rounded, thresholds):\n\n    return np.where(oof_non_rounded < thresholds[0], 0,\n\n                    np.where(oof_non_rounded < thresholds[1], 1,\n\n                             np.where(oof_non_rounded < thresholds[2], 2, 3)))\n\n\n\ndef evaluate_predictions(thresholds, y_true, oof_non_rounded):\n\n    rounded_p = threshold_Rounder(oof_non_rounded, thresholds)\n\n    return -quadratic_weighted_kappa(y_true, rounded_p)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T17:51:08.646687Z","iopub.execute_input":"2024-12-11T17:51:08.64706Z","iopub.status.idle":"2024-12-11T17:51:08.654347Z","shell.execute_reply.started":"2024-12-11T17:51:08.647024Z","shell.execute_reply":"2024-12-11T17:51:08.653084Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"imputer = KNNImputer(n_neighbors= 3)\ntrain_imputed = pd.DataFrame(imputer.fit_transform(train), columns=train.columns)#print(train_imputed)\n\n#Changed the knn\n\n# numerical_cols = train.select_dtypes(include=np.number).columns\n# categorical_cols = train.select_dtypes(exclude=np.number).columns\n# imputer = KNNImputer(n_neighbors=5)\n# train_numerical_imputed = pd.DataFrame(imputer.fit_transform(train[numerical_cols]), columns=numerical_cols)\n# train_imputed = pd.concat([train_numerical_imputed, train[categorical_cols].reset_index(drop=True)], axis=1)\n\nprint(train_imputed)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T18:08:46.78535Z","iopub.execute_input":"2024-12-11T18:08:46.785758Z","iopub.status.idle":"2024-12-11T18:08:54.106319Z","shell.execute_reply.started":"2024-12-11T18:08:46.785716Z","shell.execute_reply":"2024-12-11T18:08:54.105176Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def TrainML(model_class, test_data):\n\n    X = train.drop(['sii'], axis=1)\n\n    y = train['sii']\n\n\n\n    SKF = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=SEED)\n\n    \n\n    train_S = []\n\n    test_S = []\n\n    \n\n    oof_non_rounded = np.zeros(len(y), dtype=float) \n\n    oof_rounded = np.zeros(len(y), dtype=int) \n\n    # test_preds = np.zeros((len(test_data) ,n_splits)) \n    test_preds = np.zeros((len(test_data), len(models), n_splits))\n\n\n\n    for fold, (train_idx, test_idx) in enumerate(tqdm(SKF.split(X, y), desc=\"Training Folds\", total=n_splits)):\n\n        X_train, X_val = X.iloc[train_idx], X.iloc[test_idx]\n\n        y_train, y_val = y.iloc[train_idx], y.iloc[test_idx]\n\n\n        for model_idx, model_class in enumerate(models):\n            model = clone(model_class)\n    \n            model.fit(X_train, y_train)\n    \n    \n    \n            y_train_pred = model.predict(X_train)\n    \n            y_val_pred = model.predict(X_val)\n    \n    \n    \n            oof_non_rounded[test_idx] = y_val_pred\n    \n            y_val_pred_rounded = y_val_pred.round(0).astype(int)\n    \n            oof_rounded[test_idx] = y_val_pred_rounded\n    \n    \n    \n            train_kappa = quadratic_weighted_kappa(y_train, y_train_pred.round(0).astype(int))\n    \n            val_kappa = quadratic_weighted_kappa(y_val, y_val_pred_rounded)\n    \n    \n    \n            train_S.append(train_kappa)\n    \n            test_S.append(val_kappa)\n    \n            \n    \n            # test_preds[:, fold] = model.predict(test_data)\n            # Store predictions for test data\n            test_preds[:, model_idx, fold] = model.predict(test_data)\n    \n            \n    \n            print(f\"Fold {fold+1} - Train QWK: {train_kappa:.4f}, Validation QWK: {val_kappa:.4f}\")\n        \n\n        clear_output(wait=True)\n\n    # Aggregate predictions across folds and models\n    test_preds_mean = test_preds.mean(axis=2).mean(axis=1)\n\n    print(f\"Mean Train QWK --> {np.mean(train_S):.4f}\")\n\n    print(f\"Mean Validation QWK ---> {np.mean(test_S):.4f}\")\n\n\n\n    KappaOPtimizer = minimize(evaluate_predictions,\n\n                              x0=[0.5, 1.5, 2.5], args=(y, oof_non_rounded), \n\n                              method='Nelder-Mead')\n\n    assert KappaOPtimizer.success, \"Optimization did not converge.\"\n\n    \n\n    oof_tuned = threshold_Rounder(oof_non_rounded, KappaOPtimizer.x)\n\n    tKappa = quadratic_weighted_kappa(y, oof_tuned)\n\n\n\n    print(f\"----> || Optimized QWK SCORE :: {Fore.CYAN}{Style.BRIGHT} {tKappa:.3f}{Style.RESET_ALL}\")\n\n\n\n    # tpm = test_preds.mean(axis=1)\n\n    # tpTuned = threshold_Rounder(tpm, KappaOPtimizer.x)\n\n    # Tune test predictions using optimized thresholds\n    tpTuned = threshold_Rounder(test_preds_mean, KappaOPtimizer.x)\n\n    \n\n    submission = pd.DataFrame({\n\n        'id': sample['id'],\n\n        'sii': tpTuned\n\n    })\n\n\n\n    return submission\n\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T18:31:12.490703Z","iopub.execute_input":"2024-12-11T18:31:12.49121Z","iopub.status.idle":"2024-12-11T18:31:12.505411Z","shell.execute_reply.started":"2024-12-11T18:31:12.491171Z","shell.execute_reply":"2024-12-11T18:31:12.504071Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# XGBoost parameters\n\nXGB_Params = {\n\n    'learning_rate': 0.05,\n\n    'max_depth': 6,\n\n    'n_estimators': 200,\n\n    'subsample': 0.8,\n\n    'colsample_bytree': 0.8,\n\n    'reg_alpha': 2,  # Increased from 0.1\n\n    'reg_lambda': 10,  # Increased from 1\n\n    'random_state': SEED\n\n}\n\n#Added this\n\nLightGBM_Params = {'learning_rate': 0.05, 'max_depth': 6, 'num_leaves': 500, 'n_estimators': 200, \n                   'subsample': 0.8, 'colsample_bytree': 0.8, 'reg_alpha': 1, \n                   'reg_lambda': 5, 'force_row_wise': True, 'random_state': SEED}\nCatBoost_Params = {'learning_rate': 0.05, 'depth': 6, 'iterations': 200, \n                   'random_seed': SEED, 'silent': True}\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T18:31:20.307075Z","iopub.execute_input":"2024-12-11T18:31:20.307479Z","iopub.status.idle":"2024-12-11T18:31:20.31423Z","shell.execute_reply.started":"2024-12-11T18:31:20.307443Z","shell.execute_reply":"2024-12-11T18:31:20.312955Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Create model instances, added new ensemble\n\nXGB_Model = XGBRegressor(**XGB_Params)\nLightGBM_Model = LGBMRegressor(**LightGBM_Params)\nCatBoost_Model = CatBoostRegressor(**CatBoost_Params)\n\n# Train the ensemble model\n\n# submission = TrainML(XGB_Model, test)\n\nmodels = [XGB_Model, LightGBM_Model, CatBoost_Model]\nsubmission = TrainML(models, test)\n\nprint(submission['sii'].value_counts())\n\nsubmission.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-11T18:31:22.657994Z","iopub.execute_input":"2024-12-11T18:31:22.65839Z","iopub.status.idle":"2024-12-11T18:32:12.513459Z","shell.execute_reply.started":"2024-12-11T18:31:22.658354Z","shell.execute_reply":"2024-12-11T18:32:12.512249Z"}},"outputs":[],"execution_count":null}]}