{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":84896,"databundleVersionId":10305135,"sourceType":"competition"}],"dockerImageVersionId":31153,"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":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ================================================================\n# 🚀 Insurance Premium Prediction – RMSE Optimized (Ensemble Model)\n# ================================================================\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import KFold\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.impute import SimpleImputer\n\nfrom lightgbm import LGBMRegressor\nfrom xgboost import XGBRegressor\nfrom catboost import CatBoostRegressor\n\n# ================================================================\n# 1️⃣ Load Data\n# ================================================================\ntrain = pd.read_csv(\"/kaggle/input/playground-series-s4e12/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/playground-series-s4e12/test.csv\")\n\nprint(f\"✅ Train shape: {train.shape}\")\nprint(f\"✅ Test shape: {test.shape}\")\n\nTARGET = \"Premium Amount\"  # adjust if different in your dataset\ny = train[TARGET]\nX = train.drop(columns=[TARGET])\n\n# Identify categorical/numeric features\ncat_cols = X.select_dtypes(include=['object']).columns.tolist()\nnum_cols = X.select_dtypes(include=['int64', 'float64']).columns.tolist()\n\nprint(f\"🧠 Categorical: {len(cat_cols)} | Numerical: {len(num_cols)}\")\n\n# ================================================================\n# 2️⃣ Preprocessing\n# ================================================================\nenc = OrdinalEncoder(handle_unknown='use_encoded_value', unknown_value=-1)\nX[cat_cols] = enc.fit_transform(X[cat_cols].astype(str))\ntest[cat_cols] = enc.transform(test[cat_cols].astype(str))\n\nimp = SimpleImputer(strategy='median')\nX[num_cols] = imp.fit_transform(X[num_cols])\ntest[num_cols] = imp.transform(test[num_cols])\n\n# ================================================================\n# 3️⃣ Models\n# ================================================================\nmodels = {\n    \"LightGBM\": LGBMRegressor(\n        n_estimators=500,\n        learning_rate=0.05,\n        max_depth=10,\n        num_leaves=64,\n        subsample=0.8,\n        colsample_bytree=0.8,\n        random_state=42\n    ),\n    \"XGBoost\": XGBRegressor(\n        n_estimators=500,\n        learning_rate=0.05,\n        max_depth=10,\n        subsample=0.8,\n        colsample_bytree=0.8,\n        random_state=42\n    ),\n    \"CatBoost\": CatBoostRegressor(\n        iterations=500,\n        learning_rate=0.05,\n        depth=10,\n        verbose=0,\n        random_state=42\n    )\n}\n\n# ================================================================\n# 4️⃣ Cross-Validation + Ensemble\n# ================================================================\nkf = KFold(n_splits=5, shuffle=True, random_state=42)\noof_preds = np.zeros(len(X))\ntest_preds = np.zeros(len(test))\n\nfor fold, (train_idx, val_idx) in enumerate(kf.split(X)):\n    print(f\"\\n📂 Fold {fold+1}\")\n    X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n    y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n\n    fold_preds = np.zeros(len(X_val))\n    fold_test = np.zeros(len(test))\n\n    for name, model in models.items():\n        model.fit(X_train, y_train)\n        val_pred = model.predict(X_val)\n        test_pred = model.predict(test)\n\n        fold_preds += val_pred / len(models)\n        fold_test += test_pred / len(models)\n\n    oof_preds[val_idx] = fold_preds\n    test_preds += fold_test / kf.n_splits\n\nrmse = np.sqrt(mean_squared_error(y, oof_preds))\nprint(f\"\\n🏆 Final Cross-Validated RMSE: {rmse:.4f}\")\n\n# ================================================================\n# 5️⃣ Graph: Actual vs Predicted\n# ================================================================\nplt.figure(figsize=(8, 6))\nsns.scatterplot(x=y, y=oof_preds, alpha=0.3)\nplt.plot([y.min(), y.max()], [y.min(), y.max()], color='red', linestyle='--', label='Perfect Fit')\nplt.xlabel(\"Actual Premium Amount\")\nplt.ylabel(\"Predicted Premium Amount\")\nplt.title(\"Actual vs Predicted Premium Amount (Ensemble Model)\")\nplt.legend()\nplt.show()\n\n# ================================================================\n# 6️⃣ Create Submission\n# ================================================================\nsubmission = pd.DataFrame({\n    \"id\": test[\"id\"],\n    \"Premium Amount\": test_preds\n})\nsubmission.to_csv(\"/kaggle/working/submission.csv\", index=False)\nprint(\"✅ submission.csv created successfully!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-14T15:49:17.912401Z","iopub.execute_input":"2025-10-14T15:49:17.912771Z","iopub.status.idle":"2025-10-14T16:06:25.029556Z","shell.execute_reply.started":"2025-10-14T15:49:17.912746Z","shell.execute_reply":"2025-10-14T16:06:25.028613Z"}},"outputs":[],"execution_count":null}]}