{"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":7575239,"sourceType":"datasetVersion","datasetId":4405300}],"dockerImageVersionId":30664,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## EDA\nThis dataset contains a large number of tables as a result of utilizing diverse data sources and the varying levels of data aggregation used while preparing the dataset.","metadata":{}},{"cell_type":"code","source":"import sys\nfrom pathlib import Path\nimport subprocess\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\nimport math\n\nimport gc\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nROOT = '/kaggle/input/home-credit-credit-risk-model-stability'","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-22T17:06:26.778509Z","iopub.execute_input":"2024-03-22T17:06:26.778998Z","iopub.status.idle":"2024-03-22T17:06:26.787292Z","shell.execute_reply.started":"2024-03-22T17:06:26.778962Z","shell.execute_reply":"2024-03-22T17:06:26.785571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Checking the size\nThe following cell is used to check the size of each dataframe for both training set and test set. \n- The largest one in training set is *credit_bureau_a_2_5* which takes 2.9G \n- *applprev_1_2, credit_bureau_a_1_4, credit_bureau_a_2_11, static_0_2* are absent in the training set, so these df should not be included while training the model.","metadata":{}},{"cell_type":"code","source":"def get_disk_usage(directory):\n    cmd = f'du {directory}/* -h | sort -rh'\n    result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True)\n    output_lines = result.stdout.split('\\n')\n    data = [line.split('\\t') for line in output_lines if line]\n    \n    df = pd.DataFrame(data, columns=['size', 'path'])\n    df['file_name'] = df.path.str.replace('train_|test_', '', regex=True).apply(lambda x: Path(x).stem)\n    return df\n\ntrain_disk_usage = get_disk_usage(f'{ROOT}/csv_files/train').reset_index()\ntest_disk_usage = get_disk_usage(f'{ROOT}/csv_files/test')\n\na = train_disk_usage.reset_index().merge(test_disk_usage, on=['file_name'],\n                                    how='outer', suffixes=['_train','_test']).sort_values(by='index').drop(columns=['index','path_train','path_test','level_0'])\ndisplay(a[:6])\ndisplay(a[-5:])","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:12.397540Z","iopub.execute_input":"2024-03-22T16:40:12.398270Z","iopub.status.idle":"2024-03-22T16:40:12.521167Z","shell.execute_reply.started":"2024-03-22T16:40:12.398223Z","shell.execute_reply":"2024-03-22T16:40:12.519594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"path_train_base = f'{ROOT}/csv_files/train/train_base.csv'\npath_test_base = f'{ROOT}/csv_files/test/test_base.csv'\n\ntrain_base = pd.read_csv(path_train_base)\ntest_base = pd.read_csv(path_test_base)\n\nprint(train_base.shape)\nprint(test_base.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:12.524151Z","iopub.execute_input":"2024-03-22T16:40:12.524622Z","iopub.status.idle":"2024-03-22T16:40:14.407755Z","shell.execute_reply.started":"2024-03-22T16:40:12.524582Z","shell.execute_reply":"2024-03-22T16:40:14.406517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Transform the 'MONTH' features into 'year' and 'month' feature","metadata":{}},{"cell_type":"code","source":"train_base['year'] = train_base['MONTH'] // 100\ntrain_base['month'] = train_base['MONTH'] % 100\ntrain_base = train_base.drop(columns=['MONTH'])\ndisplay(train_base.head(5))","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:14.411650Z","iopub.execute_input":"2024-03-22T16:40:14.412195Z","iopub.status.idle":"2024-03-22T16:40:14.540821Z","shell.execute_reply.started":"2024-03-22T16:40:14.412158Z","shell.execute_reply":"2024-03-22T16:40:14.539333Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_date_interval_info(df):\n    df['date_decision'] = pd.to_datetime(df['date_decision'])\n    date_delta = df['date_decision'].drop_duplicates().sort_values().diff()\n    len_uniq_dates = len(df.date_decision.unique())\n    print(\n        f'\\n Actual date range:  {date_delta.sum().days + 1} day(s).',\n        f'\\n Total unique dates: {len_uniq_dates} day(s).'\n    )\n\n    print(f'\\n Min date: {df.date_decision.dt.date.min()}',\n          f'\\n Max date: {df.date_decision.dt.date.max()}')\n    \nget_date_interval_info(train_base)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:14.542440Z","iopub.execute_input":"2024-03-22T16:40:14.542807Z","iopub.status.idle":"2024-03-22T16:40:16.748243Z","shell.execute_reply.started":"2024-03-22T16:40:14.542758Z","shell.execute_reply":"2024-03-22T16:40:16.747031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Target\nTarget is defined as whether or not the client defaulted on the specific credit case.\n* Highly imbalanced (should do oversampling before training the model)","metadata":{}},{"cell_type":"code","source":"sns.set_style(\"whitegrid\")\nplt.figure(figsize=(10,5))\nplt.subplot(1,2,1)\nax = sns.countplot(data=train_base, x='target', palette=\"Set2\")\nfor p in ax.patches:\n    ax.annotate(f'{int(p.get_height())}', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')\n\nplt.subplot(1,2,2)\nplt.pie(train_base['target'].value_counts(), labels=['0','1'], autopct='%1.1f%%', colors=sns.color_palette(\"Set2\"))","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:16.749287Z","iopub.execute_input":"2024-03-22T16:40:16.749605Z","iopub.status.idle":"2024-03-22T16:40:17.443319Z","shell.execute_reply.started":"2024-03-22T16:40:16.749579Z","shell.execute_reply":"2024-03-22T16:40:17.442294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,8))\nplt.subplot(2,1,1)\nsns.histplot(data=train_base, x='month', hue=\"target\", binwidth=1, multiple=\"stack\", palette=\"Set2\")\nplt.title(\"Monthly Distribution\")\n\nplt.subplot(2,1,2)\nsns.histplot(data=train_base, x='month', hue=\"target\", binwidth=1, multiple=\"stack\", palette=\"Set2\")\nplt.ylim(0,10000)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:17.445109Z","iopub.execute_input":"2024-03-22T16:40:17.445751Z","iopub.status.idle":"2024-03-22T16:40:20.587668Z","shell.execute_reply.started":"2024-03-22T16:40:17.445717Z","shell.execute_reply":"2024-03-22T16:40:20.586362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,8))\nplt.subplot(2,1,1)\nsns.histplot(data=train_base, x='WEEK_NUM', hue=\"target\", binwidth=1, kde=True, multiple=\"stack\", palette=\"Set2\")\nplt.title(\"Weekly Distribution\")\n\nplt.subplot(2,1,2)\nsns.histplot(data=train_base, x='WEEK_NUM', hue=\"target\", binwidth=1, kde=True, multiple=\"stack\", palette=\"Set2\")\nplt.ylim(0,2000)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:20.589224Z","iopub.execute_input":"2024-03-22T16:40:20.589688Z","iopub.status.idle":"2024-03-22T16:40:36.225745Z","shell.execute_reply.started":"2024-03-22T16:40:20.589643Z","shell.execute_reply":"2024-03-22T16:40:36.224463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize=(10,8))\nplt.subplot(2,1,1)\nsns.histplot(data=train_base, x='date_decision', hue=\"target\", bins=50, kde=True, multiple=\"stack\", palette=\"Set2\")\nplt.title(\"Date Distribution\")\n\nplt.subplot(2,1,2)\nsns.histplot(data=train_base, x='date_decision', hue=\"target\", bins=50, kde=True, multiple=\"stack\", palette=\"Set2\")\nplt.ylim(0,2000)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:40:36.227362Z","iopub.execute_input":"2024-03-22T16:40:36.227831Z","iopub.status.idle":"2024-03-22T16:40:52.345253Z","shell.execute_reply.started":"2024-03-22T16:40:36.227773Z","shell.execute_reply":"2024-03-22T16:40:52.344068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## More EDA coming soon...","metadata":{}},{"cell_type":"markdown","source":"### Null Values visualization","metadata":{}},{"cell_type":"code","source":"# code taking reference of: https://www.kaggle.com/code/sergiosaharovskiy/home-credit-crms-2024-eda-and-submission/notebook\n\ntrain_disk_usage = pd.read_csv('/kaggle/input/2024-home-credit-public-repo/files/train_disk_usage.csv')\ntrain_disk_usage.head(3)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:14:43.522573Z","iopub.execute_input":"2024-03-22T17:14:43.526054Z","iopub.status.idle":"2024-03-22T17:14:43.589044Z","shell.execute_reply.started":"2024-03-22T17:14:43.525885Z","shell.execute_reply":"2024-03-22T17:14:43.587437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"values = train_disk_usage['isna_%'].values.tolist()\ntotal_area = train_disk_usage['height'] * train_disk_usage['width']\ntotal_area_scaled = total_area / total_area.max()\n\nrows = 4\ncols = 8\nfig, axs = plt.subplots(rows, cols, figsize=(18, 11))\n\nfor i, ax in enumerate(axs.flat):\n    \n    outer_square_side = np.sqrt(total_area_scaled[i])\n    inner_square_side = np.sqrt(total_area_scaled[i]*values[i])\n\n    # Add the small square inside the 1x1 image\n    ax.add_patch(plt.Rectangle((0.5 - outer_square_side / 2, 0.5 - outer_square_side / 2),\n                               outer_square_side, outer_square_side,\n                               color='#F03F47', label='Total Records'))\n    \n    ax.add_patch(plt.Rectangle((0.4 - inner_square_side / 2, 0.6 - inner_square_side / 2),\n                               inner_square_side, inner_square_side,\n                               color='#645F64', label='Null Values'))\n\n    ax.set_xticks([])\n    ax.set_yticks([])\n    ax.set_aspect('equal')\n    ax.set_title(f'{train_disk_usage.file_name.iloc[i]}\\n'\n                 f'{train_disk_usage[\"size\"].iloc[i]:}\\nNull_%: {values[i]*100:.2f}')\n\nplt.legend(bbox_to_anchor=(-4, -.4), loc='lower center', ncol=2)\nplt.suptitle('\\nNull values% in Train files scaled and shaped as Squares')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:16:02.107381Z","iopub.execute_input":"2024-03-22T17:16:02.109705Z"},"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":"ROOT            = Path(\"/kaggle/input/home-credit-credit-risk-model-stability\")\n\nTRAIN_DIR       = ROOT / \"parquet_files\" / \"train\"","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:47:46.696135Z","iopub.execute_input":"2024-03-22T16:47:46.696591Z","iopub.status.idle":"2024-03-22T16:47:46.703361Z","shell.execute_reply.started":"2024-03-22T16:47:46.696558Z","shell.execute_reply":"2024-03-22T16:47:46.701883Z"},"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.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","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:55:50.985001Z","iopub.execute_input":"2024-03-22T16:55:50.985437Z","iopub.status.idle":"2024-03-22T16:55:51.000905Z","shell.execute_reply.started":"2024-03-22T16:55:50.985402Z","shell.execute_reply":"2024-03-22T16:55:50.999737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Aggregator:\n    \n    def main_expr(df):\n        cols = [col for col in df.columns if col[-1] in (\"P\", \"A\", \"D\", \"M\", \"T\", \"L\")]\n        expr_max = [pl.max(col).alias(f\"max_{col}\") for col in cols]\n        return expr_max\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]  # max & replace col name\n        return expr_max\n    \n    def get_exprs(df):\n        exprs = Aggregator.main_expr(df) + \\\n                Aggregator.count_expr(df)\n        return exprs","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:55:52.749754Z","iopub.execute_input":"2024-03-22T16:55:52.750344Z","iopub.status.idle":"2024-03-22T16:55:52.762275Z","shell.execute_reply.started":"2024-03-22T16:55:52.750298Z","shell.execute_reply":"2024-03-22T16:55:52.760474Z"},"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-03-22T16:55:56.868968Z","iopub.execute_input":"2024-03-22T16:55:56.869364Z","iopub.status.idle":"2024-03-22T16:55:56.878942Z","shell.execute_reply.started":"2024-03-22T16:55:56.869334Z","shell.execute_reply":"2024-03-22T16:55:56.877717Z"},"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-03-22T17:00:01.098264Z","iopub.execute_input":"2024-03-22T17:00:01.098759Z","iopub.status.idle":"2024-03-22T17:00:01.108468Z","shell.execute_reply.started":"2024-03-22T17:00:01.098724Z","shell.execute_reply":"2024-03-22T17:00:01.106875Z"},"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-03-22T17:04:10.355274Z","iopub.execute_input":"2024-03-22T17:04:10.355712Z","iopub.status.idle":"2024-03-22T17:04:10.362852Z","shell.execute_reply.started":"2024-03-22T17:04:10.355679Z","shell.execute_reply":"2024-03-22T17:04:10.361530Z"},"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    ]\n}","metadata":{"execution":{"iopub.status.busy":"2024-03-22T16:57:28.568585Z","iopub.execute_input":"2024-03-22T16:57:28.569581Z","iopub.status.idle":"2024-03-22T16:58:12.720550Z","shell.execute_reply.started":"2024-03-22T16:57:28.569541Z","shell.execute_reply":"2024-03-22T16:58:12.719594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = feature_eng(**data_store)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:00:04.097903Z","iopub.execute_input":"2024-03-22T17:00:04.098310Z","iopub.status.idle":"2024-03-22T17:00:15.529003Z","shell.execute_reply.started":"2024-03-22T17:00:04.098282Z","shell.execute_reply":"2024-03-22T17:00:15.527792Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train = df_train.pipe(Pipeline.filter_cols)\nprint(\"train data shape:\\t\", df_train.shape)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:03:52.818745Z","iopub.execute_input":"2024-03-22T17:03:52.819287Z","iopub.status.idle":"2024-03-22T17:03:55.733560Z","shell.execute_reply.started":"2024-03-22T17:03:52.819252Z","shell.execute_reply":"2024-03-22T17:03:55.732433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_train, cat_cols = to_pandas(df_train)","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:04:15.360236Z","iopub.execute_input":"2024-03-22T17:04:15.360674Z","iopub.status.idle":"2024-03-22T17:04:32.169898Z","shell.execute_reply.started":"2024-03-22T17:04:15.360640Z","shell.execute_reply":"2024-03-22T17:04:32.168944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"del data_store\ngc.collect()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:04:32.171443Z","iopub.execute_input":"2024-03-22T17:04:32.172274Z","iopub.status.idle":"2024-03-22T17:04:32.676119Z","shell.execute_reply.started":"2024-03-22T17:04:32.172241Z","shell.execute_reply":"2024-03-22T17:04:32.674875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"display(df_train.head())","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:04:42.473911Z","iopub.execute_input":"2024-03-22T17:04:42.474978Z","iopub.status.idle":"2024-03-22T17:04:42.506650Z","shell.execute_reply.started":"2024-03-22T17:04:42.474935Z","shell.execute_reply":"2024-03-22T17:04:42.505120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_list = [col for col in df_train.columns if df_train[col].dtype.name == 'category']\n\ncatfreq_dict = {}\ncatcatfreq_dict = {}\n\nfor col in cat_list:\n    catfreq_dict[col] = len(list(df_train[col].value_counts()))\n    catcatfreq_dict[col] = {}\n    for d in dict(df_train[col].value_counts()).items():\n        catcatfreq_dict[col][d[0]] = d[1]\n\ncatfreq_df = pd.DataFrame.from_dict(catfreq_dict, orient='index', columns=['Categories'])\ndisplay(catfreq_df.sort_values(by=\"Categories\", ascending=False).head())\ndisplay(catfreq_df.sort_values(by=\"Categories\", ascending=True).head())","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:05:51.872904Z","iopub.execute_input":"2024-03-22T17:05:51.873311Z","iopub.status.idle":"2024-03-22T17:05:52.931688Z","shell.execute_reply.started":"2024-03-22T17:05:51.873281Z","shell.execute_reply":"2024-03-22T17:05:52.930468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_categories = len(catcatfreq_dict)\nnum_rows = math.ceil(num_categories / 5)\nfig, axes = plt.subplots(num_rows, 5, figsize=(16, num_rows * 5), sharey=True)\n\nfor i, (category, freq_dict) in enumerate(catcatfreq_dict.items()):\n    row = i // 5\n    col = i % 5\n    sns.barplot(data=pd.DataFrame.from_dict(freq_dict, orient='index', columns=['Frequency']).reset_index(), \n                x='index', y='Frequency', ax=axes[row, col], palette='Set2')\n    axes[row, col].set_title(category)\n    ax.set_xlabel('Categories')\n    \n# Hide empty subplots\nfor i in range(num_categories, num_rows * 5):\n    row = i // 5\n    col = i % 5\n    fig.delaxes(axes[row, col])\n    \nplt.title(\"Categorical Features\")\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-03-22T17:17:02.957523Z","iopub.execute_input":"2024-03-22T17:17:02.957961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}