{"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-30T14:23:58.075223Z","iopub.execute_input":"2025-06-30T14:23:58.075649Z","iopub.status.idle":"2025-06-30T14:23:58.083370Z","shell.execute_reply.started":"2025-06-30T14:23:58.075601Z","shell.execute_reply":"2025-06-30T14:23:58.082269Z"}},"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-30T14:23:58.085709Z","iopub.execute_input":"2025-06-30T14:23:58.086152Z","iopub.status.idle":"2025-06-30T14:23:58.508285Z","shell.execute_reply.started":"2025-06-30T14:23:58.086114Z","shell.execute_reply":"2025-06-30T14:23:58.507260Z"}},"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-30T14:23:58.509432Z","iopub.execute_input":"2025-06-30T14:23:58.509774Z","iopub.status.idle":"2025-06-30T14:23:58.677146Z","shell.execute_reply.started":"2025-06-30T14:23:58.509745Z","shell.execute_reply":"2025-06-30T14:23:58.676133Z"}},"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_hist_trans = pd.read_csv(f\"{DATA_DIR}/historical_transactions.csv\")\n\n# new_trans扱いでマージ\nnew_trans = pd.concat([_new_trans, _hist_trans], ignore_index=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T14:23:58.678669Z","iopub.execute_input":"2025-06-30T14:23:58.679078Z","iopub.status.idle":"2025-06-30T14:26:20.749714Z","shell.execute_reply.started":"2025-06-30T14:23:58.679040Z","shell.execute_reply":"2025-06-30T14:26:20.748596Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ----------------------------------------------\n# 追加テーブルの特徴量作成\n# ----------------------------------------------\n\n# 集約特徴の作成パターンを辞書化\nnew_trans[\"authorized_flag\"] = new_trans[\"authorized_flag\"].map({\"Y\": 1, \"N\": 0})\nnew_trans[\"category_1\"] = new_trans[\"category_1\"].map({\"Y\": 1, \"N\": 0})\n\nagg_funcs = {\n    \"purchase_amount\": [\"min\", \"max\", \"mean\", \"var\", \"skew\"], # mean, var, skewを追加\n    \"installments\":    [\"min\", \"max\"],\n    \"month_lag\":       [\"min\", \"max\", \"mean\"], # meanを追加\n    \"purchase_date\":   [\"count\"],\n    \"category_1\":      [\"mean\"], # 割引対象かどうか(Y:N = 1:0)\n    \"state_id\":        [\"nunique\"], # 異なる州の数\n    \"subsector_id\":    [\"nunique\"], # 異なる業種の数\n}\n\n# 全ての行を card_id の値でグループ化\n# ⇒　上の集約パターンに従って実際に特徴を集約\nagg_new = new_trans.groupby(\"card_id\").agg(agg_funcs)\n\n# 備考）上の集約特徴のテーブルは，列が MultiIndex の状態になっている\n# 　　　⇒　列名のリストを表示して確認してみよう\nprint(agg_new.columns.to_list())\n# 1列を指定するために「変数名と集約関数」をペアで指定する必要があることがわかる\n\n# 新特徴の名前（列名）を機械的に生成してリスト化\n# 　　命名規則：元変数名_集約方法（「purchase_amount_mean」など）\nflat_cols = []\nfor 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状態の列を通常の状態に変換（列方向に平坦化）\nagg_new.columns = flat_cols\nprint(agg_new.columns.to_list())\n\n# groupby によるグループ化を解除（card_idを通常の列に戻す）\nagg_new = agg_new.reset_index()\n\n# メインテーブルの特徴と結合\ntrain_x = train_x.merge(agg_new, on=\"card_id\", how=\"left\")\ntest_x  = test_x.merge(agg_new, on=\"card_id\", how=\"left\")\n\n# Fill missing values created by the left join\ntrain_x = train_x.fillna(-1)\ntest_x  = test_x.fillna(-1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-06-30T14:27:24.726563Z","iopub.execute_input":"2025-06-30T14:27:24.726899Z","iopub.status.idle":"2025-06-30T14:27:40.212085Z","shell.execute_reply.started":"2025-06-30T14:27:24.726875Z","shell.execute_reply":"2025-06-30T14:27:40.211031Z"}},"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-30T14:27:40.213647Z","iopub.execute_input":"2025-06-30T14:27:40.214099Z","iopub.status.idle":"2025-06-30T14:27:40.232986Z","shell.execute_reply.started":"2025-06-30T14:27:40.214072Z","shell.execute_reply":"2025-06-30T14:27:40.231990Z"}},"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-30T14:27:44.222590Z","iopub.execute_input":"2025-06-30T14:27:44.222930Z","iopub.status.idle":"2025-06-30T14:27:48.082917Z","shell.execute_reply.started":"2025-06-30T14:27:44.222899Z","shell.execute_reply":"2025-06-30T14:27:48.081817Z"}},"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-30T14:27:48.083814Z","iopub.execute_input":"2025-06-30T14:27:48.084053Z","iopub.status.idle":"2025-06-30T14:27:49.739442Z","shell.execute_reply.started":"2025-06-30T14:27:48.084035Z","shell.execute_reply":"2025-06-30T14:27:49.737444Z"}},"outputs":[],"execution_count":null}]}