Machine Learning Health Insurance Cost Prediction Project

Machine Learning project 20

Machine Learning Health Insurance Cost Prediction Project

Build and evaluate a complete health insurance cost prediction workflow with reproducible Python code, explicit metrics, and honest limitations.

Explore Machine Learning training in VizagView all project ideas

Dataset and objective

A reproducibly generated table with age, BMI, children, smoking flag, region, and a synthetic annual-cost target.

Skills practised

  • Mixed-feature regression
  • Gradient boosting
  • Cost metrics
  • High-stakes limits

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install numpy pandas scikit-learn
  • About 45-60 minutes to build and review

Machine Learning workflow

  1. Data: A reproducibly generated table with age, BMI, children, smoking flag, region, and a synthetic annual-cost target.
  2. Preprocessing: OneHotEncoder processes categorical variables inside a ColumnTransformer while numeric values pass through.
  3. Model: GradientBoostingRegressor learns nonlinear synthetic cost relationships.
  4. Evaluation: Holdout MAE in synthetic cost units and R-squared.

Complete Python code

Save the code as ml_health_insurance_cost_prediction.py. The random state and data handling are included so the result can be reproduced and reviewed.

"""Model synthetic health-insurance costs for regression practice."""

from __future__ import annotations

import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder


def make_demo_data(rows: int = 4000, random_state: int = 42) -> pd.DataFrame:
    rng = np.random.default_rng(random_state)
    age = rng.integers(18, 65, rows)
    bmi = np.clip(rng.normal(27, 5, rows), 16, 48)
    children = rng.integers(0, 6, rows)
    smoker = rng.choice(["yes", "no"], rows, p=[0.16, 0.84])
    region = rng.choice(["north", "south", "east", "west"], rows)
    costs = 4000 + 180 * age + 260 * np.maximum(bmi - 22, 0) + 700 * children + 22_000 * (smoker == "yes") + rng.normal(0, 3500, rows)
    costs = np.maximum(costs, 1000)
    return pd.DataFrame({"age": age, "bmi": bmi, "children": children, "smoker": smoker, "region": region, "annual_cost": costs})


def train_model(random_state: int = 42):
    data = make_demo_data(random_state=random_state)
    x, y = data.drop(columns="annual_cost"), data["annual_cost"]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25, random_state=random_state)
    preprocessing = ColumnTransformer([
        ("categories", OneHotEncoder(handle_unknown="ignore"), ["smoker", "region"]),
    ], remainder="passthrough")
    model = make_pipeline(preprocessing, GradientBoostingRegressor(random_state=random_state))
    model.fit(x_train, y_train)
    predictions = model.predict(x_test)
    return model, mean_absolute_error(y_test, predictions), r2_score(y_test, predictions)


def main() -> None:
    _, mae, r2 = train_model()
    print("Synthetic Health Insurance Cost Regression")
    print(f"MAE: {mae:,.2f} synthetic cost units")
    print(f"R-squared: {r2:.3f}")
    print("Education only—not an insurer quote, underwriting rule, health assessment, or coverage decision.")


if __name__ == "__main__":
    main()

How the pipeline works

OneHotEncoder processes categorical variables inside a ColumnTransformer while numeric values pass through.

GradientBoostingRegressor learns nonlinear synthetic cost relationships. Holdout MAE in synthetic cost units and R-squared.

Run the project

  1. Create and activate a virtual environment.
  2. Install the dependencies with python -m pip install numpy pandas scikit-learn.
  3. Run python ml_health_insurance_cost_prediction.py.
  4. Review every printed metric together with the limitation below; a single score never proves deployment readiness.

How to interpret the evaluation

Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.

Accuracy, ethics, and safety limits

Education only—not an insurer quote, underwriting rule, health assessment, premium decision, coverage decision, or substitute for regulated actuarial review.

Ways to extend the project

Use a governed de-identified research dataset, add uncertainty intervals, audit subgroup errors with experts, document exclusions, and separate prediction from policy decisions.

Continue learning Machine Learning

Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.