{"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":false,"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,"execution":{"iopub.status.busy":"2025-10-09T05:57:43.242759Z","iopub.execute_input":"2025-10-09T05:57:43.243061Z","iopub.status.idle":"2025-10-09T05:57:45.636164Z","shell.execute_reply.started":"2025-10-09T05:57:43.243028Z","shell.execute_reply":"2025-10-09T05:57:45.635256Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# -------------------------\n# Kaggle: Playground Series S4E12 - Insurance Premium Prediction (with Visualization)\n# -------------------------\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.compose import ColumnTransformer\nfrom sklearn.impute import SimpleImputer\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\nfrom sklearn.ensemble import HistGradientBoostingRegressor\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import mean_squared_error\nimport matplotlib.pyplot as plt\nimport joblib\n\n# ---------- 1) Load datasets ----------\ntrain_df = pd.read_csv(\"/kaggle/input/playground-series-s4e12/train.csv\")\ntest_df  = pd.read_csv(\"/kaggle/input/playground-series-s4e12/test.csv\")\nsample_submission = pd.read_csv(\"/kaggle/input/playground-series-s4e12/sample_submission.csv\")\n\nTARGET = 'Premium Amount'\n\nprint(\"Train shape:\", train_df.shape)\nprint(\"Test shape: \", test_df.shape)\n\n# ---------- 2) Prepare X and y ----------\nX = train_df.drop(columns=[TARGET])\ny_orig = train_df[TARGET]\n\n# Log-transform target for skewed distribution\ny = np.log1p(y_orig)\n\n# Optional: create a small validation split for visualization\nX_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, random_state=42)\n\n# ---------- 3) Preprocessing ----------\nnumeric_features = ['Age', 'Annual Income', 'Number of Dependents', 'Health Score',\n                    'Previous Claims', 'Vehicle Age', 'Credit Score', 'Insurance Duration']\ncategorical_features = ['Gender', 'Marital Status', 'Education Level', 'Occupation',\n                        'Location', 'Policy Type', 'Customer Feedback', 'Smoking Status',\n                        'Exercise Frequency', 'Property Type']\n\nnumeric_transformer = Pipeline([\n    ('imputer', SimpleImputer(strategy='median')),\n    ('scaler', StandardScaler())\n])\n\ncategorical_transformer = Pipeline([\n    ('imputer', SimpleImputer(strategy='most_frequent')),\n    ('onehot', OneHotEncoder(handle_unknown='ignore', sparse_output=False))\n])\n\npreprocessor = ColumnTransformer([\n    ('num', numeric_transformer, numeric_features),\n    ('cat', categorical_transformer, categorical_features)\n])\n\n# ---------- 4) Build pipeline with HistGradientBoosting ----------\nmodel = Pipeline([\n    ('preprocessor', preprocessor),\n    ('regressor', HistGradientBoostingRegressor(\n        max_iter=200,\n        max_depth=6,\n        learning_rate=0.05,\n        random_state=42\n    ))\n])\n\n# ---------- 5) Train the model ----------\nmodel.fit(X_train, y_train)\nprint(\"Model training completed!\")\n\n# ---------- 6) Save the model ----------\njoblib.dump(model, 'histgb_insurance_model.joblib')\nprint(\"Model saved as histgb_insurance_model.joblib\")\n\n# ---------- 7) Predict on validation set ----------\ny_val_pred = model.predict(X_val)\ny_val_pred_orig = np.expm1(y_val_pred)\ny_val_orig = np.expm1(y_val)\n\n# Calculate RMSE\nrmse_val = np.sqrt(mean_squared_error(y_val_orig, y_val_pred_orig))\nprint(f\"Validation RMSE: {rmse_val:.2f}\")\n\n# ---------- 8) Visualizations ----------\nplt.figure(figsize=(10,5))\nplt.scatter(y_val_orig, y_val_pred_orig, alpha=0.3)\nplt.plot([0, max(y_val_orig)], [0, max(y_val_orig)], 'r--', lw=2)  # perfect prediction line\nplt.xlabel(\"Actual Premium Amount\")\nplt.ylabel(\"Predicted Premium Amount\")\nplt.title(\"Actual vs Predicted Premium Amount (Validation Set)\")\nplt.show()\n\nplt.figure(figsize=(10,5))\nplt.hist(y_val_orig, bins=50, alpha=0.5, label='Actual')\nplt.hist(y_val_pred_orig, bins=50, alpha=0.5, label='Predicted')\nplt.xlabel(\"Premium Amount\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Distribution of Actual vs Predicted Premiums\")\nplt.legend()\nplt.show()\n\n# ---------- 9) Predict on test data ----------\ny_test_pred = model.predict(test_df)\ny_test_pred_orig = np.expm1(y_test_pred)  # convert back from log scale\n\n# ---------- 10) Create submission ----------\nsubmission = sample_submission.copy()\nsubmission['Premium Amount'] = y_test_pred_orig\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"submission.csv created! Ready to submit.\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-09T06:00:45.394276Z","iopub.execute_input":"2025-10-09T06:00:45.394559Z","iopub.status.idle":"2025-10-09T06:01:45.669367Z","shell.execute_reply.started":"2025-10-09T06:00:45.394539Z","shell.execute_reply":"2025-10-09T06:01:45.668417Z"}},"outputs":[],"execution_count":null}]}