Insurance is a business that runs on prediction. An insurer sells a promise to pay for something that hasn’t happened yet, so it has to estimate how likely each customer is to claim and how much that claim will cost, then set a price that covers both. Data science in insurance is the modern version of that work: better models of risk, faster claims handling, fraud detection and customers who stay.
This article covers the main use cases of data science and advanced analytics in the insurance industry, then builds the core model of the business in Python: a claim-frequency model on 677,991 real French motor insurance policies, compared against the classic actuarial approach, and turned into a risk-based price. Every number below comes from running the code in this article.
How data science is used in insurance
| Use case | Question it answers | Typical data | Common methods |
|---|---|---|---|
| Pricing and underwriting | What should this customer pay? | Policy and customer details, claims history, vehicle or property data | Poisson and Gamma GLMs, gradient boosting |
| Claims reserving | How much money must we hold for claims not yet settled? | Claim payments over time | Chain ladder, stochastic reserving models |
| Fraud detection | Which claims need a closer look? | Claims, payments, people and garages involved | Anomaly detection, classification, network analysis |
| Claims triage and automation | Which claims can be paid fast, and which need an expert? | Claim forms, adjuster notes, photos | Text classification (NLP), image models |
| Retention and lapse | Who is likely to cancel or not renew? | Policy history, price changes, contacts | Classification, survival analysis |
| Customer lifetime value and cross-sell | Which customers are worth most, and what else do they need? | Policies held, claims, tenure | CLV models, recommendations |
| Catastrophe and climate risk | What could a flood or storm cost us? | Locations, weather and hazard maps | Simulation, geospatial models |
| Telematics (usage-based insurance) | How does this person actually drive? | GPS, speed, braking, time of day | Time-series features, gradient boosting |
Pricing sits at the centre. Underwriting, reserving and capital all depend on good estimates of how often claims happen (frequency) and how big they are (severity). Multiply the two and you get the pure premium, the expected cost of claims per policy per year, before the insurer adds expenses and profit. That is what the project below builds.
What “advanced analytics” means in insurance
Insurers often use “advanced analytics” for anything beyond standard reporting. It helps to separate three levels:
- Descriptive: what happened? Loss ratios by product, claims by region, monthly dashboards.
- Predictive: what will happen? Claim frequency and severity models, fraud scores, lapse probabilities.
- Prescriptive: what should we do? Price optimization, which claims to fast-track, which customers to contact before renewal.
Most of the value comes from moving work from the first level to the second, and most of the difficulty is in the data: joining policy, claims and payment systems that nobody designed to work together.
Python project: model motor insurance claims
The data is freMTPL2, a French motor third-party liability portfolio published in the CASdatasets collection and widely used in actuarial research. One table has 677,991 policies with their exposure, number of claims and rating factors (driver age, vehicle, bonus-malus level, area). A second table has the amount of each claim. The CASdatasets repository on GitHub stores both as R data files, which the pyreadr package reads into pandas.
pip install pandas scikit-learn matplotlib pyreadr1. Load the data
import pandas as pd
import pyreadr
BASE = "https://raw.githubusercontent.com/dutangc/CASdatasets/master/data/"
for name in ["freMTPL2freq", "freMTPL2sev"]:
pyreadr.download_file(BASE + name + ".rda", name + ".rda")
policies = pyreadr.read_r("freMTPL2freq.rda")["freMTPL2freq"].reset_index(drop=True)
claims = pyreadr.read_r("freMTPL2sev.rda")["freMTPL2sev"].reset_index(drop=True)
print(policies.shape, claims.shape)
print(policies.head(3).to_string())Output:
(677991, 12) (26444, 2)
IDpol ClaimNb Exposure VehPower VehAge DrivAge BonusMalus VehBrand VehGas Area Density Region
0 1 0.0 0.10 5 0 55 50 B12 Regular D 1217 Rhone-Alpes
1 3 0.0 0.77 5 0 55 50 B12 Regular D 1217 Rhone-Alpes
2 5 0.0 0.75 6 2 52 50 B12 Diesel B 54 PicardieThe key columns: ClaimNb is the number of claims, Exposure is how many years the policy ran (0.10 is about five weeks), and BonusMalus is the French no-claims scale, from 50 for drivers with a long clean record upwards for drivers with past claims (the highest level in this data is 230). Density is the population density where the driver lives.
2. Clean it and measure the claim frequency
policies["ClaimNb"] = policies["ClaimNb"].clip(upper=4) # a handful of policies show 5 to 16 claims
policies["Exposure"] = policies["Exposure"].clip(upper=1) # at most one year per row
policies["Frequency"] = policies["ClaimNb"] / policies["Exposure"]
n_claims = policies["ClaimNb"].sum()
years = policies["Exposure"].sum()
print(f"{len(policies):,} policies, {years:,.0f} policy-years, {n_claims:,.0f} claims")
print(f"Claim frequency: {n_claims / years:.4f} claims per policy-year")
print(f"Policies with at least one claim: {(policies['ClaimNb'] > 0).mean():.1%}")Output:
677,991 policies, 358,343 policy-years, 26,405 claims
Claim frequency: 0.0737 claims per policy-year
Policies with at least one claim: 3.7%Exposure is the most important idea in insurance data. A policy that ran for six months had half the chance to claim of one that ran all year, so always compute frequency as claims per policy-year, never claims per policy. Across the portfolio there are 0.074 claims per policy-year: roughly one claim every 14 years of driving. Only 3.7% of policies have any claim at all, which makes this a rare-event problem.
Capping ClaimNb at 4 and Exposure at 1 year follows common practice with this dataset (the scikit-learn documentation does the same): only 8 policies have more than 4 claims, and 1,224 exposures exceed a year, but these extreme values would otherwise have an outsized effect on the models.
3. Explore the risk factors
import matplotlib.pyplot as plt
def frequency(by):
g = policies.groupby(by, observed=True)[["ClaimNb", "Exposure"]].sum()
return g["ClaimNb"] / g["Exposure"]
age_band = pd.cut(policies["DrivAge"], [17, 20, 25, 30, 40, 50, 60, 70, 100],
labels=["18-20", "21-25", "26-30", "31-40", "41-50", "51-60", "61-70", "71+"])
bm_band = pd.cut(policies["BonusMalus"], [49, 50, 60, 80, 100, 230],
labels=["50", "51-60", "61-80", "81-100", "101+"])
by_age, by_bm = frequency(age_band), frequency(bm_band)
print(by_age.round(3).to_string())
print(by_bm.round(3).to_string())
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4), sharey=True, layout="constrained")
ax1.bar(by_age.index.astype(str), by_age, color="#1f4e79")
ax1.set_title("By driver age")
ax1.set_ylabel("Claims per policy-year")
ax1.tick_params(axis="x", labelrotation=45)
ax2.bar(by_bm.index.astype(str), by_bm, color="#c8242c")
ax2.set_title("By bonus-malus level (50 = best)")
for ax in (ax1, ax2):
ax.spines[["top", "right"]].set_visible(False)
fig.suptitle("Claim frequency, French motor insurance")
fig.savefig("frequency.png", dpi=150, bbox_inches="tight")
plt.show()Output:
DrivAge
18-20 0.239
21-25 0.131
26-30 0.082
31-40 0.069
41-50 0.076
51-60 0.069
61-70 0.062
71+ 0.060
BonusMalus
50 0.051
51-60 0.075
61-80 0.112
81-100 0.143
101+ 0.352
Two factors stand out. Drivers aged 18 to 20 claim 0.239 times a year, more than three times the rate of drivers over 30. And the bonus-malus level, which encodes each driver’s own claims history, shows an even wider spread: drivers at the best level (50) claim 0.051 times a year, while those above 100 claim 0.352 times. Past claims predict future claims, which is why no-claims discounts are so common in motor insurance.
4. Build claim-frequency models
We model claim counts with a Poisson distribution and weight each policy by its exposure. The classic actuarial model is a Poisson generalized linear model (GLM): you cut continuous factors like age into bands, one-hot encode the categories, and the model learns a multiplier for each. Gradient boosting with a Poisson loss is the machine learning alternative. We compare both against charging everyone the average.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import (FunctionTransformer, KBinsDiscretizer,
OneHotEncoder, StandardScaler)
from sklearn.linear_model import PoissonRegressor
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_poisson_deviance
features = ["VehPower", "VehAge", "DrivAge", "BonusMalus", "VehBrand",
"VehGas", "Area", "Density", "Region"]
train, test = train_test_split(policies, test_size=0.25, random_state=0)
w_train, w_test = train["Exposure"], test["Exposure"]
average = np.average(train["Frequency"], weights=w_train)
base = mean_poisson_deviance(test["Frequency"], np.full(len(test), average), sample_weight=w_test)
def score(name, pred):
dev = mean_poisson_deviance(test["Frequency"], pred, sample_weight=w_test)
print(f"{name:<22} deviance {dev:.4f} explained {1 - dev / base:.1%}")
score("Average for everyone", np.full(len(test), average))
# Poisson GLM: the classic actuarial model
glm = make_pipeline(
ColumnTransformer([
("bins", KBinsDiscretizer(n_bins=10, quantile_method="averaged_inverted_cdf"),
["VehAge", "DrivAge"]),
("cats", OneHotEncoder(handle_unknown="ignore"),
["VehBrand", "VehPower", "VehGas", "Region", "Area"]),
("bm", StandardScaler(), ["BonusMalus"]),
("density", make_pipeline(FunctionTransformer(np.log), StandardScaler()), ["Density"]),
]),
PoissonRegressor(alpha=1e-4, max_iter=1000),
)
glm.fit(train[features], train["Frequency"], poissonregressor__sample_weight=w_train)
score("Poisson GLM", glm.predict(test[features]))
# Gradient boosting with a Poisson loss
gbm = HistGradientBoostingRegressor(loss="poisson", max_leaf_nodes=128,
categorical_features="from_dtype", random_state=0)
gbm.fit(train[features], train["Frequency"], sample_weight=w_train)
score("Gradient boosting", gbm.predict(test[features]))Output:
Average for everyone deviance 0.4728 explained 0.0%
Poisson GLM deviance 0.4520 explained 4.4%
Gradient boosting deviance 0.4446 explained 6.0%The score is the Poisson deviance on a test set of 25% of policies (lower is better), and “explained” is the share of the baseline deviance each model removes. The numbers look small, and that’s normal for claim counts: whether a careful driver has an accident this year is mostly luck, so no model can explain most of the variation for individual policies. What matters is the improvement over the average, and the gradient boosting model explains 6.0% against 4.4% for the GLM.
The GLM is still the industry standard for pricing, for good reasons: each factor has a clear multiplier that underwriters can read, regulators can review and actuaries can turn into a price table. Gradient boosting can find interactions between factors that a GLM, which gives each factor a fixed multiplier, misses unless someone adds them by hand. A common approach is to use boosting to discover where the GLM is wrong, then add those effects to the GLM. Read more in XGBoost vs LightGBM vs CatBoost and linear regression explained, which covers the ideas a GLM builds on.
5. Check that the model ranks risk correctly
For pricing, the most useful check is a lift chart: sort the test policies by predicted risk, cut them into ten equal groups and compare the predicted frequency with what actually happened in each group.
pred = gbm.predict(test[features])
decile = pd.qcut(pred, 10, labels=range(1, 11))
d = test.assign(decile=decile, pred=pred * test["Exposure"]).groupby("decile", observed=True)
lift = pd.DataFrame({
"Predicted": d["pred"].sum() / d["Exposure"].sum(),
"Actual": d["ClaimNb"].sum() / d["Exposure"].sum(),
})
print(lift.round(3).to_string())
print(f"Highest decile has {lift['Actual'].iloc[-1] / lift['Actual'].iloc[0]:.1f}x "
f"the claim frequency of the lowest")
fig, ax = plt.subplots(figsize=(8, 4))
x = np.arange(1, 11)
ax.bar(x, lift["Actual"], color="#1f4e79", label="Actual")
ax.plot(x, lift["Predicted"], "o-", color="#c8242c", label="Predicted")
ax.set_xticks(x)
ax.set_xlabel("Predicted risk decile (1 = safest 10% of policies)")
ax.set_ylabel("Claims per policy-year")
ax.set_title("The model separates low- and high-risk drivers")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("deciles.png", dpi=150, bbox_inches="tight")
plt.show()Output:
Predicted Actual
decile
1 0.031 0.030
2 0.041 0.044
3 0.047 0.042
4 0.052 0.054
5 0.058 0.055
6 0.064 0.064
7 0.073 0.072
8 0.086 0.087
9 0.113 0.105
10 0.231 0.221
Highest decile has 7.4x the claim frequency of the lowest
The predictions track reality closely, and the riskiest tenth of policies claims 7.4 times as often as the safest tenth. That spread is the commercial point of the model. An insurer charging everyone the same price would overcharge the safest drivers, who leave for a cheaper competitor, and undercharge the riskiest, who stay. Over time it keeps the bad risks and loses the good ones, a problem known as adverse selection.
6. Claim severity: the long tail
amounts = claims["ClaimAmount"]
top = amounts.sort_values(ascending=False)
print(f"{len(amounts):,} claims, mean €{amounts.mean():,.0f}, median €{amounts.median():,.0f}")
print(f"Largest claim: €{amounts.max():,.0f}")
print(f"Largest 1% of claims = {top.head(len(top) // 100).sum() / top.sum():.0%} of total cost")Output:
26,444 claims, mean €2,266, median €1,172
Largest claim: €4,075,401
Largest 1% of claims = 38% of total costClaim amounts behave very differently from claim counts. The median claim is €1,172, but the mean is almost twice that, pulled up by a few huge claims, and the largest single claim is over €4 million. The largest 1% of claims make up 38% of the total cost. That’s why actuaries usually model severity separately, often with a Gamma GLM for ordinary claims and a separate treatment (or reinsurance) for very large ones.
7. From risk to price
Multiplying predicted frequency by the average cost per claim gives the expected claims cost, the pure premium, for each risk group:
severity = amounts.mean() # average cost per claim
risk = lift["Predicted"]
premium = pd.DataFrame({
"Claims per year": risk.round(3),
"Expected cost (€)": (risk * severity).round(0).astype(int),
}).iloc[[0, 4, 9]]
premium.index = ["Safest 10%", "Middle (5th decile)", "Riskiest 10%"]
print(premium.to_string())Output:
Claims per year Expected cost (€)
Safest 10% 0.031 71
Middle (5th decile) 0.058 131
Riskiest 10% 0.231 524The model expects the riskiest tenth of drivers to cost about €524 a year in claims, against €71 for the safest tenth. A real tariff would add a severity model that varies by policy, expenses, a profit margin and constraints such as maximum year-on-year increases, and it would be checked for fairness and regulatory compliance. But the structure is the same: frequency times severity, estimated from data.
Data science in life insurance
Life insurance uses the same tools on different questions, and over much longer horizons:
- Mortality and longevity: estimating how long policyholders and pensioners will live, using survival models on large populations.
- Lapse prediction: identifying customers likely to cancel early, which matters because many life policies only become profitable after several years.
- Accelerated underwriting: using application data, prescription histories or other records (where the law allows) to approve some applicants without a medical exam.
- Customer value and cross-sell: finding which customers need cover they don’t have, such as income protection alongside a mortgage policy.
Because life products last decades, insurers judge models on stability and explainability as much as accuracy, and there is often less recent data for the outcomes that matter most, such as deaths among younger policyholders.
Fairness, regulation and privacy
Most countries regulate insurance pricing, and data science has to work within those rules:
- Banned rating factors: in the European Union, the Court of Justice’s Test-Achats ruling means insurers cannot charge men and women different prices, which has applied to new contracts since December 2012. Many countries prohibit other factors, such as ethnicity.
- Proxies: a model can rediscover a banned factor through other variables. Removing a column isn’t enough; check whether predictions differ by protected groups.
- Explainability: customers and regulators can ask why a price is what it is. This is a big reason GLMs remain popular.
- Privacy: claims and health data are sensitive personal data under laws like GDPR. See the dark side of big data.
What does an insurance data scientist do?
Insurance data scientists work alongside actuaries, who are trained and often professionally certified in pricing, reserving and solvency. In practice the roles overlap: actuaries increasingly use Python and machine learning, and data scientists need to understand exposure, deviance and reserving. Typical projects include pricing models, fraud scoring, claims text classification, retention models and dashboards for underwriters.
The skills that matter most are SQL and pandas for joining policy and claims data, statistics (especially GLMs and count models), gradient boosting, careful validation on held-out years, and being able to explain a model to people who will be accountable for its decisions. The data science career guide covers how to get started.
Project ideas for insurance data science
- Severity model: join
freMTPL2sevto the policies and fit a Gamma GLM for claim size, then combine it with the frequency model above into a full pure premium. - Fairness check: compare predicted prices across regions or density bands and see which features drive the differences.
- Interpretability: plot partial dependence for driver age and bonus-malus from the gradient boosting model and compare them with the GLM.
- Medical costs: the “insurance” dataset from the book Machine Learning with R (1,338 people with age, BMI, smoking status and charges) is a small, simple regression problem.
- Claims text: classify claim descriptions by type with the techniques in our NLP with Python tutorial.
Related reading
- Data science by industry
- Data science in retail, with a Python project
- Logistic regression explained
- Random forests explained
- Exploratory data analysis in Python
The full freMTPL2 data and documentation are in the CASdatasets repository on GitHub.
FAQ
How is data science used in insurance?
To price policies according to risk, estimate reserves for future claims, detect fraud, automate and triage claims, predict which customers will leave, and model catastrophe and climate risk. Pricing models of claim frequency and severity are the core of most insurers’ analytics.
What is the difference between an actuary and a data scientist in insurance?
Actuaries are professionally trained in insurance mathematics, pricing, reserving and solvency, and often sign off on regulatory results. Data scientists bring machine learning, programming and data engineering skills. Many teams mix both, and the skills increasingly overlap.
Why do insurers use GLMs instead of machine learning?
GLMs give a clear multiplier for every rating factor, which makes prices easy to explain to customers, underwriters and regulators. Machine learning models such as gradient boosting are often more accurate and are used to find patterns the GLM misses, to set prices in less regulated areas and for tasks like fraud detection.
What data do insurance companies use?
Policy details (who, what and where is insured), claims history and payments, customer interactions, and external data such as vehicle databases, maps, weather and, for some products, telematics from cars or phones.
What is claim frequency and claim severity?
Frequency is the number of claims per unit of exposure, usually per policy-year. Severity is the average cost of a claim. Frequency multiplied by severity is the pure premium: the expected cost of claims per policy per year.
Is there a public dataset for insurance data science?
Yes. The freMTPL2 French motor dataset used in this article is a standard benchmark for claim frequency and severity. Others include the medical costs dataset from Machine Learning with R and many more in the CASdatasets collection.
