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.formula.api import logit
from sklearn.metrics import accuracy_score , confusion_matrix
# Start coding!
car_insurance = pd.read_csv('car_insurance.csv')
columns_to_fill = ['credit_score', 'annual_mileage']
for column in columns_to_fill:
car_insurance[column].fillna(car_insurance[column].mean(), inplace=True)
models = []
outcomes = car_insurance['outcome']
columns_to_drop = ['outcome', 'id']
features = car_insurance.drop(columns=columns_to_drop)
for col in features:
model = logit(f'outcome ~ {col}', data=car_insurance).fit()
models.append((col, model))
accuracies = []
conf_matrix = []
true_negatives = []
accuracies2 = []
for model_name, model_instance in models:
predictions = model_instance.predict(features) > 0.5
accuracy = accuracy_score(outcomes, predictions)
accuracies.append((model_name, accuracy))
confusion_matrix = model_instance.pred_table(threshold= 0.5)
conf_matrix.append((model_name, confusion_matrix ))
tn, fp, fn, tp = confusion_matrix[0,0], confusion_matrix[0,1],confusion_matrix[1,0],confusion_matrix[1,1]
true_negatives.append((model_name, tn))
accuracy2 = (tn+tp)/(tn+fp+fn+tp)
accuracies2.append((model_name, accuracy2))
for index in range(len(models)):
model_name, model_instance = models[index]
model_name_acc, model_accuracy = accuracies[index]
model_name_acc2, model_accuracy2 = accuracies2[index]
model_name_con, model_con = conf_matrix[index]
model_name_tn, model_tn = true_negatives[index]
print(f"Model Name: {model_name}, Accuracy: {model_accuracy}")
print(f"Model Name: {model_name}, Accuracy2: {model_accuracy2}")
print(f"Model Name: {model_name}, True Negatives: {model_tn}")
max_accuracy = max(accuracies, key = lambda x: x[1])
max_accuracy2 = max(accuracies2, key = lambda x: x[1])
max_accuracy_index = accuracies.index(max_accuracy)
max_accuracy_index2 = accuracies2.index(max_accuracy2)
best_model , best_accuracy = accuracies[max_accuracy_index]
best_model2 , best_accuracy2 = accuracies2[max_accuracy_index2]
best_feature_df = pd.DataFrame({'best_feature': [best_model], 'best_accuracy': [best_accuracy]})
print(best_feature_df)
best_feature_df2 = pd.DataFrame({'best_feature': [best_model2], 'best_accuracy': [best_accuracy2]})
print(best_feature_df2)