{"metadata":{"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30683,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"name":"python3","display_name":"Python 3","language":"python"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"papermill":{"default_parameters":{},"duration":2159.116896,"end_time":"2024-04-07T10:19:38.712675","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-04-07T09:43:39.595779","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\nimport os\nimport gc\nfrom glob import glob\nfrom tqdm import tqdm_notebook\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nimport datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\nimport lightgbm as lgb\n\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import KNNImputer\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","papermill":{"duration":2.185049,"end_time":"2024-04-07T09:43:44.599573","exception":false,"start_time":"2024-04-07T09:43:42.414524","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:23.571518Z","iopub.execute_input":"2024-04-22T15:01:23.572520Z","iopub.status.idle":"2024-04-22T15:01:23.580050Z","shell.execute_reply.started":"2024-04-22T15:01:23.572482Z","shell.execute_reply":"2024-04-22T15:01:23.579128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n#เปลี่ยนรูปแบบข้อมูลเฉย\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int64))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n        return df\n#เปลี่ยนรูปแบบข้อมูลวันที่\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))  #!!?\n                df = df.with_columns(pl.col(col).dt.total_days()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n#ดรอป80\n    def filter_cols(df):\n        for col in df.columns:\n            if col not in [\"target\", \"case_id\", \"WEEK_NUM\"]:\n                isnull = df[col].is_null().mean()\n                if isnull > 0.8:\n                    df = df.drop(col)\n#ดรอปข้อมูลคอลัมน์ที่ row ซ้ำหมดเลย , ต่างกันมากเกิน 200 emcoding อาจไม่มีประสิทธิภาพมั้ง หาเพิ่มด่วน      \n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) & (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df\n\n\n#รวมข้อมูล\nclass Aggregator:\n    # Please add or subtract features yourself, be aware that too many features will take up too much space.\n    def num_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\")]\n        # expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n\n        return expr_mean \n\n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\")]\n        expr_first = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n\n        return expr_first\n\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        # expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return expr_first # +expr_count\n    \n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\n        numeric_cols = []\n        string_cols = []\n\n        for col in cols:\n\n            if df[col].dtype == pl.Float64:\n                numeric_cols.append(col)\n            elif df[col].dtype == pl.String:\n                string_cols.append(col)\n\n\n        exprs = []\n\n        if numeric_cols:\n        # Use unique aliases for mean expressions\n            exprs += [pl.mean(col).alias(f\"mean_numeric{col}\") for col in numeric_cols]\n\n        if string_cols:\n        # Use unique aliases for first expressions\n            exprs += [pl.first(col).alias(f\"first_string{col}\") for col in string_cols]\n\n        return exprs\n\n\n\n    def count_expr(df):\n        cols = [col for col in df.columns if \"num_group\" in col]\n        #expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        # expr_min = [pl.min(col).alias(f\"min_{col}\") for col in cols]\n        #expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        return expr_first \n\n    def get_exprs(df):\n        exprs = Aggregator.num_expr(df) + \\\n                Aggregator.date_expr(df) + \\\n                Aggregator.str_expr(df) + \\\n                Aggregator.other_expr(df) + \\\n                Aggregator.count_expr(df)\n\n        return exprs\n","metadata":{"papermill":{"duration":0.025581,"end_time":"2024-04-07T09:43:48.930409","exception":false,"start_time":"2024-04-07T09:43:48.904828","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:26.338489Z","iopub.execute_input":"2024-04-22T15:01:26.338868Z","iopub.status.idle":"2024-04-22T15:01:26.360283Z","shell.execute_reply.started":"2024-04-22T15:01:26.338839Z","shell.execute_reply":"2024-04-22T15:01:26.359281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df  # Return the modified DataFrame\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    \n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.set_table_dtypes)\n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n        chunks.append(df)\n    \n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    return df  # Return the modified DataFrame\n   \n","metadata":{"papermill":{"duration":0.020401,"end_time":"2024-04-07T09:43:48.998353","exception":false,"start_time":"2024-04-07T09:43:48.977952","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:29.438713Z","iopub.execute_input":"2024-04-22T15:01:29.439540Z","iopub.status.idle":"2024-04-22T15:01:29.446911Z","shell.execute_reply.started":"2024-04-22T15:01:29.439510Z","shell.execute_reply":"2024-04-22T15:01:29.445826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base  # Return the modified DataFrame\n\n\n\n\ndef to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"papermill":{"duration":0.019136,"end_time":"2024-04-07T09:43:49.028168","exception":false,"start_time":"2024-04-07T09:43:49.009032","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:31.465794Z","iopub.execute_input":"2024-04-22T15:01:31.466503Z","iopub.status.idle":"2024-04-22T15:01:31.473712Z","shell.execute_reply.started":"2024-04-22T15:01:31.466474Z","shell.execute_reply":"2024-04-22T15:01:31.472808Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{"papermill":{"duration":0.025318,"end_time":"2024-04-07T09:43:49.092539","exception":false,"start_time":"2024-04-07T09:43:49.067221","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:33.275181Z","iopub.execute_input":"2024-04-22T15:01:33.276225Z","iopub.status.idle":"2024-04-22T15:01:33.289701Z","shell.execute_reply.started":"2024-04-22T15:01:33.276179Z","shell.execute_reply":"2024-04-22T15:01:33.288668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(ROOT)\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"\n\ndata_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"papermill":{"duration":0.017335,"end_time":"2024-04-07T09:43:49.120502","exception":false,"start_time":"2024-04-07T09:43:49.103167","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:01:35.328912Z","iopub.execute_input":"2024-04-22T15:01:35.329591Z","iopub.status.idle":"2024-04-22T15:03:28.214365Z","shell.execute_reply.started":"2024-04-22T15:01:35.329563Z","shell.execute_reply":"2024-04-22T15:03:28.213328Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)\ndel data_store\ndf_train = df_train.pipe(Pipeline.filter_cols)\ngc.collect()","metadata":{"papermill":{"duration":22.182494,"end_time":"2024-04-07T09:46:28.617717","exception":false,"start_time":"2024-04-07T09:46:06.435223","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:03:31.339910Z","iopub.execute_input":"2024-04-22T15:03:31.340707Z","iopub.status.idle":"2024-04-22T15:03:44.012345Z","shell.execute_reply.started":"2024-04-22T15:03:31.340675Z","shell.execute_reply":"2024-04-22T15:03:44.011489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:03:46.690565Z","iopub.execute_input":"2024-04-22T15:03:46.690912Z","iopub.status.idle":"2024-04-22T15:03:46.717690Z","shell.execute_reply.started":"2024-04-22T15:03:46.690885Z","shell.execute_reply":"2024-04-22T15:03:46.716739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Convert Polars DataFrame to pandas DataFrame\ndf_train_pandas = df_train.to_pandas()\n\n# Now df_train_pandas is a pandas DataFrame\nprint(\"Type of df_train_pandas:\", type(df_train_pandas))\n\n","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:03:54.943933Z","iopub.execute_input":"2024-04-22T15:03:54.944583Z","iopub.status.idle":"2024-04-22T15:03:59.809594Z","shell.execute_reply.started":"2024-04-22T15:03:54.944541Z","shell.execute_reply":"2024-04-22T15:03:59.808590Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train_pandas","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:03.277297Z","iopub.execute_input":"2024-04-22T15:04:03.277645Z","iopub.status.idle":"2024-04-22T15:04:03.944695Z","shell.execute_reply.started":"2024-04-22T15:04:03.277616Z","shell.execute_reply":"2024-04-22T15:04:03.943831Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the columns to drop\ncolumns_to_drop = [col for col in df_train_pandas.columns if col.startswith('first_num_group')]\n\n# Drop the columns\ndf_train_pandas = df_train_pandas.drop(columns_to_drop, axis=1)\n\ndf_train_pandas","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:08.359170Z","iopub.execute_input":"2024-04-22T15:04:08.359972Z","iopub.status.idle":"2024-04-22T15:04:10.937713Z","shell.execute_reply.started":"2024-04-22T15:04:08.359941Z","shell.execute_reply":"2024-04-22T15:04:10.936802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\ndef fill_nan_values(df):\n    # Iterate through each column in the DataFrame\n    for column in df.columns:\n        # Get the data type of the column\n        column_dtype = df[column].dtype\n        \n        if column_dtype == 'float64' or column_dtype == 'int64':\n            # If the column is of float or integer data type, fill NaN with the mean\n            mean_value = df[column].mean()\n            df[column].fillna(mean_value, inplace=True)\n        elif column_dtype == 'category' or column_dtype == 'object' or column_dtype == 'bool':\n            # If the column is of categorical, object (string), or boolean data type, fill NaN with the mode\n            mode_value = df[column].mode()\n            if not mode_value.empty:\n                df[column].fillna(mode_value.iloc[0], inplace=True)\n                \n    return df\n\n# Sample usage:\n# df = pd.read_csv('your_data.csv')\n# filled_df = fill_nan_values(df)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:14.518249Z","iopub.execute_input":"2024-04-22T15:04:14.518867Z","iopub.status.idle":"2024-04-22T15:04:14.525749Z","shell.execute_reply.started":"2024-04-22T15:04:14.518836Z","shell.execute_reply":"2024-04-22T15:04:14.524829Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_train = fill_nan_values(df_train_pandas)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:16.897206Z","iopub.execute_input":"2024-04-22T15:04:16.898049Z","iopub.status.idle":"2024-04-22T15:04:37.728376Z","shell.execute_reply.started":"2024-04-22T15:04:16.898019Z","shell.execute_reply":"2024-04-22T15:04:37.727332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:42.703109Z","iopub.execute_input":"2024-04-22T15:04:42.704035Z","iopub.status.idle":"2024-04-22T15:04:43.329081Z","shell.execute_reply.started":"2024-04-22T15:04:42.704004Z","shell.execute_reply":"2024-04-22T15:04:43.328086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\ndef label_encode_categorical(df):\n    # Initialize a LabelEncoder object\n    label_encoder = LabelEncoder()\n    \n    # Iterate through each column in the DataFrame\n    for column in df.columns:\n        # Get the data type of the column\n        column_dtype = df[column].dtype\n        \n        if column_dtype == 'category' or column_dtype == 'object' or column_dtype == 'bool':\n            # If the column is of categorical, object (string), or boolean data type, perform label encoding\n            df[column] = label_encoder.fit_transform(df[column])\n                \n    return df\n\n# Sample usage:\n# df = pd.read_csv('your_data.csv')\n# encoded_df = label_encode_categorical(df)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:49.010246Z","iopub.execute_input":"2024-04-22T15:04:49.010599Z","iopub.status.idle":"2024-04-22T15:04:49.016694Z","shell.execute_reply.started":"2024-04-22T15:04:49.010569Z","shell.execute_reply":"2024-04-22T15:04:49.015713Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new_train = label_encode_categorical(new_train)\nnew_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:04:52.655908Z","iopub.execute_input":"2024-04-22T15:04:52.656722Z","iopub.status.idle":"2024-04-22T15:05:13.350190Z","shell.execute_reply.started":"2024-04-22T15:04:52.656690Z","shell.execute_reply":"2024-04-22T15:05:13.349270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.set_option('display.max_columns', None)\nnew_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:05:15.822889Z","iopub.execute_input":"2024-04-22T15:05:15.823214Z","iopub.status.idle":"2024-04-22T15:05:16.106590Z","shell.execute_reply.started":"2024-04-22T15:05:15.823190Z","shell.execute_reply":"2024-04-22T15:05:16.105734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = reduce_mem_usage(new_train)","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:05:18.988383Z","iopub.execute_input":"2024-04-22T15:05:18.988746Z","iopub.status.idle":"2024-04-22T15:05:22.591527Z","shell.execute_reply.started":"2024-04-22T15:05:18.988717Z","shell.execute_reply":"2024-04-22T15:05:22.590563Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\n\n# Assuming df_train is a pandas DataFrame\ndf_train.to_csv('/kaggle/working/train_base_newver.csv', index=False)\n","metadata":{"execution":{"iopub.status.busy":"2024-04-22T14:49:43.876955Z","iopub.execute_input":"2024-04-22T14:49:43.878098Z","iopub.status.idle":"2024-04-22T14:55:05.861705Z","shell.execute_reply.started":"2024-04-22T14:49:43.878056Z","shell.execute_reply":"2024-04-22T14:55:05.859222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:05:26.500303Z","iopub.execute_input":"2024-04-22T15:05:26.500664Z","iopub.status.idle":"2024-04-22T15:05:26.822902Z","shell.execute_reply.started":"2024-04-22T15:05:26.500635Z","shell.execute_reply":"2024-04-22T15:05:26.821959Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n# df_train, y = SMOTE().fit_resample(df_train, y)","metadata":{"execution":{"iopub.status.busy":"2024-04-22T15:05:29.677603Z","iopub.execute_input":"2024-04-22T15:05:29.678282Z","iopub.status.idle":"2024-04-22T15:05:31.371467Z","shell.execute_reply.started":"2024-04-22T15:05:29.678249Z","shell.execute_reply":"2024-04-22T15:05:31.370456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2024-04-22T14:56:27.823775Z","iopub.execute_input":"2024-04-22T14:56:27.825675Z","iopub.status.idle":"2024-04-22T14:56:28.237891Z","shell.execute_reply.started":"2024-04-22T14:56:27.825619Z","shell.execute_reply":"2024-04-22T14:56:28.236032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_split = 5\ncv = StratifiedGroupKFold(n_splits=n_split, shuffle=False)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 10,  \n    \"learning_rate\": 0.05,\n    \"n_estimators\": 2000,  \n    \"colsample_bytree\": 0.8,\n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"random_state\": 42,\n    \"reg_alpha\": 0.1,\n    \"reg_lambda\": 10,\n    \"extra_trees\":True,\n    'num_leaves':64,\n    \"sample_weight\":'balanced',\n    \"device\": \"gpu\", \n    \"verbose\": -1,\n}\n\nfitted_models = []\ncv_scores = []\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#   Because it takes a long time to divide the data set, \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# each time the data set is divided, two models are trained to each other twice, which saves time.\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.log_evaluation(200), lgb.early_stopping(100)] )\n    fitted_models.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"AVG CV AUC score: \", np.mean(cv_scores))\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"papermill":{"duration":1790.756016,"end_time":"2024-04-07T10:19:29.367755","exception":false,"start_time":"2024-04-07T09:49:38.611739","status":"completed"},"scrolled":true,"tags":[],"execution":{"iopub.status.busy":"2024-04-22T15:53:25.580101Z","iopub.execute_input":"2024-04-22T15:53:25.580491Z","iopub.status.idle":"2024-04-22T16:22:38.590658Z","shell.execute_reply.started":"2024-04-22T15:53:25.580461Z","shell.execute_reply":"2024-04-22T16:22:38.589685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_idx = np.argmax(cv_scores)\nbest_idx","metadata":{"execution":{"iopub.status.busy":"2024-04-22T16:22:49.733148Z","iopub.execute_input":"2024-04-22T16:22:49.733521Z","iopub.status.idle":"2024-04-22T16:22:49.740063Z","shell.execute_reply.started":"2024-04-22T16:22:49.733492Z","shell.execute_reply":"2024-04-22T16:22:49.739055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb.plot_importance(fitted_models[best_idx], importance_type=\"split\", figsize=(10, 50))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-22T16:22:52.194324Z","iopub.execute_input":"2024-04-22T16:22:52.194699Z","iopub.status.idle":"2024-04-22T16:22:56.190048Z","shell.execute_reply.started":"2024-04-22T16:22:52.194671Z","shell.execute_reply":"2024-04-22T16:22:56.188601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import joblib\n\njoblib.dump(fitted_models, 'lgb_models.joblib')\n\nnotebook_info = {\n    'description': 'Add notebook info dict to store cols and cat_cols',\n    'cols': df_train.columns.to_list(),\n}\njoblib.dump(notebook_info, 'notebook_info.joblib')","metadata":{"execution":{"iopub.status.busy":"2024-04-22T16:23:34.469547Z","iopub.execute_input":"2024-04-22T16:23:34.470178Z","iopub.status.idle":"2024-04-22T16:23:35.861985Z","shell.execute_reply.started":"2024-04-22T16:23:34.470147Z","shell.execute_reply":"2024-04-22T16:23:35.861014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!ls -al","metadata":{"execution":{"iopub.status.busy":"2024-04-22T16:23:42.400039Z","iopub.execute_input":"2024-04-22T16:23:42.400921Z","iopub.status.idle":"2024-04-22T16:23:43.620292Z","shell.execute_reply.started":"2024-04-22T16:23:42.400888Z","shell.execute_reply":"2024-04-22T16:23:43.619207Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"CV AUC scores: \", cv_scores)\nprint(\"AVG CV AUC score: \", np.mean(cv_scores))\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-04-22T16:23:45.271950Z","iopub.execute_input":"2024-04-22T16:23:45.272324Z","iopub.status.idle":"2024-04-22T16:23:45.278687Z","shell.execute_reply.started":"2024-04-22T16:23:45.272294Z","shell.execute_reply":"2024-04-22T16:23:45.277653Z"},"trusted":true},"execution_count":null,"outputs":[]}]}