{"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":"gpu","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"}],"dockerImageVersionId":30665,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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\n\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nfrom datetime import datetime\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-29T09:48:06.459403Z","iopub.execute_input":"2024-05-29T09:48:06.459791Z","iopub.status.idle":"2024-05-29T09:48:06.467327Z","shell.execute_reply.started":"2024-05-29T09:48:06.459761Z","shell.execute_reply":"2024-05-29T09:48:06.466385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"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\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.7:\n                    df = df.drop(col)\n        \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\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_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        \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        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return expr_max +expr_last+expr_mean\n    \n    def date_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"D\")]\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        expr_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return  expr_max +expr_last+expr_mean\n    \n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\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        #expr_count = [pl.count(col).alias(f\"count_{col}\") for col in cols]\n        return  expr_max +expr_last#+expr_count\n    \n    def other_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"T\", \"L\")]\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_max +expr_last\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_max +expr_last\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\ndef 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\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\n\ndef 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\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\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    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":{"execution":{"iopub.status.busy":"2024-05-29T09:48:06.469012Z","iopub.execute_input":"2024-05-29T09:48:06.469314Z","iopub.status.idle":"2024-05-29T09:48:06.511523Z","shell.execute_reply.started":"2024-05-29T09:48:06.469291Z","shell.execute_reply":"2024-05-29T09:48:06.510574Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR        = ROOT / \"parquet_files\" / \"test\"","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:48:06.512739Z","iopub.execute_input":"2024-05-29T09:48:06.513135Z","iopub.status.idle":"2024-05-29T09:48:06.524334Z","shell.execute_reply.started":"2024-05-29T09:48:06.513102Z","shell.execute_reply":"2024-05-29T09:48:06.523408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_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":{"execution":{"iopub.status.busy":"2024-05-29T09:48:06.526843Z","iopub.execute_input":"2024-05-29T09:48:06.527316Z","iopub.status.idle":"2024-05-29T09:50:18.383426Z","shell.execute_reply.started":"2024-05-29T09:48:06.527284Z","shell.execute_reply":"2024-05-29T09:50:18.382397Z"},"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\ngc.collect()\ndf_train = df_train.pipe(Pipeline.filter_cols)\ndf_train, cat_cols = to_pandas(df_train)\ndf_train = reduce_mem_usage(df_train)\nprint(\"train data shape:\\t\", df_train.shape)\nnums=df_train.select_dtypes(exclude='category').columns\nfrom itertools import combinations, permutations\n#df_train=df_train[nums]\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()\n\ndef 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            #print(str(gg)+'-'+str(n),', ',end='')\n        use.append(vx)\n        #print()\n    print('Use these',use)\n    return use\n\ndef group_columns_by_correlation(matrix, threshold=0.8):\n    # 计算列之间的相关性\n    correlation_matrix = matrix.corr()\n\n    # 分组列\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\n\nuses=[]\nfor k,v in nans_groups.items():\n    if len(v)>1:\n            Vs = nans_groups[k]\n            #cross_features=list(combinations(Vs, 2))\n            #make_corr(Vs)\n            grps= group_columns_by_correlation(df_train[Vs], threshold=0.8)\n            use=reduce_group(grps)\n            uses=uses+use\n            #make_corr(use)\n    else:\n        uses=uses+v\n    print('####### NAN count =',k)\nprint(uses)\nprint(len(uses))\nuses=uses+list(df_train.select_dtypes(include='category').columns)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:50:18.385259Z","iopub.execute_input":"2024-05-29T09:50:18.385653Z","iopub.status.idle":"2024-05-29T09:51:56.424338Z","shell.execute_reply.started":"2024-05-29T09:50:18.385619Z","shell.execute_reply":"2024-05-29T09:51:56.423305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = pd.read_csv(\"/kaggle/input/home-credit-credit-risk-model-stability/sample_submission.csv\")\ndevice='gpu'\n#n_samples=200000\nn_est=6000\nDRY_RUN = True if sample.shape[0] == 10 else False   \nif DRY_RUN:\n    device='cpu'\n    df_train = df_train.iloc[:50000]\n    #n_samples=10000\n    n_est=600\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:56.425986Z","iopub.execute_input":"2024-05-29T09:51:56.426332Z","iopub.status.idle":"2024-05-29T09:51:56.437005Z","shell.execute_reply.started":"2024-05-29T09:51:56.426306Z","shell.execute_reply":"2024-05-29T09:51:56.436048Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_store = {\n    \"df_base\": read_file(TEST_DIR / \"test_base.parquet\"),\n    \"depth_0\": [\n        read_file(TEST_DIR / \"test_static_cb_0.parquet\"),\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),\n        read_file(TEST_DIR / \"test_tax_registry_b_1.parquet\", 1),\n        read_file(TEST_DIR / \"test_tax_registry_c_1.parquet\", 1),\n        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TEST_DIR / \"test_credit_bureau_b_1.parquet\", 1),\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),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:56.438168Z","iopub.execute_input":"2024-05-29T09:51:56.438480Z","iopub.status.idle":"2024-05-29T09:51:56.635530Z","shell.execute_reply.started":"2024-05-29T09:51:56.438456Z","shell.execute_reply":"2024-05-29T09:51:56.634689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()\ndf_test = df_test.select([col for col in df_train.columns if col != \"target\"])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\n\ndf_test, cat_cols = to_pandas(df_test, cat_cols)\ndf_test = reduce_mem_usage(df_test)\n\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:56.636557Z","iopub.execute_input":"2024-05-29T09:51:56.636804Z","iopub.status.idle":"2024-05-29T09:51:57.341538Z","shell.execute_reply.started":"2024-05-29T09:51:56.636783Z","shell.execute_reply":"2024-05-29T09:51:57.340622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{}},{"cell_type":"code","source":"y = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.342864Z","iopub.execute_input":"2024-05-29T09:51:57.343187Z","iopub.status.idle":"2024-05-29T09:51:57.485162Z","shell.execute_reply.started":"2024-05-29T09:51:57.343162Z","shell.execute_reply":"2024-05-29T09:51:57.484297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train[cat_cols] = df_train[cat_cols].astype(str)\ndf_test[cat_cols] = df_test[cat_cols].astype(str)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.488459Z","iopub.execute_input":"2024-05-29T09:51:57.488748Z","iopub.status.idle":"2024-05-29T09:51:57.767931Z","shell.execute_reply.started":"2024-05-29T09:51:57.488723Z","shell.execute_reply":"2024-05-29T09:51:57.767156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.769054Z","iopub.execute_input":"2024-05-29T09:51:57.769350Z","iopub.status.idle":"2024-05-29T09:51:57.840322Z","shell.execute_reply.started":"2024-05-29T09:51:57.769320Z","shell.execute_reply":"2024-05-29T09:51:57.839371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"params = {\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    \"device\": device, \n    \"verbose\": -1,\n}","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.841500Z","iopub.execute_input":"2024-05-29T09:51:57.841797Z","iopub.status.idle":"2024-05-29T09:51:57.847454Z","shell.execute_reply.started":"2024-05-29T09:51:57.841771Z","shell.execute_reply":"2024-05-29T09:51:57.846489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_est = 3000","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.849838Z","iopub.execute_input":"2024-05-29T09:51:57.850135Z","iopub.status.idle":"2024-05-29T09:51:57.860619Z","shell.execute_reply.started":"2024-05-29T09:51:57.850111Z","shell.execute_reply":"2024-05-29T09:51:57.859777Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from catboost import CatBoostClassifier, Pool","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.861739Z","iopub.execute_input":"2024-05-29T09:51:57.862062Z","iopub.status.idle":"2024-05-29T09:51:57.869654Z","shell.execute_reply.started":"2024-05-29T09:51:57.862031Z","shell.execute_reply":"2024-05-29T09:51:57.868775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nfitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\nstability_results_cat = []\nstability_results_lgb = []\n\nfold = 0\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    \n    df_res_cat = pd.DataFrame()\n    df_res_lgb = pd.DataFrame()\n    \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid, week_valid = df_train.iloc[idx_valid], y.iloc[idx_valid], weeks[idx_valid]\n    \n    df_res_cat['WEEK_NUM'] = list(week_valid)\n    df_res_cat['target'] = list(y_valid)\n    df_res_cat['fold'] = fold\n    \n    \n    df_res_lgb['WEEK_NUM'] = list(week_valid)\n    df_res_lgb['target'] = list(y_valid)\n    df_res_lgb['fold'] = fold\n    \n    fold += 1\n    \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(eval_metric='AUC', task_type='GPU', learning_rate=0.03, iterations=n_est)\n    \n    random_seed=3107\n    \n    clf.fit(train_pool, eval_set=val_pool,verbose=300)\n    fitted_models_cat.append(clf)\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    \n    df_res_cat['score'] = list(y_pred_valid)\n    \n    \n    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\n    \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    \n    fitted_models_lgb.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_lgb.append(auc_score)\n    \n    df_res_lgb['score'] = list(y_pred_valid)\n    \n    stability_results_cat.append(df_res_cat)\n    stability_results_lgb.append(df_res_lgb)\n    \n    \nprint(\"Catboost CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum Catboost CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"Lightgbm CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum Lightgbm CV AUC score: \", max(cv_scores_lgb))","metadata":{"execution":{"iopub.status.busy":"2024-05-29T09:51:57.870837Z","iopub.execute_input":"2024-05-29T09:51:57.871240Z","iopub.status.idle":"2024-05-29T10:30:49.013518Z","shell.execute_reply.started":"2024-05-29T09:51:57.871207Z","shell.execute_reply":"2024-05-29T10:30:49.012284Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv_scores_cat","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.014640Z","iopub.execute_input":"2024-05-29T10:30:49.014992Z","iopub.status.idle":"2024-05-29T10:30:49.021469Z","shell.execute_reply.started":"2024-05-29T10:30:49.014961Z","shell.execute_reply":"2024-05-29T10:30:49.020573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cv_scores_lgb","metadata":{"execution":{"iopub.status.busy":"2024-05-29T11:56:35.144303Z","iopub.execute_input":"2024-05-29T11:56:35.145021Z","iopub.status.idle":"2024-05-29T11:56:35.474925Z","shell.execute_reply.started":"2024-05-29T11:56:35.144986Z","shell.execute_reply":"2024-05-29T11:56:35.473573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"catboost_weights = np.array(cv_scores_cat+cv_scores_lgb) / np.sum(cv_scores_cat+cv_scores_lgb)\ncatboost_weights","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.022606Z","iopub.execute_input":"2024-05-29T10:30:49.023143Z","iopub.status.idle":"2024-05-29T10:30:49.034297Z","shell.execute_reply.started":"2024-05-29T10:30:49.023118Z","shell.execute_reply":"2024-05-29T10:30:49.033294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_stability_results_cat = pd.concat(stability_results_cat)\ndf_stability_results_lgb = pd.concat(stability_results_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.035439Z","iopub.execute_input":"2024-05-29T10:30:49.035707Z","iopub.status.idle":"2024-05-29T10:30:49.047250Z","shell.execute_reply.started":"2024-05-29T10:30:49.035685Z","shell.execute_reply":"2024-05-29T10:30:49.046277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_stability_results_cat","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.048552Z","iopub.execute_input":"2024-05-29T10:30:49.048847Z","iopub.status.idle":"2024-05-29T10:30:49.062443Z","shell.execute_reply.started":"2024-05-29T10:30:49.048806Z","shell.execute_reply":"2024-05-29T10:30:49.061322Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def gini_stability(base, w_fallingrate=88.0, w_resstd=-0.5):\n    gini_in_time = base.loc[:, [\"WEEK_NUM\", \"target\", \"score\"]]\\\n        .sort_values(\"WEEK_NUM\")\\\n        .groupby(\"WEEK_NUM\")[[\"target\", \"score\"]]\\\n        .apply(lambda x: 2*roc_auc_score(x[\"target\"], x[\"score\"])-1).tolist()\n    \n    x = np.arange(len(gini_in_time))\n    y = gini_in_time\n    a, b = np.polyfit(x, y, 1)\n    y_hat = a*x + b\n    residuals = y - y_hat\n    res_std = np.std(residuals)\n    avg_gini = np.mean(gini_in_time)\n    return avg_gini + w_fallingrate * min(0, a) + w_resstd * res_std","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.063541Z","iopub.execute_input":"2024-05-29T10:30:49.063802Z","iopub.status.idle":"2024-05-29T10:30:49.070913Z","shell.execute_reply.started":"2024-05-29T10:30:49.063780Z","shell.execute_reply":"2024-05-29T10:30:49.070141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    df_stability_results_cat.groupby('fold').apply(gini_stability, include_groups=False)\nexcept:\n    pass","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.071932Z","iopub.execute_input":"2024-05-29T10:30:49.072225Z","iopub.status.idle":"2024-05-29T10:30:49.213222Z","shell.execute_reply.started":"2024-05-29T10:30:49.072203Z","shell.execute_reply":"2024-05-29T10:30:49.212224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gini_stability(df_stability_results_cat)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.214743Z","iopub.execute_input":"2024-05-29T10:30:49.215057Z","iopub.status.idle":"2024-05-29T10:30:49.341777Z","shell.execute_reply.started":"2024-05-29T10:30:49.215009Z","shell.execute_reply":"2024-05-29T10:30:49.340840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try:\n    df_stability_results_lgb.groupby('fold').apply(gini_stability, include_groups=False)\nexcept:\n    pass","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.343130Z","iopub.execute_input":"2024-05-29T10:30:49.343486Z","iopub.status.idle":"2024-05-29T10:30:49.482730Z","shell.execute_reply.started":"2024-05-29T10:30:49.343454Z","shell.execute_reply":"2024-05-29T10:30:49.481747Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"gini_stability(df_stability_results_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.483890Z","iopub.execute_input":"2024-05-29T10:30:49.484178Z","iopub.status.idle":"2024-05-29T10:30:49.612833Z","shell.execute_reply.started":"2024-05-29T10:30:49.484153Z","shell.execute_reply":"2024-05-29T10:30:49.611919Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-05-29T12:47:12.863605Z","iopub.execute_input":"2024-05-29T12:47:12.864509Z","iopub.status.idle":"2024-05-29T12:47:12.900213Z","shell.execute_reply.started":"2024-05-29T12:47:12.864472Z","shell.execute_reply":"2024-05-29T12:47:12.898957Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class VotingModel(BaseEstimator, RegressorMixin):\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        \n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[5:]]\n        \n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T12:49:27.818243Z","iopub.execute_input":"2024-05-29T12:49:27.818986Z","iopub.status.idle":"2024-05-29T12:49:27.855057Z","shell.execute_reply.started":"2024-05-29T12:49:27.818955Z","shell.execute_reply":"2024-05-29T12:49:27.853706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.624200Z","iopub.execute_input":"2024-05-29T10:30:49.624466Z","iopub.status.idle":"2024-05-29T10:30:49.679887Z","shell.execute_reply.started":"2024-05-29T10:30:49.624443Z","shell.execute_reply":"2024-05-29T10:30:49.678967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model5 = VotingModel(fitted_models_cat)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T12:49:24.117322Z","iopub.execute_input":"2024-05-29T12:49:24.117695Z","iopub.status.idle":"2024-05-29T12:49:24.141365Z","shell.execute_reply.started":"2024-05-29T12:49:24.117671Z","shell.execute_reply":"2024-05-29T12:49:24.140139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model6 = VotingModel(fitted_models_lgb)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from scipy.stats import gmean\nclass VotingModel2(BaseEstimator, RegressorMixin):\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 gmean(y_preds, axis=0)\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]   \n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[5:]]\n        return gmean(y_preds, axis=0)\nmodel2 = VotingModel2(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.681046Z","iopub.execute_input":"2024-05-29T10:30:49.681315Z","iopub.status.idle":"2024-05-29T10:30:49.688703Z","shell.execute_reply.started":"2024-05-29T10:30:49.681293Z","shell.execute_reply":"2024-05-29T10:30:49.687820Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model2","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.694487Z","iopub.execute_input":"2024-05-29T10:30:49.694759Z","iopub.status.idle":"2024-05-29T10:30:49.743872Z","shell.execute_reply.started":"2024-05-29T10:30:49.694735Z","shell.execute_reply":"2024-05-29T10:30:49.742999Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nclass VotingModel3(BaseEstimator, RegressorMixin):\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        harmonic_mean = len(y_preds) / np.sum(1 / np.array(y_preds), axis=0)\n        return harmonic_mean\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X) for estimator in self.estimators[5:]]\n        harmonic_mean = len(y_preds) / np.sum(1 / np.array(y_preds), axis=0)\n        return harmonic_mean\nmodel3 = VotingModel3(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.744973Z","iopub.execute_input":"2024-05-29T10:30:49.745332Z","iopub.status.idle":"2024-05-29T10:30:49.753814Z","shell.execute_reply.started":"2024-05-29T10:30:49.745295Z","shell.execute_reply":"2024-05-29T10:30:49.752827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.755078Z","iopub.execute_input":"2024-05-29T10:30:49.755362Z","iopub.status.idle":"2024-05-29T10:30:49.810459Z","shell.execute_reply.started":"2024-05-29T10:30:49.755340Z","shell.execute_reply":"2024-05-29T10:30:49.809626Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nclass VotingModel4(BaseEstimator, RegressorMixin):\n    def __init__(self, estimators, weights):\n        super().__init__()\n        self.estimators = estimators\n        self.weights = weights\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        weighted_preds = np.average(y_preds, axis=0, weights=self.weights)\n        return weighted_preds\n    \n    def predict_proba(self, X):\n        y_preds = [estimator.predict_proba(X) for estimator in self.estimators[:5]]\n        \n        X_cat = X.copy()\n        X_cat[cat_cols] = X[cat_cols].astype(\"category\")\n        \n        y_preds += [estimator.predict_proba(X_cat) for estimator in self.estimators[5:]]\n        weighted_probs = np.average(y_preds, axis=0, weights=self.weights)\n        return weighted_probs\n#权重\ncatboost_weights = np.array(cv_scores_cat) / np.sum(cv_scores_cat + cv_scores_lgb)\nlgb_weights = np.array(cv_scores_lgb) / np.sum(cv_scores_cat + cv_scores_lgb)\n\nmodel4 = VotingModel4(fitted_models_cat + fitted_models_lgb, weights=np.concatenate([catboost_weights, lgb_weights]))","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.811405Z","iopub.execute_input":"2024-05-29T10:30:49.811641Z","iopub.status.idle":"2024-05-29T10:30:49.821531Z","shell.execute_reply.started":"2024-05-29T10:30:49.811621Z","shell.execute_reply":"2024-05-29T10:30:49.820666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model4","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.822605Z","iopub.execute_input":"2024-05-29T10:30:49.822918Z","iopub.status.idle":"2024-05-29T10:30:49.885327Z","shell.execute_reply.started":"2024-05-29T10:30:49.822890Z","shell.execute_reply":"2024-05-29T10:30:49.884425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# feature_importance =fitted_models[2].get_feature_importance(type='PredictionValuesChange')\n\n# # 获取特征名称\n# feature_names = X_train.columns\n\n# # 对特征重要性进行排序\n# sorted_idx = np.argsort(feature_importance)\n\n# # 绘制特征重要性图\n# plt.figure(figsize=(20, 60))\n# plt.barh(range(len(sorted_idx)), feature_importance[sorted_idx], align='center')\n# plt.yticks(range(len(sorted_idx)), [feature_names[i] for i in sorted_idx])\n# plt.xlabel('Feature Importance')\n# plt.ylabel('Features')\n# plt.title('CatBoost Feature Importance')\n# plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.886295Z","iopub.execute_input":"2024-05-29T10:30:49.886561Z","iopub.status.idle":"2024-05-29T10:30:49.890941Z","shell.execute_reply.started":"2024-05-29T10:30:49.886538Z","shell.execute_reply":"2024-05-29T10:30:49.889926Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Submission","metadata":{}},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\n\n\ny_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:49.892241Z","iopub.execute_input":"2024-05-29T10:30:49.892572Z","iopub.status.idle":"2024-05-29T10:30:50.433865Z","shell.execute_reply.started":"2024-05-29T10:30:49.892539Z","shell.execute_reply":"2024-05-29T10:30:50.432921Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model2.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:50.435080Z","iopub.execute_input":"2024-05-29T10:30:50.435381Z","iopub.status.idle":"2024-05-29T10:30:50.923642Z","shell.execute_reply.started":"2024-05-29T10:30:50.435357Z","shell.execute_reply":"2024-05-29T10:30:50.922660Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model3.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:50.924763Z","iopub.execute_input":"2024-05-29T10:30:50.925121Z","iopub.status.idle":"2024-05-29T10:30:51.407761Z","shell.execute_reply.started":"2024-05-29T10:30:50.925087Z","shell.execute_reply":"2024-05-29T10:30:51.406832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model4.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-05-29T10:30:51.408872Z","iopub.execute_input":"2024-05-29T10:30:51.409155Z","iopub.status.idle":"2024-05-29T10:30:51.885484Z","shell.execute_reply.started":"2024-05-29T10:30:51.409131Z","shell.execute_reply":"2024-05-29T10:30:51.884581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model5.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.Series(model6.predict_proba(df_test)[:, 1], index=df_test.index)\ndf_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\n\ndf_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{},"execution_count":null,"outputs":[]}]}