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
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
import statsmodels.api as sm
# Start coding!df = pd.read_csv('car_insurance.csv')
df.head()df.info()df.describe()column_name = 'credit_score' # replace with your actual column name
# Visual Inspection
# Histogram
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
sns.histplot(df[column_name].dropna(), kde=True)
plt.title('Histogram')
# Q-Q plot
plt.subplot(1, 2, 2)
sm.qqplot(df[column_name].dropna(), line='s')
plt.title('Q-Q Plot')
plt.tight_layout()
plt.show()
# Statistical Tests
data = df[column_name].dropna()plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
sns.histplot(df[column_name].dropna(), kde=True)
plt.title('Histogram')
# Q-Q plot
plt.subplot(1, 2, 2)
sm.qqplot(df[column_name].dropna(), line='s')
plt.title('Q-Q Plot')
plt.tight_layout()
plt.show()
# Statistical Tests
data = df[column_name].dropna()columns_to_fill = ['credit_score', 'annual_mileage' ]
for column in columns_to_fill:
mean_value = df[column].mean()
df[column].fillna(mean_value, inplace=True)df.info()import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import SimpleImputer
# Load the data
cars = pd.read_csv('car_insurance.csv')
# Drop columns that are not features
columns_to_drop = ["id", "outcome", "postal_code"]
features = cars.drop(columns=columns_to_drop).columns
# Encode categorical variables
label_encoders = {}
for column in cars.select_dtypes(include=['object']).columns:
le = LabelEncoder()
cars[column] = le.fit_transform(cars[column].astype(str))
label_encoders[column] = le
# Define features and target
X = cars[features]
y = cars['outcome']
# Handle missing values by imputing with mean
imputer = SimpleImputer(strategy='mean')
X = imputer.fit_transform(X)
# Train a Random Forest model
rf_model = RandomForestClassifier(random_state=42)
rf_model.fit(X, y)
# Get feature importances
importances = rf_model.feature_importances_
# Create a DataFrame to display the feature importances
feature_importances = pd.DataFrame({'Feature': features, 'Importance': importances})
feature_importances = feature_importances.sort_values(by='Importance', ascending=False)
print(feature_importances)
models = []features = cars.drop(columns =["id", "outcome"]).columnsfor col in features:
model = logit(f"outcome ~{col}", data=cars).fit()
models.append(model)accuracies = []