{"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":"none","dataSources":[{"sourceId":50160,"databundleVersionId":7921029,"sourceType":"competition"},{"sourceId":8056043,"sourceType":"datasetVersion","datasetId":4751438},{"sourceId":8056897,"sourceType":"datasetVersion","datasetId":4752070},{"sourceId":8063268,"sourceType":"datasetVersion","datasetId":4756691}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"f5a73d9a-d411-44b1-8693-3dde670e2a5b","_cell_guid":"c07d6b55-2cfb-4a63-8c20-e8c039e3c6f5","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-16T10:38:49.69082Z","iopub.execute_input":"2024-04-16T10:38:49.69183Z","iopub.status.idle":"2024-04-16T10:38:49.74617Z","shell.execute_reply.started":"2024-04-16T10:38:49.691789Z","shell.execute_reply":"2024-04-16T10:38:49.744781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport os\n\n# Directory containing CSV files to merge\ndirectory = '/kaggle/input/trainbase'\n\n# List to hold DataFrame objects\ndfs = []\n\n# Loop through each file in the directory\nfor dirname, _, filenames in os.walk(directory):\n    for filename in filenames:\n        if filename.endswith('.csv'):\n            # Read CSV file into a DataFrame\n            file_path = os.path.join(dirname, filename)\n            df = pd.read_csv(file_path)\n            \n            # Add DataFrame to the list\n            dfs.append(df)\n\n# Merge all DataFrames based on a common column\nfirst = dfs[0]  # Start with the first DataFrame\nfor df in dfs[1:]:\n    first = pd.merge(first, df, how='outer')","metadata":{"_uuid":"8868957c-4012-4fb0-86ea-b403bb5ee83c","_cell_guid":"8a071eb8-0e14-482c-849f-4599abd4d76f","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-16T06:53:21.539884Z","iopub.execute_input":"2024-04-16T06:53:21.540416Z","iopub.status.idle":"2024-04-16T06:55:53.096189Z","shell.execute_reply.started":"2024-04-16T06:53:21.540376Z","shell.execute_reply":"2024-04-16T06:55:53.092612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"al = pd.read_csv('/kaggle/input/mergej/merged_file.csv')","metadata":{"_uuid":"97ddf8ac-d484-43b1-b1b6-5434ca7a3ef6","_cell_guid":"ad5a166e-b5f6-4722-9e96-35805e632d3b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-16T06:57:49.822814Z","iopub.execute_input":"2024-04-16T06:57:49.823304Z","iopub.status.idle":"2024-04-16T06:59:37.269787Z","shell.execute_reply.started":"2024-04-16T06:57:49.823219Z","shell.execute_reply":"2024-04-16T06:59:37.268585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"al","metadata":{"_uuid":"1fd8ebd0-fb58-455b-b91c-b2e215d563cd","_cell_guid":"7f32bc1b-a3c9-4a11-8f0a-92c2842b49d2","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-16T08:12:23.901735Z","iopub.execute_input":"2024-04-16T08:12:23.90215Z","iopub.status.idle":"2024-04-16T08:12:24.237174Z","shell.execute_reply.started":"2024-04-16T08:12:23.902118Z","shell.execute_reply":"2024-04-16T08:12:24.23593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output_file = '/kaggle/working/merged_file.csv'\nfirst.to_csv(output_file, index=False)","metadata":{"_uuid":"3ade05e6-181e-4955-bc01-d6990e955f5c","_cell_guid":"de8f093d-0b90-46cd-b80c-2279b66ba3eb","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2024-04-16T06:59:45.989272Z","iopub.execute_input":"2024-04-16T06:59:45.989676Z","iopub.status.idle":"2024-04-16T06:59:46.028672Z","shell.execute_reply.started":"2024-04-16T06:59:45.989645Z","shell.execute_reply":"2024-04-16T06:59:46.02702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"new = al.drop(['MONTH','date_decision'], axis=1, inplace=False)\nnew\n","metadata":{"execution":{"iopub.status.busy":"2024-04-16T08:12:29.076843Z","iopub.execute_input":"2024-04-16T08:12:29.077259Z","iopub.status.idle":"2024-04-16T08:12:30.212587Z","shell.execute_reply.started":"2024-04-16T08:12:29.077225Z","shell.execute_reply":"2024-04-16T08:12:30.21128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"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\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\n\nfrom sklearn.impute import KNNImputer\ny = new[\"target\"]\nweeks = new[\"WEEK_NUM\"]\ndf_train= new.drop(columns=[\"target\", \"case_id\", \"WEEK_NUM\"])\n# df_train, y = SMOTE().fit_resample(df_train, y)\ncv = StratifiedGroupKFold(n_splits=5, shuffle=False)\n\n","metadata":{"execution":{"iopub.status.busy":"2024-04-16T08:12:36.507965Z","iopub.execute_input":"2024-04-16T08:12:36.508378Z","iopub.status.idle":"2024-04-16T08:12:37.246286Z","shell.execute_reply.started":"2024-04-16T08:12:36.508346Z","shell.execute_reply":"2024-04-16T08:12:37.245183Z"},"trusted":true},"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    'categorical_feature ': 'auto',\n    \"verbose\": -1,\n}\n\nfitted_models = []\ncv_scores = []\n\n\nfor idx_train, idx_valid in cv.split(df_train, y, groups=weeks):#   Because it takes a long time to divide the data set, \n    X_train, y_train = df_train.iloc[idx_train], y.iloc[idx_train]# each time the data set is divided, two models are trained to each other twice, which saves time.\n    X_valid, y_valid = df_train.iloc[idx_valid], y.iloc[idx_valid]\n    model = lgb.LGBMClassifier(**params)\n    model.fit(\n        X_train, y_train,\n        eval_set = [(X_valid, y_valid)],\n        callbacks = [lgb.early_stopping(100)] )\n    fitted_models.append(model)\n    y_pred_valid = model.predict_proba(X_valid)[:,1]\n    auc_score = roc_auc_score(y_valid, y_pred_valid)\n    cv_scores.append(auc_score)\n    del model, auc_score, y_pred_valid\n    gc.collect()\n    \nprint(\"CV AUC scores: \", cv_scores)\nprint(\"Maximum CV AUC score: \", max(cv_scores))","metadata":{"execution":{"iopub.status.busy":"2024-04-16T08:12:42.04513Z","iopub.execute_input":"2024-04-16T08:12:42.045543Z","iopub.status.idle":"2024-04-16T10:28:32.321825Z","shell.execute_reply.started":"2024-04-16T08:12:42.045513Z","shell.execute_reply":"2024-04-16T10:28:32.320117Z"},"trusted":true},"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        y_preds = [estimator.predict_proba(X) for estimator in self.estimators]\n        return np.mean(y_preds, axis=0)\n\nmodel = VotingModel(fitted_models)","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:33:44.794852Z","iopub.execute_input":"2024-04-16T10:33:44.795415Z","iopub.status.idle":"2024-04-16T10:33:44.807578Z","shell.execute_reply.started":"2024-04-16T10:33:44.795376Z","shell.execute_reply":"2024-04-16T10:33:44.806135Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lgb.plot_importance(fitted_models[2], importance_type=\"split\", figsize=(10,50))\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:33:49.162658Z","iopub.execute_input":"2024-04-16T10:33:49.163138Z","iopub.status.idle":"2024-04-16T10:33:51.683268Z","shell.execute_reply.started":"2024-04-16T10:33:49.163098Z","shell.execute_reply":"2024-04-16T10:33:51.682269Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nfeatures = X_train.columns\nimportances = fitted_models[2].feature_importances_\nfeature_importance = pd.DataFrame({'importance':importances,'features':features}).sort_values('importance', ascending=False).reset_index(drop=True)\nfeature_importance\n\ndrop_list = []\nfor i, f in feature_importance.iterrows():\n    if f['importance']<80:\n        drop_list.append(f['features'])\nprint(f\"Number of features which are not important: {len(drop_list)} \")\n\nprint(drop_list)","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:34:59.95635Z","iopub.execute_input":"2024-04-16T10:34:59.956807Z","iopub.status.idle":"2024-04-16T10:34:59.984038Z","shell.execute_reply.started":"2024-04-16T10:34:59.95677Z","shell.execute_reply":"2024-04-16T10:34:59.982599Z"},"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='cpu'\n#n_samples=200000\nDRY_RUN = True if sample.shape[0] == 10 else False   \nif DRY_RUN:\n    device='cpu'\n    df_train = df_train.iloc[:1000000]\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:39:44.054316Z","iopub.execute_input":"2024-04-16T10:39:44.05481Z","iopub.status.idle":"2024-04-16T10:39:44.072716Z","shell.execute_reply.started":"2024-04-16T10:39:44.054772Z","shell.execute_reply":"2024-04-16T10:39:44.071289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_file(path, depth=None):\n    df = pl.read_parquet(path)\n    df = df.pipe(Pipeline.set_table_dtypes)\n    if depth in [1,2]:\n        df = df.group_by(\"case_id\").agg(Aggregator.get_exprs(df)) \n    return df\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","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:06.006882Z","iopub.execute_input":"2024-04-16T10:55:06.007627Z","iopub.status.idle":"2024-04-16T10:55:06.016097Z","shell.execute_reply.started":"2024-04-16T10:55:06.00759Z","shell.execute_reply":"2024-04-16T10:55:06.015074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Pipeline:\n\n    def set_table_dtypes(df):\n        for col in df.columns:\n            if col in [\"case_id\", \"WEEK_NUM\", \"num_group1\", \"num_group2\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Int64))\n            elif col in [\"date_decision\"]:\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n            elif col[-1] in (\"P\", \"A\"):\n                df = df.with_columns(pl.col(col).cast(pl.Float64))\n            elif col[-1] in (\"M\",):\n                df = df.with_columns(pl.col(col).cast(pl.String))\n            elif col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col).cast(pl.Date))\n        return df\n\n    def handle_dates(df):\n        for col in df.columns:\n            if col[-1] in (\"D\",):\n                df = df.with_columns(pl.col(col) - pl.col(\"date_decision\"))  #!!?\n                df = df.with_columns(pl.col(col).dt.total_days()) # t - t-1\n        df = df.drop(\"date_decision\", \"MONTH\")\n        return df\n\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.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                if (freq == 1) | (freq > 200):\n                    df = df.drop(col)\n        \n        return df","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:08.749334Z","iopub.execute_input":"2024-04-16T10:55:08.749732Z","iopub.status.idle":"2024-04-16T10:55:08.765277Z","shell.execute_reply.started":"2024-04-16T10:55:08.749703Z","shell.execute_reply":"2024-04-16T10:55:08.763725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class 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        expr_var = [pl.var(col).alias(f\"var_{col}\") for col in cols]\n\n        return expr_max +expr_last+expr_mean+expr_var\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","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:10.842812Z","iopub.execute_input":"2024-04-16T10:55:10.843279Z","iopub.status.idle":"2024-04-16T10:55:10.863559Z","shell.execute_reply.started":"2024-04-16T10:55:10.843193Z","shell.execute_reply":"2024-04-16T10:55:10.86225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def feature_eng(df_base, depth_0, depth_1, depth_2):\n    df_base = (\n        df_base\n        .with_columns(\n            month_decision = pl.col(\"date_decision\").dt.month(),\n            weekday_decision = pl.col(\"date_decision\").dt.weekday(),\n        )\n    )\n    for i, df in enumerate(depth_0 + depth_1 + depth_2):\n        df_base = df_base.join(df, how=\"left\", on=\"case_id\", suffix=f\"_{i}\")\n    df_base = df_base.pipe(Pipeline.handle_dates)\n    return df_base","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:14.368865Z","iopub.execute_input":"2024-04-16T10:55:14.369761Z","iopub.status.idle":"2024-04-16T10:55:14.377744Z","shell.execute_reply.started":"2024-04-16T10:55:14.369718Z","shell.execute_reply":"2024-04-16T10:55:14.376394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-04-16T10:55:16.808409Z","iopub.execute_input":"2024-04-16T10:55:16.808828Z","iopub.status.idle":"2024-04-16T10:55:16.815792Z","shell.execute_reply.started":"2024-04-16T10:55:16.808796Z","shell.execute_reply":"2024-04-16T10:55:16.814534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_mem_usage(df):\n    \"\"\" iterate through all the columns of a dataframe and modify the data type\n        to reduce memory usage.        \n    \"\"\"\n    start_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage of dataframe is {:.2f} MB'.format(start_mem))\n    \n    for col in df.columns:\n        col_type = df[col].dtype\n        if str(col_type)==\"category\":\n            continue\n        \n        if col_type != object:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)\n        else:\n            continue\n    end_mem = df.memory_usage().sum() / 1024**2\n    print('Memory usage after optimization is: {:.2f} MB'.format(end_mem))\n    print('Decreased by {:.1f}%'.format(100 * (start_mem - end_mem) / start_mem))\n    \n    return df","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:19.213634Z","iopub.execute_input":"2024-04-16T10:55:19.214069Z","iopub.status.idle":"2024-04-16T10:55:19.23146Z","shell.execute_reply.started":"2024-04-16T10:55:19.214022Z","shell.execute_reply":"2024-04-16T10:55:19.230064Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def reduce_group(grps, df):\n    use = []\n    for g in grps:\n        mx = 0; vx = g[0]\n        for gg in g:\n            n = df[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","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:21.42607Z","iopub.execute_input":"2024-04-16T10:55:21.426538Z","iopub.status.idle":"2024-04-16T10:55:21.437419Z","shell.execute_reply.started":"2024-04-16T10:55:21.426498Z","shell.execute_reply":"2024-04-16T10:55:21.435899Z"},"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-04-16T10:55:24.67006Z","iopub.execute_input":"2024-04-16T10:55:24.670467Z","iopub.status.idle":"2024-04-16T10:55:24.676553Z","shell.execute_reply.started":"2024-04-16T10:55:24.670435Z","shell.execute_reply":"2024-04-16T10:55:24.675293Z"},"trusted":true},"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}\ndf_test = feature_eng(**data_store)\nprint(\"test data shape:\\t\", df_test.shape)\ndel data_store\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:27.598231Z","iopub.execute_input":"2024-04-16T10:55:27.598637Z","iopub.status.idle":"2024-04-16T10:55:28.100343Z","shell.execute_reply.started":"2024-04-16T10:55:27.598607Z","shell.execute_reply":"2024-04-16T10:55:28.098741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# cnt_encoding_cols = df_test.select(pl.selectors.by_dtype([pl.String, pl.Boolean, pl.Categorical])).columns\n\nmappings = {}\nfor col in encoding_cols:\n    mappings[col] = df_test.group_by(col).len()\n\ndf_test_lazy = df_test.select(mappings.keys()).lazy()\n# df_test_lazy = pl.LazyFrame(df_test.select('case_id'))\n\nfor col, mapping in mappings.items():\n    remapping = {category: count for category, count in mapping.rows()}\n    remapping[None] = -2\n    expr = pl.col(col).replace(\n                remapping,\n                default=-1,\n            )\n    df_test_lazy = df_test_lazy.with_columns(expr.alias(col + '_cnt'))\n    del col, mapping, remapping\ndel mappings\ntransformed_test = df_test_lazy.collect()\n\ndf_test = pl.concat([df_test, transformed_test.select(\"^*cnt$\")], how='horizontal')\ndel transformed_test, encoding_cols","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:55:31.507288Z","iopub.execute_input":"2024-04-16T10:55:31.507698Z","iopub.status.idle":"2024-04-16T10:55:31.555095Z","shell.execute_reply.started":"2024-04-16T10:55:31.507668Z","shell.execute_reply":"2024-04-16T10:55:31.553408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.select([col for col in df_train.columns if col not in [\"target\"]])\nprint(\"train data shape:\\t\", df_train.shape)\nprint(\"test data shape:\\t\", df_test.shape)\n\nnum_cols = df_test.select(\"^*A$\").columns\n\nfor col in tqdm(num_cols, total=len(num_cols)):\n    df_test = df_test.with_columns(\n        pl.col(col).fill_null(0)\n    )\n    del col\ndf_test\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-04-16T10:54:51.164863Z","iopub.execute_input":"2024-04-16T10:54:51.165479Z","iopub.status.idle":"2024-04-16T10:54:52.028592Z","shell.execute_reply.started":"2024-04-16T10:54:51.165431Z","shell.execute_reply":"2024-04-16T10:54:52.027168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_test = df_test.drop(columns=[\"WEEK_NUM\"])\ndf_test = df_test.set_index(\"case_id\")\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\n","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:56:00.738398Z","iopub.execute_input":"2024-04-16T10:56:00.738834Z","iopub.status.idle":"2024-04-16T10:56:00.782797Z","shell.execute_reply.started":"2024-04-16T10:56:00.738802Z","shell.execute_reply":"2024-04-16T10:56:00.781264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_subm[\"score\"] = y_pred\ndf_subm.to_csv(\"submission.csv\")\ndf_subm","metadata":{"execution":{"iopub.status.busy":"2024-04-16T10:56:05.017013Z","iopub.execute_input":"2024-04-16T10:56:05.017438Z","iopub.status.idle":"2024-04-16T10:56:05.057384Z","shell.execute_reply.started":"2024-04-16T10:56:05.017406Z","shell.execute_reply":"2024-04-16T10:56:05.055539Z"},"trusted":true},"execution_count":null,"outputs":[]}]}