Dive into the heart of data science with a project that combines healthcare insights and predictive analytics. As a Data Scientist at a top Health Insurance company, you have the opportunity to predict customer healthcare costs using the power of machine learning. Your insights will help tailor services and guide customers in planning their healthcare expenses more effectively.
Dataset Summary
Meet your primary tool: the insurance.csv dataset. Packed with information on health insurance customers, this dataset is your key to unlocking patterns in healthcare costs. Here's what you need to know about the data you'll be working with:
insurance.csv
| Column | Data Type | Description |
|---|---|---|
age | int | Age of the primary beneficiary. |
sex | object | Gender of the insurance contractor (male or female). |
bmi | float | Body mass index, a key indicator of body fat based on height and weight. |
children | int | Number of dependents covered by the insurance plan. |
smoker | object | Indicates whether the beneficiary smokes (yes or no). |
region | object | The beneficiary's residential area in the US, divided into four regions. |
charges | float | Individual medical costs billed by health insurance. |
A bit of data cleaning is key to ensure the dataset is ready for modeling. Once your model is built using the insurance.csv dataset, the next step is to apply it to the validation_dataset.csv. This new dataset, similar to your training data minus the charges column, tests your model's accuracy and real-world utility by predicting costs for new customers.
Let's Get Started!
This project is your playground for applying data science in a meaningful way, offering insights that have real-world applications. Ready to explore the data and uncover insights that could revolutionize healthcare planning? Let's begin this exciting journey!
# Re-run this cell
# Import required libraries
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import cross_val_score
# Loading the insurance dataset
insurance_data_path = 'insurance.csv'
insurance = pd.read_csv(insurance_data_path)
insurance.head()# Implement model creation and training here
# Use as many cells as you needimport pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score as r2_metric
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
# -----------------------
# STEP 1: Load and clean training data
# -----------------------
df = pd.read_csv("insurance.csv", na_values=["", " ", "NA", "N/A", "-", "null"])
# Clean data (same logic as before)
df['age'] = df['age'].apply(lambda x: abs(x) if pd.notnull(x) else np.nan)
df['sex'] = df['sex'].str.lower().map({
'female': 'F', 'woman': 'F', 'f': 'F',
'male': 'M', 'man': 'M', 'm': 'M'
})
df['children'] = df['children'].apply(lambda x: abs(x) if pd.notnull(x) else np.nan)
df['smoker'] = df['smoker'].str.lower().map({'yes': 'Y', 'no': 'N'})
df['region'] = df['region'].str.title()
df['charges'] = df['charges'].replace(r'[\$,]', '', regex=True).astype(float)
# Drop rows with >2 missing values
df = df[df.isnull().sum(axis=1) <= 2]
# Fill missing numerics with median, categoricals with mode
numeric_cols = df.select_dtypes(include=np.number).columns
for col in numeric_cols:
df[col] = df[col].fillna(df[col].median())
categorical_cols = df.select_dtypes(include='object').columns
for col in categorical_cols:
df[col] = df[col].fillna(df[col].mode()[0])
# -----------------------
# STEP 2: Set up features and labels
# -----------------------
X = df.drop(columns=["charges"])
y = df["charges"]
# -----------------------
# STEP 3: Create preprocessing pipeline
# -----------------------
categorical_features = ['sex', 'smoker', 'region']
numeric_features = ['age', 'bmi', 'children']
preprocessor = ColumnTransformer(transformers=[
('cat', OneHotEncoder(drop='first'), categorical_features)
], remainder='passthrough')
# -----------------------
# STEP 4: Train the model
# -----------------------
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = Pipeline(steps=[
('preprocessor', preprocessor),
('regressor', LinearRegression())
])
model.fit(X_train, y_train)
# -----------------------
# STEP 5: Evaluate the model
# -----------------------
y_pred = model.predict(X_test)
r2_score = r2_metric(y_test, y_pred)
print(f"R-Squared Score: {r2_score:.4f}")
if r2_score < 0.65:
print("⚠️ Warning: R-Squared score is below the required threshold of 0.65.")
# -----------------------
# STEP 6: Predict on validation dataset
# -----------------------
validation_data = pd.read_csv("validation_dataset.csv", na_values=["", " ", "NA", "N/A", "-", "null"])
# Apply same cleaning
validation_data['age'] = validation_data['age'].apply(lambda x: abs(x) if pd.notnull(x) else np.nan)
validation_data['sex'] = validation_data['sex'].str.lower().map({
'female': 'F', 'woman': 'F', 'f': 'F',
'male': 'M', 'man': 'M', 'm': 'M'
})
validation_data['children'] = validation_data['children'].apply(lambda x: abs(x) if pd.notnull(x) else np.nan)
validation_data['smoker'] = validation_data['smoker'].str.lower().map({'yes': 'Y', 'no': 'N'})
validation_data['region'] = validation_data['region'].str.title()
# Fill missing values
for col in numeric_features:
if col in validation_data.columns:
validation_data[col] = validation_data[col].fillna(df[col].median())
for col in categorical_features:
if col in validation_data.columns:
validation_data[col] = validation_data[col].fillna(df[col].mode()[0])
# Predict
predictions = model.predict(validation_data)
predictions = np.maximum(predictions, 1000) # Enforce minimum charge of 1000
validation_data['predicted_charges'] = predictions
# Done!
print("✅ Predictions completed. Column 'predicted_charges' added to validation_data.")