{"metadata":{"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8299095,"sourceType":"datasetVersion","datasetId":4930184},{"sourceId":172484134,"sourceType":"kernelVersion"},{"sourceId":173192285,"sourceType":"kernelVersion"},{"sourceId":173296608,"sourceType":"kernelVersion"},{"sourceId":173736853,"sourceType":"kernelVersion"},{"sourceId":173741328,"sourceType":"kernelVersion"}],"dockerImageVersionId":30683,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true},"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.10.13"},"papermill":{"default_parameters":{},"duration":281.414705,"end_time":"2024-04-17T08:36:36.275874","environment_variables":{},"exception":null,"input_path":"__notebook__.ipynb","output_path":"__notebook__.ipynb","parameters":{},"start_time":"2024-04-17T08:31:54.861169","version":"2.5.0"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## 未实验：\n### 20240502\n- 多Fold训练Stability模型 （无效）\n- Stability模型添加Category列 （排队准备实验）\n- 增加catboost和lgb模型的训练时长(50%) （实验中）\n- 使用十个Fold训练catboost和lgb模型（排队准备实验）\n- dart模型集成（无效）","metadata":{}},{"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\n\nHACKCOL_O = 'refreshdate_3813885D'\nHACKCOL = 'min_refreshdate_3813885D'","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2024-04-17T08:31:57.752636Z","iopub.status.busy":"2024-04-17T08:31:57.752205Z","iopub.status.idle":"2024-04-17T08:32:04.546194Z","shell.execute_reply":"2024-04-17T08:32:04.545102Z"},"papermill":{"duration":6.806715,"end_time":"2024-04-17T08:32:04.54887","exception":false,"start_time":"2024-04-17T08:31:57.742155","status":"completed"},"tags":[]},"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 if col == HACKCOL_O]\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_min+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.execute_input":"2024-04-17T08:32:04.56691Z","iopub.status.busy":"2024-04-17T08:32:04.565911Z","iopub.status.idle":"2024-04-17T08:32:04.610393Z","shell.execute_reply":"2024-04-17T08:32:04.609387Z"},"papermill":{"duration":0.055972,"end_time":"2024-04-17T08:32:04.612742","exception":false,"start_time":"2024-04-17T08:32:04.55677","status":"completed"},"tags":[]},"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.execute_input":"2024-04-17T08:32:04.629397Z","iopub.status.busy":"2024-04-17T08:32:04.628788Z","iopub.status.idle":"2024-04-17T08:32:04.633474Z","shell.execute_reply":"2024-04-17T08:32:04.632498Z"},"papermill":{"duration":0.015224,"end_time":"2024-04-17T08:32:04.635656","exception":false,"start_time":"2024-04-17T08:32:04.620432","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndata_store = {\n    \"df_base\": read_file(TRAIN_DIR / \"train_base.parquet\"),\n    \"depth_0\": [\n        read_file(TRAIN_DIR / \"train_static_cb_0.parquet\"),\n        read_files(TRAIN_DIR / \"train_static_0_*.parquet\"),\n    ],\n    \"depth_1\": [\n        read_files(TRAIN_DIR / \"train_applprev_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_a_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_tax_registry_c_1.parquet\", 1),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_1_*.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_other_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_person_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_deposit_1.parquet\", 1),\n        read_file(TRAIN_DIR / \"train_debitcard_1.parquet\", 1),\n    ],\n    \"depth_2\": [\n        read_file(TRAIN_DIR / \"train_credit_bureau_b_2.parquet\", 2),\n        read_files(TRAIN_DIR / \"train_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_applprev_2.parquet\", 2),\n        read_file(TRAIN_DIR / \"train_person_2.parquet\", 2)\n    ]\n}","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:32:04.651735Z","iopub.status.busy":"2024-04-17T08:32:04.651424Z","iopub.status.idle":"2024-04-17T08:34:34.304673Z","shell.execute_reply":"2024-04-17T08:34:34.30364Z"},"papermill":{"duration":149.672065,"end_time":"2024-04-17T08:34:34.315247","exception":false,"start_time":"2024-04-17T08:32:04.643182","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\ndf_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    if col == HACKCOL:\n        continue\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)\nif HACKCOL not in uses:\n    uses.append(HACKCOL)\nprint(len(uses))\ndf_train=df_train[uses]","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:34:34.331555Z","iopub.status.busy":"2024-04-17T08:34:34.331234Z","iopub.status.idle":"2024-04-17T08:36:26.470426Z","shell.execute_reply":"2024-04-17T08:36:26.469148Z"},"papermill":{"duration":112.149885,"end_time":"2024-04-17T08:36:26.472648","exception":false,"start_time":"2024-04-17T08:34:34.322763","status":"completed"},"tags":[]},"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[:500]\n    #n_samples=10000\n    n_est=60\nprint(device)","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:26.496982Z","iopub.status.busy":"2024-04-17T08:36:26.496652Z","iopub.status.idle":"2024-04-17T08:36:26.512033Z","shell.execute_reply":"2024-04-17T08:36:26.510927Z"},"papermill":{"duration":0.03013,"end_time":"2024-04-17T08:36:26.514189","exception":false,"start_time":"2024-04-17T08:36:26.484059","status":"completed"},"tags":[]},"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.execute_input":"2024-04-17T08:36:26.539106Z","iopub.status.busy":"2024-04-17T08:36:26.53879Z","iopub.status.idle":"2024-04-17T08:36:26.933409Z","shell.execute_reply":"2024-04-17T08:36:26.932466Z"},"papermill":{"duration":0.410219,"end_time":"2024-04-17T08:36:26.935984","exception":false,"start_time":"2024-04-17T08:36:26.525765","status":"completed"},"tags":[]},"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\n\ngc.collect()","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:26.960824Z","iopub.status.busy":"2024-04-17T08:36:26.960467Z","iopub.status.idle":"2024-04-17T08:36:27.543261Z","shell.execute_reply":"2024-04-17T08:36:27.542206Z"},"papermill":{"duration":0.597919,"end_time":"2024-04-17T08:36:27.545974","exception":false,"start_time":"2024-04-17T08:36:26.948055","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature Selection","metadata":{"papermill":{"duration":0.011842,"end_time":"2024-04-17T08:36:27.569987","exception":false,"start_time":"2024-04-17T08:36:27.558145","status":"completed"},"tags":[]}},{"cell_type":"code","source":"fd = 2 if DRY_RUN else 5\ny = df_train[\"target\"]\nweeks = df_train[\"WEEK_NUM\"]\ndf_train= df_train.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\nif DRY_RUN:\n    pass\n    #df_test = df_train.copy()\ncv = StratifiedGroupKFold(n_splits=fd, shuffle=False)","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:27.595439Z","iopub.status.busy":"2024-04-17T08:36:27.594972Z","iopub.status.idle":"2024-04-17T08:36:27.693605Z","shell.execute_reply":"2024-04-17T08:36:27.692644Z"},"papermill":{"duration":0.114077,"end_time":"2024-04-17T08:36:27.696072","exception":false,"start_time":"2024-04-17T08:36:27.581995","status":"completed"},"tags":[]},"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.execute_input":"2024-04-17T08:36:27.721761Z","iopub.status.busy":"2024-04-17T08:36:27.721044Z","iopub.status.idle":"2024-04-17T08:36:27.783266Z","shell.execute_reply":"2024-04-17T08:36:27.782394Z"},"papermill":{"duration":0.077824,"end_time":"2024-04-17T08:36:27.785827","exception":false,"start_time":"2024-04-17T08:36:27.708003","status":"completed"},"tags":[]},"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.execute_input":"2024-04-17T08:36:27.812193Z","iopub.status.busy":"2024-04-17T08:36:27.811336Z","iopub.status.idle":"2024-04-17T08:36:27.817674Z","shell.execute_reply":"2024-04-17T08:36:27.816644Z"},"papermill":{"duration":0.022012,"end_time":"2024-04-17T08:36:27.819986","exception":false,"start_time":"2024-04-17T08:36:27.797974","status":"completed"},"tags":[]},"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)*0.8 for estimator in self.estimators[:fd]]\n        \n        X[cat_cols] = X[cat_cols].astype(\"category\")\n        y_preds += [estimator.predict_proba(X)*1.2 for estimator in self.estimators[fd:]]\n        \n        return np.mean(y_preds, axis=0)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\nfrom catboost import CatBoostClassifier, Pool\n\nfitted_models_cat = []\nfitted_models_lgb = []\n\ncv_scores_cat = []\ncv_scores_lgb = []\n\ndf_test.fillna(0, inplace=True)\ndf_train.fillna(0, inplace=True)\n\nimport joblib\n\nmodel_path = \"/kaggle/input/home-credit-lgb-cat-ensemble-nogroup2-train/lgb_cat_fold_5_20240422140926.pkl\"\nmodel_path2 = \"/kaggle/input/home-credit-lgb-cat-ensemble-nogroup-train/lgb_cat_fold_5_20240421213035.pkl\"\n#model_path2 = \"/kaggle/input/lgb-cat-fold-5-20240503162551/lgb_cat_fold_5_20240503162551.pkl\"\nmodel = joblib.load(model_path)\nmodel2 = joblib.load(model_path2)\n\n'''\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#\n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# \n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\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    clf = CatBoostClassifier(\n    eval_metric='AUC',\n    task_type='GPU',\n    learning_rate=0.03,\n    iterations=n_est)\n    random_seed=3107\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    \n    X_train[cat_cols] = X_train[cat_cols].astype(\"category\")\n    X_valid[cat_cols] = X_valid[cat_cols].astype(\"category\")\n    \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    \nprint(\"CV AUC scores: \", cv_scores_cat)\nprint(\"Maximum CV AUC score: \", max(cv_scores_cat))\n\n\nprint(\"CV AUC scores: \", cv_scores_lgb)\nprint(\"Maximum CV AUC score: \", max(cv_scores_lgb))\n'''","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:27.845503Z","iopub.status.busy":"2024-04-17T08:36:27.845176Z","iopub.status.idle":"2024-04-17T08:36:33.697862Z","shell.execute_reply":"2024-04-17T08:36:33.694975Z"},"papermill":{"duration":5.868655,"end_time":"2024-04-17T08:36:33.70094","exception":false,"start_time":"2024-04-17T08:36:27.832285","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#model = VotingModel(fitted_models_cat+fitted_models_lgb)","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:33.72948Z","iopub.status.busy":"2024-04-17T08:36:33.728946Z","iopub.status.idle":"2024-04-17T08:36:33.740405Z","shell.execute_reply":"2024-04-17T08:36:33.739541Z"},"papermill":{"duration":0.027973,"end_time":"2024-04-17T08:36:33.74302","exception":false,"start_time":"2024-04-17T08:36:33.715047","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test[HACKCOL].fillna(0, inplace=True)\ndf_test['WEEK_NUM'] = ( 2 - df_test[HACKCOL] ) // 7\ndf_test = df_test.set_index(\"case_id\")","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\ndf_subm['WEEK_NUM'] = df_test['WEEK_NUM']\ndf_test = df_test.drop(columns=[HACKCOL])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 训练一个模型用来区分df_train和df_test中的数据","metadata":{"papermill":{"duration":0.019527,"end_time":"2024-04-17T08:36:33.944674","exception":false,"start_time":"2024-04-17T08:36:33.925147","status":"completed"},"tags":[]}},{"cell_type":"code","source":"%%time\n# 找出df_train 和 df_test 中的公共列\ncommon_cols = df_train.columns.intersection(df_test.columns)\n#去掉非数值列\ncommon_cols = common_cols[common_cols.isin(df_train.select_dtypes(include=[np.number]).columns)]\n\ncommon_cols = [c for c in common_cols if c not in [\"WEEK_NUM\", \"case_id\"]]\n'''\ncommon_cols = common_cols[::3]\n\n#将df_train的common_cols中的列添加到df_train_for_matching并将label置为1\ndf_train_for_matching = df_train[common_cols].copy()\ndf_train_for_matching['target'] = 1\n#将df_test的common_cols中的列添加到df_test_for_matching并将label置为0\ndf_test_for_matching2 = df_test[common_cols].copy()\ndf_test_for_matching2['target'] = 0\n\n#将df_train_for_matching和df_test_for_matching2合并\ndf_for_matching = pd.concat([df_train_for_matching, df_test_for_matching2], axis=0)\n#将df_for_matching的index重置\ndf_for_matching.reset_index(drop=True, inplace=True)\n#打乱df_for_matching的顺序\ndf_for_matching = df_for_matching.sample(frac=1).reset_index(drop=True)\n\n#分离df_for_matching的特征和标签\nX_for_matching = df_for_matching.drop(columns=['target'])\ny_for_matching = df_for_matching['target']\n\n#删除df_train_for_matching和df_test_for_matching2\ndel df_train_for_matching, df_test_for_matching2, df_train\ngc.collect()\n\n#输出X_for_matching的信息\nprint(f'X_for_matching shape: {X_for_matching.shape}')\nprint(f'y_for_matching shape: {y_for_matching.shape}')\n'''","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:33.985127Z","iopub.status.busy":"2024-04-17T08:36:33.984694Z","iopub.status.idle":"2024-04-17T08:36:34.181537Z","shell.execute_reply":"2024-04-17T08:36:34.180144Z"},"papermill":{"duration":0.219728,"end_time":"2024-04-17T08:36:34.183899","exception":false,"start_time":"2024-04-17T08:36:33.964171","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n'''\n#创建一个lgb模型来训练X_for_matching和y_for_matching\nparams_for_matching = {\n    'boosting_type': 'gbdt',\n    'objective': 'binary',\n    'metric': 'auc',\n    'max_depth': 10,\n    'learning_rate': 0.05,\n    'n_estimators': 2000+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,#True > False\n    'num_leaves': 64,\n    'device': device,\n    'verbose': -1,\n    'early_stopping_rounds': None,  # 不使用early stop\n}\nif DRY_RUN:\n    params_for_matching[\"n_estimators\"] = 200\n\n#只训练一个fold\nmodel_for_matching = lgb.LGBMClassifier(**params_for_matching)\n\nX_for_matching.fillna(0, inplace=True)\nmodel_for_matching.fit(X_for_matching, y_for_matching)\n\n#删除X_for_matching和y_for_matching\ndel X_for_matching, y_for_matching\ngc.collect()\n'''","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:34.211098Z","iopub.status.busy":"2024-04-17T08:36:34.210432Z","iopub.status.idle":"2024-04-17T08:36:34.671223Z","shell.execute_reply":"2024-04-17T08:36:34.670167Z"},"papermill":{"duration":0.477242,"end_time":"2024-04-17T08:36:34.673514","exception":false,"start_time":"2024-04-17T08:36:34.196272","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#使用模型model_for_matching找到df_train和df_test中最相似的行\ndef stability_predict(df_test,cols,ma_model):\n    df_test_for_matching = df_test[cols]\n    df_test_for_matching.fillna(0, inplace=True)\n    y_pred = ma_model.predict_proba(df_test_for_matching)[:, 1]\n    \n    df_test['matched'] = False\n    df_test['score'] = 0.0\n    df_test['WEEK_NUM'] = 0\n    df_test['diff_sum'] = 0.0\n    \n    #当阈值大于0.25时，认为是df_train中的行\n    df_test['diff_sum'] = y_pred\n    df_test['diff_sum'].fillna(0,inplace=True)\n    df_test['matched'] = df_test['diff_sum'] > 0.5 #0.6 -> 0.5\n    #将pred大于0.25的值置为0.02,否则置为0\n    df_test['score'] = 1 - df_test['diff_sum'].astype(\"float\")\n    \n    df_test = df_test.drop(columns=[\"matched\"])\n    df_test = df_test.drop(columns=[\"diff_sum\"])\n    df_test = df_test.drop(columns=[\"WEEK_NUM\"])\n    score_delta = df_test['score']\n    df_test = df_test.drop(columns=[\"score\"])\n\n    return score_delta\n","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:34.701194Z","iopub.status.busy":"2024-04-17T08:36:34.700865Z","iopub.status.idle":"2024-04-17T08:36:34.707738Z","shell.execute_reply":"2024-04-17T08:36:34.706747Z"},"papermill":{"duration":0.023024,"end_time":"2024-04-17T08:36:34.709832","exception":false,"start_time":"2024-04-17T08:36:34.686808","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def stability_train(df_train,df_test,cols,n_estimators=4000):\n    model_for_matching = None\n    \n    #将df_train的common_cols中的列添加到df_train_for_matching并将label置为1\n    df_train_for_matching = df_train[cols].copy()\n    df_train_for_matching['target'] = 1\n    #将df_test的common_cols中的列添加到df_test_for_matching并将label置为0\n    df_test_for_matching2 = df_test[cols].copy()\n    df_test_for_matching2['target'] = 0\n\n    #将df_train_for_matching和df_test_for_matching2合并\n    df_for_matching = pd.concat([df_train_for_matching, df_test_for_matching2], axis=0)\n    #将df_for_matching的index重置\n    df_for_matching.reset_index(drop=True, inplace=True)\n    #打乱df_for_matching的顺序\n    df_for_matching = df_for_matching.sample(frac=1).reset_index(drop=True)\n\n    #分离df_for_matching的特征和标签\n    X_for_matching = df_for_matching.drop(columns=['target'])\n    y_for_matching = df_for_matching['target']\n\n    #删除df_train_for_matching和df_test_for_matching2\n    del df_train_for_matching, df_test_for_matching2\n    gc.collect()\n\n    #输出X_for_matching的信息\n    print(f'X_for_matching shape: {X_for_matching.shape}')\n    print(f'y_for_matching shape: {y_for_matching.shape}')\n\n    #创建一个lgb模型来训练X_for_matching和y_for_matching\n    params_for_matching = {\n        'boosting_type': 'gbdt',\n        'objective': 'binary',\n        'metric': 'auc',\n        'max_depth': 10,\n        'learning_rate': 0.05,\n        'n_estimators': n_estimators,\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,#True > False\n        'num_leaves': 64,\n        'device': device,\n        'verbose': -1,\n        'early_stopping_rounds': None,  # 不使用early stop\n    }\n    if DRY_RUN:\n        params_for_matching[\"n_estimators\"] = 200\n\n    #只训练一个fold\n    model_for_matching = lgb.LGBMClassifier(**params_for_matching)\n\n    X_for_matching.fillna(0, inplace=True)\n    model_for_matching.fit(X_for_matching, y_for_matching)\n\n    #删除X_for_matching和y_for_matching\n    del X_for_matching, y_for_matching\n    gc.collect()\n    return model_for_matching","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_stability(cols,n_estimators=4000):\n    print('stability start')\n    print('cols count:',len(cols))\n    print('first 10 cols:',cols[:10])\n    print('last 10 cols:',cols[10:])\n    print('train start')\n    model_for_matching = stability_train(df_train,df_test,cols,n_estimators)\n    print('train end')\n    print('predict start')\n    score_delta = stability_predict(df_test,cols,model_for_matching)\n    print('predict end')\n    print('stability end')\n    return score_delta","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submision","metadata":{"papermill":{"duration":0.012183,"end_time":"2024-04-17T08:36:34.73471","exception":false,"start_time":"2024-04-17T08:36:34.722527","status":"completed"},"tags":[]}},{"cell_type":"code","source":"%%time\nif DRY_RUN:\n    '''\n    cols_to_append = df_train[common_cols].head(10)\n    df2_columns = df_test.columns.tolist()\n    for col in df2_columns:\n        if col not in cols_to_append:\n            cols_to_append[col] = 0\n    df_test = pd.concat([df_test,cols_to_append[df2_columns]])\n    '''\n    pass\n    \n#if DRY_RUN:\n#    print(df_test[['score', 'matched', 'diff_sum']])\n    #df_test[\"case_id\"]=[c for c in range(len(df_test))]\n    #df_test=df_test.head(10)\ndf_test = df_test.drop(columns=[\"WEEK_NUM\"])\n#df_test = df_test.set_index(\"case_id\")\ny_pred = pd.Series(model.predict_proba(df_test)[:, 1], index=df_test.index)\ny_pred2 = pd.Series(model2.predict_proba(df_test)[:, 1], index=df_test.index)\ny_pred = y_pred * 0.5 + y_pred2 * 0.5\nif DRY_RUN:\n    print(y_pred)\nn_estimators = 4000\nprint('common_cols:\\n','\\n'.join(common_cols))\ncol12=common_cols[3::12]\nprint('common_cols[::6]:\\n','\\n'.join(common_cols[::6]))\nprint('common_cols[3::12]:\\n','\\n'.join(common_cols[3::12]))\ngood_cols = [col12[0],col12[3],col12[5],col12[6],col12[13]]+col12[8:11]+[col12[18]]\nmid_cols = [col12[11],col12[12]]\nbad_cols = [col12[1],col12[2],col12[4],col12[7],col12[14]]\nprint('good_cols\\n','\\n'.join(good_cols))\nprint('mid_cols\\n','\\n'.join(mid_cols))\nprint('bad_cols\\n','\\n'.join(bad_cols))\npickidx=-1#22\ndel_idxs = [1,8,9,10,11,18,19,30,31,32,35]\ndel_pick = 45\nif pickidx >= 0:\n    print('pickidx',pickidx)\n    print('col12[pickidx]',col12[pickidx])\n    pickcol=good_cols+mid_cols+[col12[pickidx]]\nelse:\n    pickcol = good_cols+mid_cols\ncols6 = common_cols[::6]\nn_cols6 = len(cols6)\ncols6_ext = [cols6[i] for i in range(n_cols6) if i not in del_idxs and i != del_pick]\nstability6 = get_stability(cols6_ext+pickcol,n_estimators)\n#stability3_12 = get_stability(common_cols[5::12],n_estimators)\nstability = stability6# * 0.51 + stability3_12 * 0.49\ny_pred #*= stability\ndel df_train\ngc.collect()\ndf_subm[\"score\"] = y_pred\n'''\nif DRY_RUN:\n    #print(y_pred)\n    print(df_subm)\ndf_subm.loc[df_subm['score'] < 0, 'score'] = 0\ndf_subm.to_csv(\"submission.csv\")\n#df_subm[\"score\"] += score_delta\n#df_subm.to_csv(\"old_submission.csv\")\ndf_subm\n'''","metadata":{"execution":{"iopub.execute_input":"2024-04-17T08:36:34.762306Z","iopub.status.busy":"2024-04-17T08:36:34.761481Z","iopub.status.idle":"2024-04-17T08:36:35.13793Z","shell.execute_reply":"2024-04-17T08:36:35.136864Z"},"papermill":{"duration":0.392816,"end_time":"2024-04-17T08:36:35.140343","exception":false,"start_time":"2024-04-17T08:36:34.747527","status":"completed"},"tags":[]},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#condition = df_subm[\"WEEK_NUM\"] >= (df_subm[\"WEEK_NUM\"].max() - df_subm[\"WEEK_NUM\"].min())/2+df_subm[\"WEEK_NUM\"].min()\n#df_subm.loc[condition, 'score'] = (df_subm.loc[condition, 'score'] - 0.029).clip(0)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"week_nums = df_subm[\"WEEK_NUM\"]\nmax_week_num = week_nums.max()\nmin_week_num = week_nums.min()\nmid_week_num = (max_week_num - min_week_num) / 2 + min_week_num\nmid2_week_num = (max_week_num - mid_week_num) / 2 + mid_week_num\noffset_base = 0.029\noffset_part3 = offset_base\noffset_part4 = offset_base + 0.001\n\ncondition3 = (df_subm[\"WEEK_NUM\"] >= mid_week_num) & (df_subm[\"WEEK_NUM\"] < mid2_week_num)\ncondition4 = df_subm[\"WEEK_NUM\"] >= mid2_week_num\n\ndf_subm.loc[condition3, 'score'] = (df_subm.loc[condition3, 'score'] - offset_part3).clip(0)\ndf_subm.loc[condition4, 'score'] = (df_subm.loc[condition4, 'score'] - offset_part4).clip(0)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm[\"score\"] *= stability ** 0.7","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm = df_subm.drop(columns=[\"WEEK_NUM\"])\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{},"execution_count":null,"outputs":[]}]}