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!
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.api import Logit, add_constant
# Start coding!df = pd.read_csv('car_insurance.csv')
df.head(2)# Replace problematic characters in column names
df.columns = df.columns.str.replace(' ', '_').str.replace('-', '_').str.replace('(', '').str.replace(')', '')
# Convert categorical columns to numeric codes
for column in df.columns:
if df[column].dtype == 'object':
df[column] = pd.Categorical(df[column]).codes
# Prepare target variable
y = df['outcome']
# Handle missing values
# Fill numerical columns with their mean
for column in df.columns:
if df[column].dtype != 'object':
df[column].fillna(df[column].mean(), inplace=True)
# Variables to store the best feature and its performance
best_feature = None
best_accuracy = 0
# Iterate through each feature to find the best one
for feature in df.drop(columns=['id', 'outcome']).columns:
try:
# Prepare the feature as an independent variable with a constant
X = add_constant(df[[feature]]) # Add constant for intercept
model = Logit(y, X).fit(disp=False)
# Predict and evaluate using the model's own dataset
predictions = (model.predict(X) >= 0.5).astype(int)
accuracy = (predictions == y).mean() # Calculate accuracy
# Track the best performing feature
if accuracy > best_accuracy:
best_accuracy = accuracy
best_feature = feature
except Exception as e:
print(f"Could not process feature {feature} due to: {e}")
# Create a DataFrame with the best feature and accuracy
best_feature_df = pd.DataFrame({
'best_feature': [best_feature],
'best_accuracy': [best_accuracy]
})
# Display the DataFrame
print(best_feature_df)