{"metadata":{"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.11.11"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":10445,"databundleVersionId":200747,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom xgboost import XGBRegressor\nimport matplotlib.pyplot as plt\n\nrseed = 71","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:43:36.058924Z","iopub.execute_input":"2025-06-30T12:43:36.059882Z","iopub.status.idle":"2025-06-30T12:43:36.064492Z","shell.execute_reply.started":"2025-06-30T12:43:36.059851Z","shell.execute_reply":"2025-06-30T12:43:36.063461Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------------------------------------------\n# データ読み込み\n# ----------------------------------------------\nDATA_DIR = \"/kaggle/input/elo-merchant-category-recommendation\"\ntrain = pd.read_csv(f\"{DATA_DIR}/train.csv\")\ntest  = pd.read_csv(f\"{DATA_DIR}/test.csv\")\n\n# 元テーブルからID列と目的変数をコピー\ntrain_card_id = train['card_id'].copy()\ntest_card_id  = test['card_id'].copy()\ntrain_y       = train['target'].copy()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:43:36.145047Z","iopub.execute_input":"2025-06-30T12:43:36.145366Z","iopub.status.idle":"2025-06-30T12:43:36.454028Z","shell.execute_reply.started":"2025-06-30T12:43:36.145347Z","shell.execute_reply":"2025-06-30T12:43:36.453090Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------------------------------------------\n# メインテーブルの特徴量作成\n# ・年月文字列は欠損補完・Label Encoding\n# ・他はそのまま\n# ----------------------------------------------\n\n# 元テーブルから特徴量をコピー（目的変数は削除）\ntrain_x = train.copy().drop(columns=[\"target\"])\ntest_x  = test.copy()\n\n# 年月文字列に欠損があるので補完\ntrain_x[\"first_active_month\"] = train_x[\"first_active_month\"].fillna(\"Unknown\")\ntest_x[\"first_active_month\"]  = test_x[\"first_active_month\"].fillna(\"Unknown\")\n\n# 年月文字列をLabel Encoding\nle = LabelEncoder()\nall_months = pd.concat([train_x[\"first_active_month\"], test_x[\"first_active_month\"]])\nle.fit(all_months)\ntrain_x[\"fam_label\"] = le.transform(train_x[\"first_active_month\"])\ntest_x[\"fam_label\"]  = le.transform(test_x[\"first_active_month\"])\n\n# 変換前の年月文字列を削除\ntrain_x = train_x.drop(columns=[\"first_active_month\"])\ntest_x  = test_x.drop(columns=[\"first_active_month\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:43:36.455351Z","iopub.execute_input":"2025-06-30T12:43:36.455672Z","iopub.status.idle":"2025-06-30T12:43:36.572466Z","shell.execute_reply.started":"2025-06-30T12:43:36.455628Z","shell.execute_reply":"2025-06-30T12:43:36.571521Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# # ----------------------------------------------\n# # 追加テーブルの特徴量作成\n# # ----------------------------------------------\n\n# # 追加テーブルの読み込み\n# new_trans = pd.read_csv(f\"{DATA_DIR}/new_merchant_transactions.csv\")\n# print(new_trans.describe())\n\n# # 集約特徴の作成パターンを辞書化\n# agg_funcs = {\n#     \"purchase_amount\": [\"min\", \"max\"], # 正規化済みの購入金額（負値 = 顧客の支出）\n#     \"installments\":    [\"min\", \"max\"], # 分割払いの分割回数\n#     \"month_lag\":       [\"min\", \"max\"], # 基準日からの経過月数\n#     \"purchase_date\":   [\"count\"],      # 購入日時（countで空でない行を数える ⇔ 購入回数）\n# }\n# # 例）\"month_lag\": [\"min\", \"mean\", \"max\"],\n# # 　　⇔　変数 \"month_lag\" について，同一IDの中で\n# # 　　　　最小値，平均値，最大値を取って集約特徴に追加する\n\n# # 全ての行を card_id の値でグループ化\n# # ⇒　上の集約パターンに従って実際に特徴を集約\n# agg_new = new_trans.groupby(\"card_id\").agg(agg_funcs)\n\n# # 備考）上の集約特徴のテーブルは，列が MultiIndex の状態になっている\n# # 　　　⇒　列名のリストを表示して確認してみよう\n# print(agg_new.columns.to_list())\n# # 1列を指定するために「変数名と集約関数」をペアで指定する必要があることがわかる\n\n# # 新特徴の名前（列名）を機械的に生成してリスト化\n# # 　　命名規則：元変数名_集約方法（「purchase_amount_mean」など）\n# flat_cols = []\n# for col_name, func_name in agg_new.columns.to_flat_index():\n#     new_name = f\"new_{col_name}_{func_name}\"\n#     flat_cols.append(new_name)\n\n# # MultiIndex状態の列を通常の状態に変換（列方向に平坦化）\n# agg_new.columns = flat_cols\n# print(agg_new.columns.to_list())\n\n# # groupby によるグループ化を解除（card_idを通常の列に戻す）\n# agg_new = agg_new.reset_index()\n\n# # メインテーブルの特徴と結合\n# train_x = train_x.merge(agg_new, on=\"card_id\", how=\"left\")\n# test_x  = test_x.merge(agg_new, on=\"card_id\", how=\"left\")\n\n# # Fill missing values created by the left join\n# train_x = train_x.fillna(-1)\n# test_x  = test_x.fillna(-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:43:36.573573Z","iopub.execute_input":"2025-06-30T12:43:36.573892Z","iopub.status.idle":"2025-06-30T12:43:36.580089Z","shell.execute_reply.started":"2025-06-30T12:43:36.573868Z","shell.execute_reply":"2025-06-30T12:43:36.579072Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ID列を削除\ntrain_x = train_x.drop(columns=[\"card_id\"])\ntest_x  = test_x.drop(columns=[\"card_id\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:48:05.101892Z","iopub.execute_input":"2025-06-30T12:48:05.102205Z","iopub.status.idle":"2025-06-30T12:48:05.124108Z","shell.execute_reply.started":"2025-06-30T12:48:05.102175Z","shell.execute_reply":"2025-06-30T12:48:05.123326Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------------------------------------------\n# 使用する特徴量の可視化\n# ----------------------------------------------\n\n# 各特徴の統計量\nprint(pd.concat([train_x, train_y], axis=1).describe())\n\n# 各特徴のヒストグラム\ntrain_x.hist(bins=100, color=\"blue\", grid=True, label='pandas')\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:48:05.124860Z","iopub.execute_input":"2025-06-30T12:48:05.125144Z","iopub.status.idle":"2025-06-30T12:48:10.942383Z","shell.execute_reply.started":"2025-06-30T12:48:05.125124Z","shell.execute_reply":"2025-06-30T12:48:10.941492Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ------------------------------\n# XGBoostの学習・推論・submit\n# ------------------------------\nmodel = XGBRegressor(random_state=rseed)\nmodel.fit(train_x, train_y)\npreds = model.predict(test_x)\n\nsubmission = pd.DataFrame({\n    \"card_id\": test_card_id,\n    \"target\":  preds\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:48:10.943415Z","iopub.execute_input":"2025-06-30T12:48:10.943641Z","iopub.status.idle":"2025-06-30T12:48:10.984629Z","shell.execute_reply.started":"2025-06-30T12:48:10.943623Z","shell.execute_reply":"2025-06-30T12:48:10.982999Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 特徴量重要度の表示（棒グラフ）\nimport matplotlib.pyplot as plt\nimportances = model.feature_importances_\nfeatures = train_x.columns\n\n# DataFrameでまとめて表示\nimportance_df = pd.DataFrame({\n    \"feature\": features,\n    \"importance\": importances\n}).sort_values(by=\"importance\", ascending=False)\n\nplt.figure(figsize=(10, 6))\nplt.barh(importance_df[\"feature\"][:][::-1], importance_df[\"importance\"][:][::-1])\nplt.xlabel(\"Feature Importance\")\nplt.title(\"Feature Importances from XGBoost\")\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T12:48:10.985133Z","iopub.status.idle":"2025-06-30T12:48:10.985412Z","shell.execute_reply.started":"2025-06-30T12:48:10.985285Z","shell.execute_reply":"2025-06-30T12:48:10.985297Z"}},"outputs":[],"execution_count":null}]}