{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceType":"competition","sourceId":50160,"databundleVersionId":7921029,"isSourceIdPinned":false},{"sourceType":"kernelVersion","sourceId":318492194,"isSourceIdPinned":false}],"dockerImageVersionId":31329,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Home Credit LGBM Inference Only\n","metadata":{}},{"cell_type":"markdown","source":"This notebook loads saved models, processes only the test data, and writes submission.csv. It does not train models.\n","metadata":{}},{"cell_type":"code","source":"import warnings\nwarnings.simplefilter(action='ignore', category=FutureWarning)\n\nimport os\nimport gc\n\nimport re\nimport numpy as np\nimport pandas as pd\nimport polars as pl\nimport joblib\n\nfrom glob import glob\nfrom pathlib import Path\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import TimeSeriesSplit, GroupKFold, StratifiedGroupKFold\nfrom sklearn.base import BaseEstimator, RegressorMixin\nfrom sklearn.metrics import roc_auc_score\n\nimport lightgbm as lgb\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:14.556487Z","iopub.execute_input":"2026-05-11T20:00:14.556794Z","iopub.status.idle":"2026-05-11T20:00:22.357747Z","shell.execute_reply.started":"2026-05-11T20:00:14.556755Z","shell.execute_reply":"2026-05-11T20:00:22.357088Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Locate saved model artifacts from a Kaggle Notebook Output or Dataset input.\n# The training notebook saves these files under /kaggle/working/models.\nMODEL_INPUT_DIR = None\nfor candidate in Path(\"/kaggle/input\").glob(\"**/lgb_models.pkl\"):\n    MODEL_INPUT_DIR = candidate.parent\n    break\n\nif MODEL_INPUT_DIR is None:\n    raise FileNotFoundError(\n        \"Could not find lgb_models.pkl under /kaggle/input. \"\n        \"Add the training notebook Output or a dataset containing the saved models as an input.\"\n    )\n\nfitted_models = joblib.load(MODEL_INPUT_DIR / \"lgb_models.pkl\")\nmodel_metadata = joblib.load(MODEL_INPUT_DIR / \"model_metadata.pkl\")\nfeature_names = model_metadata[\"feature_names\"]\ncat_cols = model_metadata[\"cat_cols\"]\n\nprint(\"Loaded model artifacts from:\", MODEL_INPUT_DIR)\nprint(\"Models:\", len(fitted_models))\nprint(\"Features:\", len(feature_names))\nprint(\"Categorical columns:\", len(cat_cols))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:22.359074Z","iopub.execute_input":"2026-05-11T20:00:22.359756Z","iopub.status.idle":"2026-05-11T20:00:23.144264Z","shell.execute_reply.started":"2026-05-11T20:00:22.359729Z","shell.execute_reply":"2026-05-11T20:00:23.143643Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Feature Pipeline\n","metadata":{}},{"cell_type":"code","source":"class DataPrep:\n\n    # Special columns:\n    # case_id - This is the unique identifier for each credit case. You'll need this ID to join relevant tables to the base table.\n    # date_decision - This refers to the date when a decision was made regarding the approval of the loan.\n    # WEEK_NUM - This is the week number used for aggregation. In the test sample, WEEK_NUM continues sequentially from the last training value of WEEK_NUM.\n    # MONTH - This column represents the month and is intended for aggregation purposes.\n    # target - This is the target value, determined after a certain period based on whether or not the client defaulted on the specific credit case (loan).\n    # num_group1 - This is an indexing column used for the historical records of case_id in both depth=1 and depth=2 tables.\n    # num_group2 - This is the second indexing column for depth=2 tables' historical records of case_id. The order of num_group1 and num_group2 is important and will be clarified in feature definitions.\n    # All other raw columns in the tables serve as predictors. Their definitions can be found in the file feature_definitions.csv. For depth=0 tables, predictors can be directly used as features. However, for tables with depth>0, you may need to employ aggregation functions that will condense the historical records associated with each case_id into a single feature. In case num_group1 or num_group2 stands for person index (this is clear with predictor definitions) the zero index has special meaning. When num_groupN=0 it is the applicant (the person who applied for a loan).\n    \n    # Various predictors were transformed, therefore we have the following notation for similar groups of transformations\n    # P - Transform DPD (Days past due)\n    # M - Masking categories\n    # A - Transform amount\n    # D - Transform date\n    # T - Unspecified Transform\n    # L - Unspecified Transform\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.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    # Handle dates\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.drop(\"date_decision\", \"MONTH\")\n\n        return df\n\n    # Filter columns\n    # If the column name is not in the reserved list and the null value ratio of the column is greater than 0.95, then delete the column.\n    # If the column name is not in the reserved list, the column data type is String, and the number of unique values is 1 or greater than 200, then delete the column.\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:\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\n                if (freq == 1) | (freq > 50):\n                    df = df.drop(col)\n\n        return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.145232Z","iopub.execute_input":"2026-05-11T20:00:23.145495Z","iopub.status.idle":"2026-05-11T20:00:23.154812Z","shell.execute_reply.started":"2026-05-11T20:00:23.145474Z","shell.execute_reply":"2026-05-11T20:00:23.153978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Aggregator:\n    # Generate maximum aggregate expression for numeric columns\n    @staticmethod\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        [pl.min(col).alias(f\"min_{col}\") for col in cols]+ \\\n        [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return expr_max\n\n    # Generate maximum aggregate expression for date type columns\n    @staticmethod \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        return expr_max+expr_min\n\n    # Generate a maximum aggregate expression for a column of type string\n    @staticmethod\n    def str_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"M\",)]\n        expr_first = [pl.first(col).alias(f\"first_{col}\") for col in cols]\n        expr_last = [pl.last(col).alias(f\"last_{col}\") for col in cols]\n        return expr_first+expr_last\n\n\n    # Generate maximum aggregate expressions for columns of other types\n    @staticmethod\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_mean = [pl.mean(col).alias(f\"mean_{col}\") for col in cols]\n        return expr_max+expr_min+expr_mean\n\n\n    # Generate the maximum aggregate expression for a specific column \"num_group\"\n    @staticmethod\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        return expr_max\n\n\n    # Get all types of aggregate expressions\n    @staticmethod\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        return exprs","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.155881Z","iopub.execute_input":"2026-05-11T20:00:23.156216Z","iopub.status.idle":"2026-05-11T20:00:23.179186Z","shell.execute_reply.started":"2026-05-11T20:00:23.156181Z","shell.execute_reply":"2026-05-11T20:00:23.178467Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Read a single file and preprocess it\ndef read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(DataPrep.set_table_dtypes)\n    # If the depth parameter is 1 or 2, the data is aggregated by \"case_id\"\n    if depth in [1, 2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df))\n    return df","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.179981Z","iopub.execute_input":"2026-05-11T20:00:23.180274Z","iopub.status.idle":"2026-05-11T20:00:23.194620Z","shell.execute_reply.started":"2026-05-11T20:00:23.180241Z","shell.execute_reply":"2026-05-11T20:00:23.193753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Read multiple files and preprocess them\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(DataPrep.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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.195452Z","iopub.execute_input":"2026-05-11T20:00:23.195742Z","iopub.status.idle":"2026-05-11T20:00:23.210558Z","shell.execute_reply.started":"2026-05-11T20:00:23.195721Z","shell.execute_reply":"2026-05-11T20:00:23.209745Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Feature engineering function for adding new features and merging dataframes\ndef data_preprocessing(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(DataPrep.handle_dates)\n    return df_base","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.212641Z","iopub.execute_input":"2026-05-11T20:00:23.212951Z","iopub.status.idle":"2026-05-11T20:00:23.223973Z","shell.execute_reply.started":"2026-05-11T20:00:23.212929Z","shell.execute_reply":"2026-05-11T20:00:23.223221Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def to_pandas(df_data, cat_cols=None):\n    df_data = df_data.to_pandas()\n    if cat_cols is None:\n        cat_cols = list(df_data.select_dtypes(\"object\").columns)\n    df_data[cat_cols] = df_data[cat_cols].astype(\"category\")\n    return df_data, cat_cols","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.224900Z","iopub.execute_input":"2026-05-11T20:00:23.225182Z","iopub.status.idle":"2026-05-11T20:00:23.234953Z","shell.execute_reply.started":"2026-05-11T20:00:23.225154Z","shell.execute_reply":"2026-05-11T20:00:23.234233Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ROOT = Path(\"/kaggle/input/competitions/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR = ROOT / \"parquet_files\" / \"train\"\nTEST_DIR = ROOT / \"parquet_files\" / \"test\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.235810Z","iopub.execute_input":"2026-05-11T20:00:23.236415Z","iopub.status.idle":"2026-05-11T20:00:23.247645Z","shell.execute_reply.started":"2026-05-11T20:00:23.236391Z","shell.execute_reply":"2026-05-11T20:00:23.246881Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Load Test Data\n","metadata":{}},{"cell_type":"code","source":"# Read all test data sets into a variable\ntest_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_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        read_files(TEST_DIR / \"test_credit_bureau_a_1_*.parquet\",1),\n    ],\n    \"depth_2\": [\n        read_file(TEST_DIR / \"test_applprev_2.parquet\", 2),\n        read_file(TEST_DIR / \"test_person_2.parquet\", 2),\n        read_files(TEST_DIR / \"test_credit_bureau_a_2_*.parquet\", 2),\n        read_file(TEST_DIR / \"test_credit_bureau_b_2.parquet\", 2),\n    ]\n}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.248540Z","iopub.execute_input":"2026-05-11T20:00:23.248938Z","iopub.status.idle":"2026-05-11T20:00:23.801854Z","shell.execute_reply.started":"2026-05-11T20:00:23.248904Z","shell.execute_reply":"2026-05-11T20:00:23.801014Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Build test features only. No train data and no model fitting in this notebook.\ndf_test = data_preprocessing(**test_data_store)\nprint(\"raw test data shape:\t\", df_test.shape)\n\ndel test_data_store\ngc.collect()\n\n# Add any missing train-time feature columns and select the exact train-time feature order.\nfor col in feature_names:\n    if col not in df_test.columns:\n        df_test = df_test.with_columns(pl.lit(None).alias(col))\n\nneeded_cols = [\"case_id\"] + feature_names\ndf_test = df_test.select(needed_cols)\nprint(\"aligned test data shape:\t\", df_test.shape)\n\n# Convert to pandas and restore categorical dtypes expected by LightGBM.\ndf_test = df_test.to_pandas()\ncase_ids = df_test[\"case_id\"]\nX_test = df_test[feature_names]\n\nfor col in cat_cols:\n    if col in X_test.columns:\n        X_test[col] = X_test[col].astype(\"category\")\n\nprint(\"X_test shape:\", X_test.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:00:23.802858Z","iopub.execute_input":"2026-05-11T20:00:23.803166Z","iopub.status.idle":"2026-05-11T20:00:24.179210Z","shell.execute_reply.started":"2026-05-11T20:00:23.803131Z","shell.execute_reply":"2026-05-11T20:00:24.178489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Align test features with trained LightGBM features\nfeature_names = fitted_models[0].feature_name_\n\nX_test = X_test.reindex(columns=feature_names)\n\n# LightGBM only accepts int / float / bool / category.\n# Some numeric columns may become object after Polars concat/join, so convert them back.\nobject_cols = X_test.select_dtypes(include=[\"object\", \"string\"]).columns.tolist()\n\nprint(\"Object/string columns before fix:\", len(object_cols))\n\nfor col in object_cols:\n    X_test[col] = pd.to_numeric(X_test[col], errors=\"coerce\")\n\nX_test = X_test.replace([np.inf, -np.inf], np.nan)\n\nbad_cols_after = X_test.select_dtypes(include=[\"object\", \"string\"]).columns.tolist()\nprint(\"Object/string columns after fix:\", len(bad_cols_after))\n\nif bad_cols_after:\n    print(bad_cols_after[:50])\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:04:13.402664Z","iopub.execute_input":"2026-05-11T20:04:13.403554Z","iopub.status.idle":"2026-05-11T20:04:13.569744Z","shell.execute_reply.started":"2026-05-11T20:04:13.403478Z","shell.execute_reply":"2026-05-11T20:04:13.568936Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Prediction\n","metadata":{}},{"cell_type":"code","source":"# Predict in batches to keep memory lower on hidden test.\ndef predict_lgbm_in_batches(models, data, batch_size=200_000):\n    preds = np.zeros(len(data), dtype=np.float64)\n    n_batches = int(np.ceil(len(data) / batch_size))\n\n    for batch_idx in range(n_batches):\n        start = batch_idx * batch_size\n        end = min((batch_idx + 1) * batch_size, len(data))\n        print(f\"Processing batch {batch_idx + 1}/{n_batches}: rows {start}:{end}\")\n        X_batch = data.iloc[start:end]\n        preds[start:end] = np.mean(\n            [model.predict_proba(X_batch)[:, 1] for model in models],\n            axis=0,\n        )\n        del X_batch\n        gc.collect()\n\n    return preds\n\nlgb_pred = pd.Series(predict_lgbm_in_batches(fitted_models, X_test), index=case_ids, name=\"score\")\nprint(lgb_pred.head())\nprint(\"Prediction nulls:\", lgb_pred.isna().any())\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:04:19.250843Z","iopub.execute_input":"2026-05-11T20:04:19.251121Z","iopub.status.idle":"2026-05-11T20:04:19.658416Z","shell.execute_reply.started":"2026-05-11T20:04:19.251099Z","shell.execute_reply":"2026-05-11T20:04:19.657587Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Submission\n","metadata":{}},{"cell_type":"code","source":"df_subm = pd.read_csv(ROOT / \"sample_submission.csv\")\ndf_subm = df_subm.set_index(\"case_id\")\ndf_subm[\"score\"] = lgb_pred.reindex(df_subm.index)\n\nprint(\"Check null:\", df_subm[\"score\"].isnull().any())\ndisplay(df_subm.head())\n\ndf_subm.to_csv(\"submission.csv\")\nprint(\"Saved submission.csv\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-05-11T20:04:24.062114Z","iopub.execute_input":"2026-05-11T20:04:24.062823Z","iopub.status.idle":"2026-05-11T20:04:24.095438Z","shell.execute_reply.started":"2026-05-11T20:04:24.062790Z","shell.execute_reply":"2026-05-11T20:04:24.094577Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}