Insurance companies invest a lot of time and money into optimizing their pricing and accurately estimating the likelihood that customers will make a claim. In many countries insurance it is a legal requirement to have car insurance in order to drive a vehicle on public roads, so the market is very large!
(Source: https://www.accenture.com/_acnmedia/pdf-84/accenture-machine-leaning-insurance.pdf)
Knowing all of this, On the Road car insurance have requested your services in building a model to predict whether a customer will make a claim on their insurance during the policy period. As they have very little expertise and infrastructure for deploying and monitoring machine learning models, they've asked you to identify the single feature that results in the best performing model, as measured by accuracy, so they can start with a simple model in production.
They have supplied you with their customer data as a csv file called car_insurance.csv, along with a table detailing the column names and descriptions below.
The dataset
| Column | Description |
|---|---|
id | Unique client identifier |
age | Client's age:
|
gender | Client's gender:
|
driving_experience | Years the client has been driving:
|
education | Client's level of education:
|
income | Client's income level:
|
credit_score | Client's credit score (between zero and one) |
vehicle_ownership | Client's vehicle ownership status:
|
vehcile_year | Year of vehicle registration:
|
married | Client's marital status:
|
children | Client's number of children |
postal_code | Client's postal code |
annual_mileage | Number of miles driven by the client each year |
vehicle_type | Type of car:
|
speeding_violations | Total number of speeding violations received by the client |
duis | Number of times the client has been caught driving under the influence of alcohol |
past_accidents | Total number of previous accidents the client has been involved in |
outcome | Whether the client made a claim on their car insurance (response variable):
|
# Import required modules
import pandas as pd
import numpy as np
from statsmodels.formula.api import logit
# Start coding!1. Read and explore dataset
# Load dataset
df = pd.read_csv("car_insurance.csv")
df.head()# View dataset info
df.info()# Verify null values
print("Missing values per column:")
print(df.isnull().sum())
# Percentage of missing values
print("Percentage of missing values")
print(df.isnull().sum()/len(df) * 100)2. Fill missing values
# credit_score and annual_mileage present missing values, filling with median
# as it is more robust than the mean
df["credit_score"] = df["credit_score"].fillna(df["credit_score"].median())
df["annual_mileage"] = df["annual_mileage"].fillna(df["annual_mileage"].median())
print("Missing values after imputation:")
print(df.isnull().sum())3. Preparing for modelling
features = [col for col in df.columns if col not in ['id', 'outcome']]
print("Features to evaluate:")
print(features)4. Building and storing the models
# Loop through features
models = []
for col in features:
print(f"Training model for feature '{col}'")
# Create formula (cat ~ num)
formula = f"outcome ~ {col}"
model = logit(formula, data=df).fit()
models.append(model)
print(f"Total models trained: {len(models)}")5. Measure performance
accuracies = []
for i in range(len(models)):
print(f"Calculating precision for model {i+1}/{len(models)} - Feature: '{features[i]}'")
# Get confusion matrix on model i
conf_matrix = models[i].pred_table()
# Extract individual values from conf_matrix
true_negatives = conf_matrix[0,0]
false_positives = conf_matrix[0,1]
false_negatives = conf_matrix[1,0]
true_positives = conf_matrix[1,1]
# Calculate precision (accuracy)
accuracy = (true_positives + true_negatives)/(true_positives + true_negatives + false_positives + false_negatives)
# Add values to accuracies list
accuracies.append(accuracy)
print(f" Accuracy: {accuracy:.4f}")
print(f"Total calculated accuracies: {len(accuracies)}")