Counts and amounts: objectives and exposure
Claims per policy, rainfall, spend. Choose Poisson, Gamma or Tweedie to match the target's shape, and use exposure so a half-year policy isn't compared with a full year.
What runs in CodeSplash
- XGBoost Verified in Python and R
- LightGBM Verified in Python and R
- Generalized additive model Verified in Python and R
- Bayesian GLM Verified in Python and R
You will be able to
- Match Poisson, Gamma and Tweedie objectives to the target
- Use an exposure so models learn a rate
- Read deviance rather than RMSE on these targets
Read first
Not every number is bell-shaped
ReadSquared error treats a miss of 5 the same whether the prediction is 10 or 10,000, and it can predict negative values. Some targets have a shape that says otherwise.
| Target | Objective | Why it fits |
|---|---|---|
| Claims per policy | Poisson (counts) | Non-negative counts, with variance rising alongside the mean |
| Cost of a claim | Gamma (positive amounts) | Strictly positive, with spread growing with the mean |
| Total spend, with many zeros | Tweedie (amounts with many zeros) | A spike at zero plus a positive tail |
All three use a log link, so predictions stay positive.
What's the right comparison?
PredictPredict first
Driver A had 1 claim during a full year. Driver B had 1 claim during a half year on the books. Compared per year, who looks riskier?
Reveal
Driver B. One claim in half a year is a rate of 2 per year, against 1 for driver A. A model that doesn't know about time on risk treats them alike. Exposure tells it: models learn a rate, and predict rate × exposure.
Exposure
ReadCount models usually have a term like this, called an offset:
The exposure's coefficient is fixed at 1, so doubling the time on risk doubles the expected count. Exposure (optional) in Setup takes policy-years, hours, area, or whatever measures opportunity.
Rate, or count?
ExploreOn a log link, a fixed step in multiplies the outcome. Here it's shown for a probability. Change Link and Slope, and watch Change in probability shift as At x moves. Same coefficient, different change, depending on where you start.
DExplorable · GLM link functions
If a coefficient is constant on the link scale, what does it mean on the probability scale?
How much does one more unit of x change the probability here?
Link
Commit your prediction above to see the result
Make your prediction to see the result.
Read a log-link model's effects as ratios: a coefficient of means about 10% more, whatever the level.
Judged by deviance
ReadRMSE on rare counts mostly measures the few big rows. So with one of these objectives, the Primary metric defaults to the matching deviance, which is the score that objective optimizes.
Motor claims with exposure, Poisson deviance:
| Learner | Cross-validated | Test |
|---|---|---|
| Bayesian GLM | 0.574 | 0.504 |
| XGBoost | 0.571 | 0.522 |
| LightGBM | 0.579 | 0.510 |
| GAM | 0.586 | 0.499 |
Tied, on a problem with few events. Deviances from different objectives aren't comparable, so only compare runs with the same one.
Frequency and severity
ReflectInsurers often split the question. Claim count: Poisson with exposure. Cost per claim: Gamma on rows that had a claim. For severity, Gamma deviance is 0.521 for XGBoost, 0.526 for LightGBM and 0.515 for a GAM.
Or use Tweedie on the total, with a Tweedie power between 1 and 2, in one model. Near suits totals with many zeros. For the total amount, its deviance is 35.2 for a GAM at power .
Two models give you two stories to explain, and one model gives you simplicity. Which would you rather defend to the person who sets the prices?
Check your understanding
CheckpointCheck yourself
A model's rate is 0.12 claims per policy-year. What is the expected count for a policy on the books for half a year?
Show the answer
Answer: 0.06
Rate × exposure .
Check yourself
Annual customer spend: 80% of customers spend nothing, and the rest spend positive amounts with a long tail. Which objective fits one model best?
Show the answer
Answer: c
Gamma can't handle exact zeros. Tweedie mixes a point mass at zero with a positive tail.
Check yourself
Why not choose between a Poisson run and a Gamma run by their deviances?
Show the answer
Answer: a
Compare runs with the same objective, or compare both on a shared metric such as MAE, or by predicted total.
Check yourself
Which learner gives you a log-link count model with a readable curve per feature?
Show the answer
Answer: a
A GAM keeps its curves under a log link: they add up on the log scale, and multiply on the count scale. A Bayesian GLM offers Poisson too, with a credible interval for each coefficient.
Set it up
In the appWith a numeric target in Setup, set Objective, then Exposure (optional) and, for Tweedie, Tweedie power. XGBoost, LightGBM and the GAM offer all three objectives, and the Bayesian GLM offers Poisson. The gallery lists the others under Not for this task. The leaderboard then ranks by that deviance.
import numpy as np
import pandas as pd
from sklearn.linear_model import PoissonRegressor
from sklearn.metrics import mean_poisson_deviance
from sklearn.model_selection import KFold
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("claims.csv")
X = StandardScaler().fit_transform(pd.get_dummies(df[["age", "power", "region", "diesel"]], drop_first=True).astype(float))
y, e = df["claims"].to_numpy(), df["exposure"].to_numpy()
dev = []
for tr, va in KFold(4, shuffle=True, random_state=1).split(X):
m = PoissonRegressor(alpha=0.01).fit(X[tr], y[tr] / e[tr], sample_weight=e[tr]) # a rate, weighted by exposure
dev.append(mean_poisson_deviance(y[va], m.predict(X[va]) * e[va]))
print(np.mean(dev))df <- read.csv("claims.csv")
set.seed(1)
fold <- sample(rep(1:4, length.out = nrow(df)))
pois_dev <- function(y, mu) mean(2 * (ifelse(y > 0, y * log(y / mu), 0) - (y - mu)))
dev <- sapply(1:4, function(k) {
fit <- glm(claims ~ age + power + region + diesel + offset(log(exposure)), poisson, df[fold != k, ])
pois_dev(df$claims[fold == k], predict(fit, df[fold == k, ], type = "response"))
})
mean(dev)Recap
Recap- Poisson for counts, Gamma for positive amounts, Tweedie for amounts with many zeros.
- Exposure makes the model learn a rate.
- Judge with the matching deviance, and compare only within one objective.
Concepts in this lesson