{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"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"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8621043,"sourceType":"datasetVersion","datasetId":5160590}],"dockerImageVersionId":30732,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# dependencies\n\nimport sys  # System-specific parameters and functions\nimport subprocess  # Spawn new processes, connect to their input/output/error pipes, and obtain their return codes\nimport os  # Operating system dependent functionality\nimport gc  # Garbage Collector interface\nfrom pathlib import Path  # Object-oriented filesystem paths\nfrom glob import glob  # Unix style pathname pattern expansion\n\nimport numpy as np  # Fundamental package for scientific computing with Python\nimport pandas as pd  # Powerful data structures for data manipulation and analysis\nimport polars as pl  # Fast DataFrame library implemented in Rust\n\nfrom datetime import datetime  # Basic date and time types\nimport seaborn as sns  # Statistical data visualization\nimport matplotlib.pyplot as plt  # MATLAB-like plotting framework\n\nimport joblib  # Save and load Python objects\n\nimport warnings  # Warning control\nwarnings.filterwarnings('ignore')  # Ignore warnings\n\nfrom sklearn.base import BaseEstimator, ClassifierMixin  # Base classes for all estimators in scikit-learn\nfrom sklearn.metrics import roc_auc_score, accuracy_score  # ROC AUC score\nimport lightgbm as lgb  # LightGBM: Gradient boosting framework\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold  # Cross-validation strategies\nfrom imblearn.over_sampling import SMOTE  # Oversampling technique for imbalanced datasets\nfrom sklearn.preprocessing import OrdinalEncoder  # Encode categorical features as an integer array\nfrom sklearn.impute import KNNImputer  # Imputation for completing missing values using k-Nearest Neighbors\n\n\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'  # Setting the root directory pa","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-10T05:01:40.926287Z","iopub.execute_input":"2024-06-10T05:01:40.926940Z","iopub.status.idle":"2024-06-10T05:01:40.935313Z","shell.execute_reply.started":"2024-06-10T05:01:40.926908Z","shell.execute_reply":"2024-06-10T05:01:40.934286Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"related_feature_path = '/kaggle/input/related-feature-for-home-credit/related_features.csv'\nrelated_features = []\nwith open(related_feature_path,'r') as f:\n    for line in f.readlines():\n        related_features.append(line.split(\"，\")[0])\nprint(len(related_features))\n        ","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:01:40.936844Z","iopub.execute_input":"2024-06-10T05:01:40.937141Z","iopub.status.idle":"2024-06-10T05:01:40.952179Z","shell.execute_reply.started":"2024-06-10T05:01:40.937116Z","shell.execute_reply":"2024-06-10T05:01:40.951092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Help funtions\nfrom https://www.kaggle.com/code/hlfen567/explained-home-credit-pipeline, includes:\n\nPipeline class\n\nFile I/O: read_file, read_files,\n\nfeature engine : feature_eng\n\nefficinet memory: reduce_mem_usage\n\nfrom https://www.kaggle.com/code/hlfen567/custom-loss-stablerocaucloss, includes:\n\nAggregator class","metadata":{}},{"cell_type":"code","source":"class Pipeline:\n\n    @staticmethod\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.Int32))\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\n        return df\n    \n    @staticmethod\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())\n                df = df.with_columns(pl.col(col).cast(pl.Float32))\n\n        df = df.drop(\"date_decision\", \"MONTH\")\n\n        return df\n\n    @staticmethod\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\n                if isnull > 0.95:  # 0.7\n                    df = df.drop(col)\n\n        for col in df.columns:\n            if (col not in [\"target\", \"case_id\", \"WEEK_NUM\"]) and (df[col].dtype == pl.String):\n                freq = df[col].n_unique()\n\n                if (freq <= 1) or (freq > 255):  # (freq <= 1) | (freq > 200)\n                    df = df.drop(col)\n\n        return df\n    \n    @staticmethod\n    def remain_relatived_features(df):\n        drop_cols=[]\n        for col in df.columns:\n            if col in [\"target\", \"case_id\", \"date_decision\",\"MONTH\",\"WEEK_NUM\", \"num_group1\",\"num_group2\"]:\n                continue\n            if col not in related_features:\n                drop_cols.append(col)\n                \n        for col in drop_cols:\n            df = df.drop(col)\n        \n        return df","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:01:40.953785Z","iopub.execute_input":"2024-06-10T05:01:40.954079Z","iopub.status.idle":"2024-06-10T05:01:40.968918Z","shell.execute_reply.started":"2024-06-10T05:01:40.954055Z","shell.execute_reply":"2024-06-10T05:01:40.968030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n\n    @staticmethod\n    def _applicant_max_expr(df, depth, cols):\n        assert depth == 1\n        assert \"num_group1\" in df.columns\n        assert \"num_group2\" not in df.columns\n        assert \"num_group1\" not in cols\n\n        redundant_cols = [\n            'creationdate_885D',\n            'recorddate_4527225D',\n            'deductiondate_4917603D',\n            'debtoutstand_525A',\n            'debtoverdue_47A',\n            'empl_employedfrom_271D',\n            'empl_employedtotal_800L',\n            'empl_industry_691L',\n            'familystate_447L',\n            'housetype_905L',\n            'incometype_1044T',\n            'safeguarantyflag_411L',\n            'sex_738L',\n            'revolvingaccount_394A',\n            'residualamount_488A',\n            'instlamount_768A',\n            'instlamount_852A',\n            'outstandingamount_362A',\n            'totaldebtoverduevalue_178A',\n            'totaloutstanddebtvalue_39A',\n            'dateofcredstart_181D',\n            'numberofoverdueinstlmaxdat_641D',\n            'overdueamountmax2date_1142D',\n            'numberofcontrsvalue_258L',\n            'maxdpdtolerance_577P',\n            'outstandingdebt_522A',\n            'actualdpd_943P',\n            'financialinstitution_591M',\n            'contractst_545M',\n            'contractst_964M',\n        ]\n\n        return [\n            pl.col(\"num_group1\", col)\n            .filter(pl.col(\"num_group1\") == 0)\n            .exclude(\"num_group1\")\n            .max()\n            .alias(f\"applicant_max_{col}\")\n            for col in cols if col not in redundant_cols\n        ]\n\n    @staticmethod\n    def _above_expr(df, depth, cols, threshold):\n        assert depth in [1, 2]\n        assert \"num_group1\" in df.columns\n        return [\n            pl.col(col)\n            .filter(pl.col(col) > threshold)\n            .len()\n            .cast(pl.Float64)\n            .truediv(1 + pl.len())\n            .alias(f\"above_{threshold}_share_{col}\")\n            for col in cols\n        ]\n\n    @staticmethod\n    def _mode_share_expr(df, depth, cols):\n        assert depth in [1, 2]\n        assert \"num_group1\" in df.columns\n        \n        additional_param_cols = [\n            'numberofoverdueinstlmax_1151L',\n            'postype_4733339M',\n            'rejectreasonclient_4145042M',\n            'purposeofcred_874M',\n            'purposeofcred_426M',\n            'purposeofcred_722M',\n            'classificationofcontr_13M',\n            'contractst_545M',\n            'financialinstitution_591M',\n            'numberofoutstandinstls_520L',\n            'employername_M',\n            'name_4527232M',\n            'name_4917606M',\n            'employername_160M',\n            'numberofcontrsvalue_358L',\n            'contaddr_district_15M',\n            'registaddr_district_1083M',\n            'empladdr_district_926M',\n            'empladdr_zipcode_114M',\n        ]\n\n        expr = []\n\n        for col in cols:\n            if df[col].dtype == pl.String:\n                mode1 = pl.col(col).drop_nulls().mode().max()\n                # mode2 = pl.col(col).filter(pl.col(col) != mode1).mode().first()\n                expr.append(mode1.alias(f\"mode1_{col}\"))\n\n                if col in additional_param_cols:\n                    expr.append(\n                        (pl.col(col) == mode1).cast(pl.Float64).sum()\n                        .truediv(1 + pl.len())\n                        .alias(f\"mode1_additional_param_{col}\")\n                    )\n            else:\n                expr.append(\n                    pl.mean(col).alias(f\"mode1_{col}\")\n                )\n\n                if col in additional_param_cols:\n                    expr.append(\n                        pl.max(col).alias(f\"mode1_additional_param_{col}\")\n                    )\n\n        return expr\n\n    @staticmethod\n    def num_dpd_expr(df, depth):\n        assert depth in [1, 2]\n        \n        redundant_cols = [\n            'avgdbdtollast24m_4525197P',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] == \"P\") and (col not in redundant_cols)\n        ]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n\n        expr_above = Aggregator._above_expr(\n            df,\n            depth,\n            [col for col in cols if 'pmts_dpd' in col],\n            threshold=0.0\n        )\n        \n        if depth == 2:\n            return expr_mean + expr_max + expr_above\n\n        expr_applicant_max = Aggregator._applicant_max_expr(df, depth, cols)\n        return expr_mean + expr_max + expr_above + expr_applicant_max\n\n    @staticmethod\n    def num_amnt_expr(df, depth):\n        assert depth in [1, 2]\n        \n        redundant_cols = [\n            'avgpmtlast12m_4525200A',\n            'disbursedcredamount_1113A',\n            'maxpmtlast3m_4525190A',\n            'pmtamount_36A',\n            'totaloutstanddebtvalue_668A',\n            'mainoccupationinc_384A',\n            'credacc_credlmt_575A',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] == \"A\") and (col not in redundant_cols)\n        ]\n\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        expr_min = [\n            pl.min(col).alias(f\"min_{col}\") for col in cols\n            if col not in [\n                'debtoutstand_525A',\n                'debtoverdue_47A',\n                'outstandingamount_362A',\n                'residualamount_488A',\n                'totalamount_996A',\n                'credlmt_935A',\n                'residualamount_856A',\n                'instlamount_768A',\n                \n            ]\n        ]\n\n        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        expr_std = [\n            pl.std(col).alias(f\"std_{col}\")\n            for col in cols if 'amount' in col\n        ]\n\n        if depth == 2:\n            return expr_max + expr_min + expr_mean + expr_std\n\n        expr_applicant_max = Aggregator._applicant_max_expr(df, depth, cols)\n        return expr_max + expr_min + expr_mean + expr_std + expr_applicant_max\n\n    @staticmethod\n    def date_expr(df, depth):\n        assert depth in [1, 2]\n\n        redundant_cols = [\n            'responsedate_1012D',\n            'processingdate_168D',\n            'numberofoverdueinstlmaxdat_148D',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] == \"D\") and (col not in redundant_cols)\n        ]\n\n        expr_max = [\n            pl.max(col).alias(f\"max_{col}\") for col in cols\n            if col not in [\n                'recorddate_4527225D',\n                'approvaldate_319D',\n                'creationdate_885D',\n            ]\n        ]\n        expr_min = [\n            pl.min(col).alias(f\"min_{col}\") for col in cols\n            if col not in [\n                'empl_employedfrom_271D',\n                'recorddate_4527225D',\n            ]\n        ]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        if depth == 1:\n            expr_applicant_max = Aggregator._applicant_max_expr(df, depth, cols)\n            return expr_max + expr_min + expr_applicant_max + expr_last\n\n        return expr_max + expr_min + expr_last\n\n    @staticmethod\n    def str_expr(df, depth):\n        assert depth in [1, 2]\n\n        redundant_cols = [\n            'lastrejectcommodtypec_5251769M',\n            'language1_981M',\n            'subjectrole_182M',\n            'subjectrole_93M',\n            'subjectroles_name_838M',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] == \"M\") and (col not in redundant_cols)\n        ]\n\n        expr_mode_share = Aggregator._mode_share_expr(df, depth, cols)\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        if depth == 2:\n            return expr_mode_share + expr_last\n\n        expr_applicant_max = Aggregator._applicant_max_expr(df, depth, cols)\n        return expr_mode_share + expr_applicant_max + expr_last\n\n    @staticmethod\n    def other_expr(df, depth):\n        assert depth in [1, 2]\n        \n        redundant_cols = [\n            'pmts_month_158T',\n            'pmts_year_1139T',\n            'pmts_month_706T',\n            'dpdmaxdateyear_596T',\n            'overdueamountmaxdatemonth_284T',\n            'overdueamountmaxdatemonth_365T',\n            'dpdmaxdatemonth_89T',\n            'dpdmaxdatemonth_442T',\n\n            'contractssum_5085716L',\n            'applicationscnt_629L',\n            'clientscnt_1130L',\n            'clientscnt_360L',\n            'clientscnt_533L',\n            'clientscnt_887L',\n            'clientscnt_946L',\n            'numinstpaidlastcontr_4325080L',\n            'numnotactivated_1143L',\n            'contaddr_smempladdr_334L',\n            'type_25L',\n\n            # only 1 unique value\n            'personindex_1023L',\n            'persontype_1072L',\n            'persontype_792L',\n\n            # only 2 unique values\n            'contaddr_matchlist_1032L',  # [null, false]\n            'remitter_829L',             # [ 0. null]\n\n            # duplicates\n            'tenor_203L',  # ~ pmtnum_8L\n            \n            # score decrease\n            'periodicityofpmts_837L',\n            'overdueamountmaxdateyear_2T',\n            'numberofoutstandinstls_59L',\n            'annualeffectiverate_63L',\n            'pmtnum_8L',\n            'status_219L',\n        ]\n\n        cols = [\n            col for col in df.columns\n            if (col[-1] in (\"T\", \"L\")) and (col not in redundant_cols)\n        ]\n\n        expr_mode_share = Aggregator._mode_share_expr(df, depth, cols)\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n\n        if depth == 2:\n            return expr_mode_share + expr_last\n\n        expr_applicant_max = Aggregator._applicant_max_expr(df, depth, cols)\n        return expr_mode_share + expr_applicant_max + expr_last\n    \n    @staticmethod\n    def count_expr(df, depth):\n        assert depth in [1, 2]\n\n        cols = [\n            col for col in df.columns\n            if \"num_group\" in col\n        ]\n\n        if depth == 1:\n            assert \"num_group1\" in df.columns\n            assert \"num_group2\" not in df.columns\n            expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n            expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n            return expr_max + expr_last\n\n        assert \"num_group1\" in df.columns\n        assert \"num_group2\" in df.columns\n\n        return []  # expr_n_unique + expr_applicant_share\n\n    @staticmethod\n    def get_exprs(df, depth):\n        assert depth in [1, 2]\n\n        exprs = Aggregator.num_dpd_expr(df, depth) + \\\n                Aggregator.num_amnt_expr(df, depth) + \\\n                Aggregator.date_expr(df, depth) + \\\n                Aggregator.str_expr(df, depth) + \\\n                Aggregator.other_expr(df, depth) + \\\n                Aggregator.count_expr(df, depth)\n\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:01:40.970780Z","iopub.execute_input":"2024-06-10T05:01:40.971048Z","iopub.status.idle":"2024-06-10T05:01:41.014681Z","shell.execute_reply.started":"2024-06-10T05:01:40.971025Z","shell.execute_reply":"2024-06-10T05:01:41.013702Z"},"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.remain_relatived_features)\n    df = df.pipe(Pipeline.set_table_dtypes)\n\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df, depth))\n\n    return df\n\n\ndef read_files(regex_path, depth=None):\n    chunks = []\n    for path in glob(str(regex_path)):\n        df = pl.read_parquet(path)\n        df = df.pipe(Pipeline.remain_relatived_features)\n        df = df.pipe(Pipeline.set_table_dtypes)\n\n        if depth in [1, 2]:\n            df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df, depth))\n        \n        chunks.append(df)\n\n    df = pl.concat(chunks, how=\"vertical_relaxed\")\n    df = df.unique(subset=[\"case_id\"])\n    \n    return df\n\ndef feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base.with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\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\n    df_base = df_base.pipe(Pipeline.handle_dates)\n\n    return df_base\n\ndef to_pandas(df_data, cat_cols=None):\n    \"\"\"\n    Returns the converted Pandas DataFrame and the list of categorical column names.\n    \"\"\"\n    df_data = df_data.to_pandas()\n\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n\n    return df_data, cat_cols\n\n\ndef 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    \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    return df","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:01:41.016594Z","iopub.execute_input":"2024-06-10T05:01:41.016928Z","iopub.status.idle":"2024-06-10T05:01:41.036417Z","shell.execute_reply.started":"2024-06-10T05:01:41.016898Z","shell.execute_reply":"2024-06-10T05:01:41.035562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT      = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\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\"),  # external\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),  # external\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),  # external\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),  # external\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),  #external\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),  # external\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), # external \n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:01:41.037757Z","iopub.execute_input":"2024-06-10T05:01:41.038031Z","iopub.status.idle":"2024-06-10T05:05:44.377402Z","shell.execute_reply.started":"2024-06-10T05:01:41.038009Z","shell.execute_reply":"2024-06-10T05:05:44.376548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:05:44.379403Z","iopub.execute_input":"2024-06-10T05:05:44.379714Z","iopub.status.idle":"2024-06-10T05:06:04.504977Z","shell.execute_reply.started":"2024-06-10T05:05:44.379689Z","shell.execute_reply":"2024-06-10T05:06:04.504159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\nprint(gc.collect())\n\ndf_train = df_train.pipe(Pipeline.filter_cols)\nassert len(df_train.shape) == 2\nprint(\"train data shape:\\t\", df_train.shape)\n\ndf_train, cat_cols = to_pandas(df_train)\ntrain_cols = list(df_train.columns)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:04.506471Z","iopub.execute_input":"2024-06-10T05:06:04.506923Z","iopub.status.idle":"2024-06-10T05:06:39.412440Z","shell.execute_reply.started":"2024-06-10T05:06:04.506890Z","shell.execute_reply":"2024-06-10T05:06:39.411202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(cat_cols))\nprint(len(train_cols))","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:39.413865Z","iopub.execute_input":"2024-06-10T05:06:39.414283Z","iopub.status.idle":"2024-06-10T05:06:39.420643Z","shell.execute_reply.started":"2024-06-10T05:06:39.414245Z","shell.execute_reply":"2024-06-10T05:06:39.419434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Handling Missing Values and Reducing Columns Based on Correlation\n\nfrom https://www.kaggle.com/code/hlfen567/explained-home-credit-pipeline","metadata":{}},{"cell_type":"code","source":"nums=df_train.select_dtypes(exclude='category').columns\nnans_df = df_train[nums].isna()\nnans_groups={}\nfor col in nums:\n    cur_group = nans_df[col].sum()\n    try:\n        nans_groups[cur_group].append(col)\n    except:\n        nans_groups[cur_group]=[col]\ndel nans_df; x=gc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:39.421895Z","iopub.execute_input":"2024-06-10T05:06:39.422573Z","iopub.status.idle":"2024-06-10T05:06:44.779382Z","shell.execute_reply.started":"2024-06-10T05:06:39.422530Z","shell.execute_reply":"2024-06-10T05:06:44.778553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_group(grps):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df_train[gg].nunique()\n            if n>mx:\n                mx = n\n                vx = gg\n        use.append(vx)\n    return use","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:44.780694Z","iopub.execute_input":"2024-06-10T05:06:44.781048Z","iopub.status.idle":"2024-06-10T05:06:44.787616Z","shell.execute_reply.started":"2024-06-10T05:06:44.781015Z","shell.execute_reply":"2024-06-10T05:06:44.786529Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def group_columns_by_correlation(matrix, threshold=0.8):\n    correlation_matrix = matrix.corr()\n    groups = []\n    remaining_cols = list(matrix.columns)\n    while remaining_cols:\n        col = remaining_cols.pop(0)\n        group = [col]\n        correlated_cols = [col]\n        for c in remaining_cols:\n            if correlation_matrix.loc[col, c] >= threshold:\n                group.append(c)\n                correlated_cols.append(c)\n        groups.append(group)\n        remaining_cols = [c for c in remaining_cols if c not in correlated_cols]\n    \n    return groups","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:44.788876Z","iopub.execute_input":"2024-06-10T05:06:44.789212Z","iopub.status.idle":"2024-06-10T05:06:44.806384Z","shell.execute_reply.started":"2024-06-10T05:06:44.789167Z","shell.execute_reply":"2024-06-10T05:06:44.805481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"uses=[]\nfor k,v in nans_groups.items():\n    if len(v)>1:\n            Vs = nans_groups[k]\n            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n    else:\n        uses=uses+v\n\n# Subset the DataFrame to keep only the selected columns\ndf_train = df_train[uses + cat_cols]       ","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:06:44.809884Z","iopub.execute_input":"2024-06-10T05:06:44.810339Z","iopub.status.idle":"2024-06-10T05:07:11.599396Z","shell.execute_reply.started":"2024-06-10T05:06:44.810315Z","shell.execute_reply":"2024-06-10T05:07:11.598281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(df_train.shape)\nprint(df_train.memory_usage().sum() / 1024**2)\nprint(df_train.columns)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:11.600895Z","iopub.execute_input":"2024-06-10T05:07:11.601308Z","iopub.status.idle":"2024-06-10T05:07:11.630736Z","shell.execute_reply.started":"2024-06-10T05:07:11.601272Z","shell.execute_reply":"2024-06-10T05:07:11.629420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# simple EDA\nnum_neg = df_train[\"target\"].value_counts()[0]\nnum_pos = df_train[\"target\"].value_counts()[1]\nprint(f\"正样本数{num_pos}, 负样本数{num_neg}, 正样本占比{num_pos/(num_pos+num_neg):.4f} \")","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:11.632626Z","iopub.execute_input":"2024-06-10T05:07:11.632914Z","iopub.status.idle":"2024-06-10T05:07:11.662780Z","shell.execute_reply.started":"2024-06-10T05:07:11.632891Z","shell.execute_reply":"2024-06-10T05:07:11.661895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train=reduce_mem_usage(df_train)\nprint(\"memery usage after reduction:\",df_train.memory_usage().sum() / 1024**2)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:11.664053Z","iopub.execute_input":"2024-06-10T05:07:11.664387Z","iopub.status.idle":"2024-06-10T05:07:20.165733Z","shell.execute_reply.started":"2024-06-10T05:07:11.664357Z","shell.execute_reply":"2024-06-10T05:07:20.164542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# split df_train into train and val set by 9:1\n\nN_train_old = len(df_train)\n\n# shuffle\ndf_train =  df_train.sample(frac=1, random_state=42).reset_index(drop=True)\n\ndf_val = df_train.head(int(N_train_old*0.1))\ndf_train = df_train.tail(N_train_old - len(df_val))\n\nprint(f\"num of train set: {len(df_train)}, num of val set: {len(df_val)}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:20.167253Z","iopub.execute_input":"2024-06-10T05:07:20.167692Z","iopub.status.idle":"2024-06-10T05:07:26.241713Z","shell.execute_reply.started":"2024-06-10T05:07:20.167654Z","shell.execute_reply":"2024-06-10T05:07:26.240752Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# get df_test\nROOT      = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\nTRAIN_DIR = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR  = ROOT / \"parquet_files\" / \"test\"\n\ndata_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),  # external\n        read_files(TEST_DIR / \"test_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TEST_DIR / \"test_applprev_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_a_1.parquet\", 1),  # external\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),  # external\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),  # external\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),  #external\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),  # external\n        read_file(TEST_DIR / \"test_other_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_person_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_deposit_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2), # external \n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:26.243086Z","iopub.execute_input":"2024-06-10T05:07:26.243470Z","iopub.status.idle":"2024-06-10T05:07:26.527417Z","shell.execute_reply.started":"2024-06-10T05:07:26.243419Z","shell.execute_reply":"2024-06-10T05:07:26.526561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\ndel data_store\nprint(gc.collect())\n\ndf_test, _ = to_pandas(df_test, cat_cols)\ndf_test[\"target\"] = 0\ndf_test = df_test[df_train.columns]\n\nprint(df_test.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:26.528465Z","iopub.execute_input":"2024-06-10T05:07:26.528751Z","iopub.status.idle":"2024-06-10T05:07:26.845280Z","shell.execute_reply.started":"2024-06-10T05:07:26.528727Z","shell.execute_reply":"2024-06-10T05:07:26.844140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# process inconsistences between df_train, df_val, and df_test\ndef convert_cols_cat_add_Unknown(*dfs):\n    # List of columns of the tuple of dataframes that are of type \"object\" in at least\n    # one of the dataframes\n    cat_cols = dfs[0].select_dtypes(include=['category']).columns\n    # For each column of dtype \"object\"\n    for col in cat_cols:\n        # For each dataframe of the tuple\n        for df in dfs:\n            # Convert current column to dtype \"category\"\n            # New categorical dtype whose categories correspond to the ones of the\n            # current column and the category \"Unknown\", being ordered\n            new_dtype = pd.CategoricalDtype(categories=list(set(df[col].cat.categories.to_list() +\n                                            [\"Unknown\"])),\n                                            ordered=True)\n            # Assign new dtype to current column\n            df[col] = df[col].astype(new_dtype)\n            df[col].fillna('Unknown', inplace=True)\n    return dfs\n\ndef make_cat_excl_unknown(df, df_ref):\n    # For each categorical column of the reference pandas dataframe\n    for col in df_ref.select_dtypes(include=[\"category\"]).columns:\n        # List of categories in the reference pandas dataframe\n        cat_ref = df_ref[col].cat.categories.to_list()\n        # List of categories in the pandas dataframe of interest\n        cat = df[col].cat.categories.to_list()\n        # List of common categories\n        cat_common = list(set(cat).intersection(cat_ref))\n        # List of exclusive categories\n        cat_exc = list(set(cat).difference(cat_common))\n        # New categorical dtype whose categories correspond to the common ones\n        new_dtype = pd.CategoricalDtype(categories=cat_common,\n                                        ordered=True)\n        # Replace current column's entries associated with exclusive categories as\n        # \"Unknown\"\n        df[col] = df[col].replace(to_replace=cat_exc, value=\"Unknown\")\n        # Assign the new dtype to the current column\n        df[col] = df[col].astype(new_dtype)\n    return df","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:26.846914Z","iopub.execute_input":"2024-06-10T05:07:26.847365Z","iopub.status.idle":"2024-06-10T05:07:26.860299Z","shell.execute_reply.started":"2024-06-10T05:07:26.847324Z","shell.execute_reply":"2024-06-10T05:07:26.859341Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, df_val, df_test = convert_cols_cat_add_Unknown(df_train, df_val, df_test)\n\n\n# For compatibility reasons, make categories of the feature validation, test and\n# submission dataframes which do not pertain to the the training dataframe be replaced\n# by the category \"Unknown\"\ndf_val = make_cat_excl_unknown(df= df_val, df_ref= df_train)\ndf_test = make_cat_excl_unknown(df= df_test, df_ref= df_train)\n\ndisplay(pd.DataFrame(data=\n                     {\"Feature dataset\": [\"train\", \"valid\", \"test\"],\n                      \"N_rows\": [df.shape[0]for\n                                          df in (df_train, df_val, df_test)],\n                      \"N_cols\": [df.shape[1]for\n                                          df in (df_train, df_val, df_test)]\n                     }))","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:26.861681Z","iopub.execute_input":"2024-06-10T05:07:26.862416Z","iopub.status.idle":"2024-06-10T05:07:28.458040Z","shell.execute_reply.started":"2024-06-10T05:07:26.862386Z","shell.execute_reply":"2024-06-10T05:07:28.457068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-06-10T06:18:43.984909Z","iopub.execute_input":"2024-06-10T06:18:43.985825Z","iopub.status.idle":"2024-06-10T06:18:45.266810Z","shell.execute_reply.started":"2024-06-10T06:18:43.985791Z","shell.execute_reply":"2024-06-10T06:18:45.265593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# joblib.dump((df_train, df_val), \"data1.pkl\")\n# joblib.dump(model_lgb_balanced, \"model_lgb.pkl\")","metadata":{"execution":{"iopub.status.busy":"2024-06-10T06:18:05.841929Z","iopub.execute_input":"2024-06-10T06:18:05.842768Z","iopub.status.idle":"2024-06-10T06:18:08.712117Z","shell.execute_reply.started":"2024-06-10T06:18:05.842731Z","shell.execute_reply":"2024-06-10T06:18:08.711236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, ClassifierMixin):\n    def __init__(self, estimators):\n        super().__init__()\n        self.estimators = estimators\n        \n    def fit(self, X, y=None):\n        return self\n    \n    def predict(self, X):\n        y_preds = [estimator.predict(X, predictor=\"gpu_predictor\") for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X, predictor=\"gpu_predictor\") for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:28.459467Z","iopub.execute_input":"2024-06-10T05:07:28.459843Z","iopub.status.idle":"2024-06-10T05:07:28.467182Z","shell.execute_reply.started":"2024-06-10T05:07:28.459812Z","shell.execute_reply":"2024-06-10T05:07:28.466262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\n\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\nparams = {\n    \"boosting_type\": \"gbdt\",\n    \"objective\": \"binary\",\n    \"metric\": \"auc\",\n    \"max_depth\": 5,\n    \"learning_rate\": 0.05,\n    \"n_estimators\": 500,\n#     \"n_estimators\": 10,\n    \"num_leaves\":64,\n    \"feature_fraction\": 0.9,\n    \"bagging_fraction\": 0.8,\n    \"bagging_freq\": 5,\n    \"colsample_bytree\": 0.8, \n    \"colsample_bynode\": 0.8,\n    \"verbose\": -1,\n    \"sample_weight\": \"balanced\",\n    \"random_state\": 42,\n    \"device\": \"gpu\",\n}\n\nfitted_models = []\n\nfor idx_train, idx_valid in cv.split(X, y, groups=weeks):\n    X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n    X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set=[(X_valid, y_valid), (X_train, y_train)],\n        callbacks=[lgb.log_evaluation(100), \n                   lgb.early_stopping(first_metric_only=True,\n                        stopping_rounds=10,\n                        verbose=True,\n                        min_delta=0),\n                  ]\n    )\n\n    fitted_models.append(model)\nmodel_lgb_balanced = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:07:28.468283Z","iopub.execute_input":"2024-06-10T05:07:28.468547Z","iopub.status.idle":"2024-06-10T05:10:29.899167Z","shell.execute_reply.started":"2024-06-10T05:07:28.468520Z","shell.execute_reply":"2024-06-10T05:10:29.898071Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cal accuray and gini_score:\ndf_bases = []\nfor df in [df_train, df_val]:\n    df_base = df[[\"case_id\",\"WEEK_NUM\",\"target\"]]\n    X_val= df.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n#     P_pred = model.predict(X_val)\n    P_pred = model_lgb_balanced.predict_proba(X_val)[:,1]\n    df_base[\"P_pred\"] = P_pred\n    df_bases.append(df_base)\n    y_pred = (P_pred >= 0.5).astype(dtype=\"int32\")\n    accuracy = accuracy_score(\n            y_true=df[\"target\"],\n            y_pred=y_pred\n        )\n    auc = roc_auc_score(\n            y_true=df[\"target\"],\n            y_score=P_pred\n        )\n    gini = 2*auc - 1\n    print(\"accuray, auc, gini =\",accuracy, auc, gini)\n","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:10:29.903071Z","iopub.execute_input":"2024-06-10T05:10:29.903973Z","iopub.status.idle":"2024-06-10T05:11:13.652799Z","shell.execute_reply.started":"2024-06-10T05:10:29.903943Z","shell.execute_reply":"2024-06-10T05:11:13.651760Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_stability_score(\n    dt_base,\n    # Weight for average (in week number) of Gini coefficient\n    w_G_av=1,\n    # Weight for the slope of the Gini coefficient (if negative)\n    w_a=88.0,\n    # Weight for the root mean square deviation of the linear regression Gini\n    # coefficients from the actual ones\n    w_RMSD=-0.5\n):\n    # List of Gini coefficients - one for each week number\n    # [NOTE: the base pandas dataframe is sorted and grouped by WEEK_NUM. The respective\n    # lists of labels (y) and predicted probabilities (P_pred) for each week number are\n    # taken and a respective Gini coefficient is computed.]\n    G = dt_base[[\"WEEK_NUM\", \"target\", \"P_pred\"]]\\\n        .sort_values(by=\"WEEK_NUM\")\\\n        .groupby(by=\"WEEK_NUM\")[[\"target\", \"P_pred\"]]\\\n        .apply(lambda x:\n               2 * roc_auc_score(x[\"target\"], x[\"P_pred\"]) - 1).tolist()\n    \n    # Average (in week number) Gini coefficient\n    G_av = np.mean(G)\n\n    # Array of indices for the Gini coefficients\n    i = np.arange(len(G))\n    \n    # Weight (a) and bias (_) of the linear regression\n    [a, b] = np.polyfit(x=i, y=G, deg=1)\n    \n    # Array of fit Gini coefficients\n    G_fit = a * i + b\n    \n    # Root mean square deviation of the fit Gini values from the actual ones \n    RMSD = np.sqrt(np.mean((G_fit - G)**2))\n\n    # Stability score\n    stability_score = w_G_av * G_av + w_a * min(0, a) + w_RMSD * RMSD\n    \n    # Dictionary of stability score elements\n    dt = {\n        \"g_week\": G,\n        \"a\": a,\n        \"b\": b,\n        \"RMSD\": RMSD,\n        \"stability_score\": stability_score\n    }\n    \n    return dt","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:13.654293Z","iopub.execute_input":"2024-06-10T05:11:13.654977Z","iopub.status.idle":"2024-06-10T05:11:13.664872Z","shell.execute_reply.started":"2024-06-10T05:11:13.654941Z","shell.execute_reply":"2024-06-10T05:11:13.663847Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"On training set:\")\nprint(get_stability_score(df_bases[0]))\n\nprint(\"On validation set:\")\nprint(get_stability_score(df_bases[1]))","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:13.666063Z","iopub.execute_input":"2024-06-10T05:11:13.666330Z","iopub.status.idle":"2024-06-10T05:11:14.580938Z","shell.execute_reply.started":"2024-06-10T05:11:13.666307Z","shell.execute_reply":"2024-06-10T05:11:14.580082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Catboost","metadata":{}},{"cell_type":"code","source":"from catboost import CatBoostClassifier, Pool","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.581965Z","iopub.execute_input":"2024-06-10T05:11:14.582224Z","iopub.status.idle":"2024-06-10T05:11:14.586380Z","shell.execute_reply.started":"2024-06-10T05:11:14.582202Z","shell.execute_reply":"2024-06-10T05:11:14.585571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# print(df_train.dtypes.unique())\ndisplay(df_train.head(10))\nprint(df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.587218Z","iopub.execute_input":"2024-06-10T05:11:14.587460Z","iopub.status.idle":"2024-06-10T05:11:14.629337Z","shell.execute_reply.started":"2024-06-10T05:11:14.587439Z","shell.execute_reply":"2024-06-10T05:11:14.628531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n# X = df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n# y = df_train[\"target\"]\n# weeks = df_train[\"WEEK_NUM\"]\n\n# cv = StratifiedGroupKFold(n_splits=5, shuffle=True)\n\n\n# cat_fitted_models = []\n# cv_scores_cat=[]\n# for idx_train, idx_valid in cv.split(X, y, groups=weeks):\n#     X_train, y_train = X.iloc[idx_train], y.iloc[idx_train]\n#     X_valid, y_valid = X.iloc[idx_valid], y.iloc[idx_valid]\n\n#     train_pool = Pool(X_train, y_train, cat_features=cat_cols)\n#     val_pool = Pool(X_valid, y_valid, cat_features=cat_cols)\n\n#     clf = CatBoostClassifier(\n# #         best_model_min_trees = 1200,\n#         boosting_type = \"Plain\",\n#         eval_metric = \"AUC\",\n#         iterations = 200,\n#         learning_rate = 0.03,\n#         l2_leaf_reg = 10,\n#         max_leaves = 64,\n#         random_seed = 42,\n#         task_type = \"GPU\",\n#         use_best_model = True,\n#         verbose = True\n#     )\n\n#     clf.fit(train_pool, eval_set=val_pool, verbose=False)\n#     y_pred_valid = clf.predict_proba(X_valid)[:, 1]\n#     auc_score = roc_auc_score(y_valid, y_pred_valid)\n#     cv_scores_cat.append(auc_score)\n#     cat_fitted_models.append(clf)\n\n# cat_model = VotingModel(cat_fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:16:47.110189Z","iopub.execute_input":"2024-06-10T05:16:47.110853Z","iopub.status.idle":"2024-06-10T05:44:24.627895Z","shell.execute_reply.started":"2024-06-10T05:16:47.110824Z","shell.execute_reply":"2024-06-10T05:44:24.627038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cv_scores_cat","metadata":{"execution":{"iopub.status.busy":"2024-06-10T06:07:54.426961Z","iopub.execute_input":"2024-06-10T06:07:54.427432Z","iopub.status.idle":"2024-06-10T06:07:54.434204Z","shell.execute_reply.started":"2024-06-10T06:07:54.427406Z","shell.execute_reply":"2024-06-10T06:07:54.433284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# gc.collect()\n# class VotingModel_cat(BaseEstimator, ClassifierMixin):\n#     def __init__(self, estimators):\n#         super().__init__()\n#         self.estimators = estimators\n        \n#     def fit(self, X, y=None):\n#         return self\n    \n#     def predict(self, X):\n#         y_preds = [estimator.predict(X) for estimator in self.estimators]\n#         return np.mean(y_preds, axis=0)\n    \n#     def predict_proba(self, X):\n#         y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n#         return np.mean(y_preds, axis=0)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:52:22.683968Z","iopub.execute_input":"2024-06-10T05:52:22.684782Z","iopub.status.idle":"2024-06-10T05:52:22.823756Z","shell.execute_reply.started":"2024-06-10T05:52:22.684747Z","shell.execute_reply":"2024-06-10T05:52:22.822747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cat_model = VotingModel_cat(cat_fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:52:44.767447Z","iopub.execute_input":"2024-06-10T05:52:44.768236Z","iopub.status.idle":"2024-06-10T05:52:44.772265Z","shell.execute_reply.started":"2024-06-10T05:52:44.768207Z","shell.execute_reply":"2024-06-10T05:52:44.771145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_bases = []\n# for df in [df_train, df_val]:\n#     df_base = df[[\"case_id\",\"WEEK_NUM\",\"target\"]]\n#     X_val= df.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n# #     P_pred = model.predict(X_val)\n#     P_pred = cat_model.predict_proba(X_val)[:,1]\n#     df_base[\"P_pred\"] = P_pred\n#     df_bases.append(df_base)\n#     y_pred = (P_pred >= 0.5).astype(dtype=\"int32\")\n#     accuracy = accuracy_score(\n#             y_true=df[\"target\"],\n#             y_pred=y_pred\n#         )\n#     auc = roc_auc_score(\n#             y_true=df[\"target\"],\n#             y_score=P_pred\n#         )\n#     gini = 2*auc - 1\n#     print(\"accuray, auc, gini =\",accuracy, auc, gini)\n    \n# print(\"On training set:\")\n# print(get_stability_score(df_bases[0])[\"stability_score\"])\n\n# print(\"On validation set:\")\n# print(get_stability_score(df_bases[1])[\"stability_score\"])","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:52:50.035937Z","iopub.execute_input":"2024-06-10T05:52:50.036554Z","iopub.status.idle":"2024-06-10T06:06:36.276477Z","shell.execute_reply.started":"2024-06-10T05:52:50.036523Z","shell.execute_reply":"2024-06-10T06:06:36.275565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# # joblib.dump(fitted_models, 'lgbm_model-5fold.pkl')\n# import os\n# import zipfile\n# # os.mkdir(\"lgbmodels\")\n# # 创建一个 ZIP 文件\n# for i in range(len(fitted_models)):\n#     fitted_models[i].booster_.save_model(f'lgbmodels/model{i}.txt')\n    \n# zip_file = zipfile.ZipFile('/kaggle/working/lgbmodels.zip', mode='w')\n\n# # 遍历 /kaggle/working/ 目录,添加所需文件到 ZIP 文件\n# for folder, subfolders, files in os.walk('/kaggle/working/lgbmodels'):\n#     for file in files:\n#         # 构建文件在 ZIP 中的路径\n#         zip_path = os.path.join(folder, file)\n#         # 添加文件到 ZIP 归档\n#         zip_file.write(zip_path, arcname=os.path.basename(zip_path))\n# # 关闭 ZIP 文件\n# zip_file.close()","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.654059Z","iopub.execute_input":"2024-06-10T05:11:14.654358Z","iopub.status.idle":"2024-06-10T05:11:14.665915Z","shell.execute_reply.started":"2024-06-10T05:11:14.654335Z","shell.execute_reply":"2024-06-10T05:11:14.665024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train=reduce_mem_usage(df_train)\n# df_test = reduce_mem_usage(df_test)\n\n# joblib.dump((df_train,df_test),'data.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.666933Z","iopub.execute_input":"2024-06-10T05:11:14.667175Z","iopub.status.idle":"2024-06-10T05:11:14.675122Z","shell.execute_reply.started":"2024-06-10T05:11:14.667154Z","shell.execute_reply":"2024-06-10T05:11:14.674249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# df_train,df_test=joblib.load('/kaggle/working/data.pkl')","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.676122Z","iopub.execute_input":"2024-06-10T05:11:14.677155Z","iopub.status.idle":"2024-06-10T05:11:14.685281Z","shell.execute_reply.started":"2024-06-10T05:11:14.677129Z","shell.execute_reply":"2024-06-10T05:11:14.684458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# def make_consist_cattype(df, df_ref):\n#     for col in df.select_dtypes(include=[\"category\"]).columns:\n#         cat_ref = df_ref[col].cat.categories.to_list()\n#         new_dtype = pd.CategoricalDtype(categories=cat_ref,\n#                                         ordered=True)\n#         df[col] = df[col].astype(new_dtype)\n\n# make_consist_cattype(df_test,df_train)\n        ","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.686500Z","iopub.execute_input":"2024-06-10T05:11:14.687264Z","iopub.status.idle":"2024-06-10T05:11:14.695186Z","shell.execute_reply.started":"2024-06-10T05:11:14.687231Z","shell.execute_reply":"2024-06-10T05:11:14.694406Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test= df_test.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ny_pred = pd.Series(model_lgb_balanced.predict_proba(X_test)[:, 1], index=df_test.case_id)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:14.696308Z","iopub.execute_input":"2024-06-10T05:11:14.697020Z","iopub.status.idle":"2024-06-10T05:11:15.054210Z","shell.execute_reply.started":"2024-06-10T05:11:14.696989Z","shell.execute_reply":"2024-06-10T05:11:15.053333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm","metadata":{"execution":{"iopub.status.busy":"2024-06-10T05:11:15.055339Z","iopub.execute_input":"2024-06-10T05:11:15.055640Z","iopub.status.idle":"2024-06-10T05:11:15.064297Z","shell.execute_reply.started":"2024-06-10T05:11:15.055616Z","shell.execute_reply":"2024-06-10T05:11:15.063397Z"},"trusted":true},"execution_count":null,"outputs":[]}]}