12  Zero-Inflated Poisson Regression

When to Use and Not Use Zero-Inflated Poisson Regression

Zero-Inflated Poisson (ZIP) regression is useful when:

  • The outcome variable is discrete and count-type, taking values \(0, 1, 2, \dots\).
  • The data contain more zeros than a standard Poisson model would typically expect.
  • It is scientifically plausible that zeros may arise from more than one mechanism.
  • We want to model both whether an observation belongs to a certain-zero group and, separately, the expected count among observations that remain in the count-generating process.

However, ZIP regression should not be used automatically whenever zeros appear in a dataset. In particular:

  • If the outcome is binary, use the model introduced in Chapter 8.
  • If the outcome is a count but the data do not exhibit unusual zero inflation, start with the Classical Poisson model introduced in Chapter 10.
  • If the outcome is overdispersed for reasons not primarily driven by excess zeros, compare against the Negative Binomial model introduced in Chapter 11.
  • If there is no substantive reason to believe that a separate zero-generating process exists, a simpler count model is usually easier to interpret.

mindmap
  root((Regression 
  Analysis)
    Continuous <br/>Outcome Y
      {{Unbounded <br/>Outcome Y}}
        )Chapter 3: <br/>Ordinary <br/>Least Squares <br/>Regression(
          (Normal <br/>Outcome Y)
      {{Nonnegative <br/>Outcome Y}}
        )Chapter 4: <br/>Gamma Regression(
          (Gamma <br/>Outcome Y)
      {{Bounded <br/>Outcome Y <br/> between 0 and 1}}
        )Chapter 5: Beta <br/>Regression(
          (Beta <br/>Outcome Y)
      {{Nonnegative <br/>Survival <br/>Time Y}}
        )Chapter 6: <br/>Parametric <br/> Survival <br/>Regression(
          (Exponential <br/>Outcome Y)
          (Weibull <br/>Outcome Y)
          (Lognormal <br/>Outcome Y)
        )Chapter 7: <br/>Semiparametric <br/>Survival <br/>Regression(
          (Cox Proportional <br/>Hazards Model)
            (Hazard Function <br/>Outcome Y)
    Discrete <br/>Outcome Y
      {{Binary <br/>Outcome Y}}
        {{Ungrouped <br/>Data}}
          )Chapter 8: <br/>Binary Logistic <br/>Regression(
            (Bernoulli <br/>Outcome Y)
        {{Grouped <br/>Data}}
          )Chapter 9: <br/>Binomial Logistic <br/>Regression(
            (Binomial <br/>Outcome Y)
      {{Count <br/>Outcome Y}}
        {{Equidispersed <br/>Data}}
          )Chapter 10: <br/>Classical Poisson <br/>Regression(
            (Poisson <br/>Outcome Y)
        {{Overdispersed <br/>Data}}
          )Chapter 11: <br/>Negative Binomial <br/>Regression(
            (Negative Binomial <br/>Outcome Y)
        {{Overdispersed or <br/>Underdispersed <br/>Data}}
        {{Zero Inflated <br/>Data}}
          )Chapter 12: <br/>Zero Inflated Poisson <br/>Regression(
            (Zero Inflated <br/>Poisson <br/>Outcome Y)

Figure 12.1: Regression analysis mind map depicting where Zero-Inflated Poisson regression fits within the broader family of models introduced in this book.

Learning Objectives

By the end of this chapter, you will be able to:

  • Explain why Zero-Inflated Poisson (ZIP) regression is useful for count outcomes with more zeros than a standard Poisson model would typically expect.
  • Describe the difference between structural zeros and ordinary sampling zeros in a count-data setting.
  • Identify the response variable and main explanatory variables in the insurance-claims example used throughout the chapter.
  • Use exploratory summaries and plots to assess whether a standard Poisson model may be inadequate.
  • Write the two components of a ZIP model: a zero-inflation model and a Poisson count model.
  • Fit and compare Classical Poisson or Logistic Regression with ZIP models using both R and Python.
  • Interpret coefficients from the count component and the zero-inflation component.

12.1 Introduction

In many applied regression problems, the outcome of interest is a count: the number of events, occurrences, or cases observed for an individual or unit over a fixed period of time. Examples include the number of hospital visits, the number of customer complaints, the number of defects on a manufactured item, or the number of insurance claims filed by a policyholder in a year.

A common starting point for this kind of outcome is Classical Poisson regression, introduced in Chapter 10, which is designed for nonnegative integer-valued responses and is part of the broader GLM framework (Nelder and Wedderburn 1972; Cameron and Trivedi 2013). However, in practice, some count datasets contain many more zeros than a simple Poisson model would be expected to generate. In those situations, a standard Poisson regression may fit poorly, especially near zero, and may fail to represent the data-generating process in a meaningful way (Lambert 1992; Cameron and Trivedi 2013).

This chapter introduces Zero-Inflated Poisson (ZIP) regression, a model designed for count data with excess zeros (Lambert 1992). ZIP regression is similar to a generalized linear model (GLM) because each part uses a familiar GLM-style link function (Nelder and Wedderburn 1972). More precisely, though, it is best understood as the combination of two linked regression components: a logistic-style model for whether an observation belongs to a zero-generating state, and a Poisson log-link model for the count-generating state. Thus, ZIP regression connects naturally to Chapter 8 and Chapter 10 respectively, but it is not just a single ordinary GLM.

Definition of Zero-Inflated Poisson

A Zero-Inflated Poisson (ZIP) model is a two-component model for a count response with excess zeros. One component models the probability that an observation belongs to a latent group that can only produce zeros. The other component models the expected count among observations that remain in the ordinary Poisson count-generating process.

Throughout the chapter, we use a synthetic insurance-claims dataset as a running example. In this setting, the response of interest is the number of claims filed by a policyholder during a fixed time window. This is a useful example because insurance data often contain a large proportion of zeros: many policyholders do not file any claims at all, while a smaller subset files one or more. That practical feature makes the insurance setting a natural context for introducing zero-inflated modelling.

The chapter is organised as follows:

  • Introduction and chapter roadmap: We introduce Zero-Inflated Poisson (ZIP) regression, explain why it is useful for count data with excess zeros, and position it relative to related cookbook chapters.
  • Running example and data context: We introduce the cookbook insurance-claims dataset, clarify the response variable, classify the covariates, and explain what a zero means in this setting.
  • Data splitting: Before EDA or model fitting, we follow the workflow introduced in Section 1.4 and create training and testing sets. The training set is used for EDA and model fitting, while the testing set is held out for later prediction and model assessment.
  • Exploratory Data Analysis (EDA): Using only the training data, we examine the observed count distribution, the number of zeros and non-zeros, marginal covariate patterns, and the empirical evidence that motivates a zero-inflated model.- Preparing for modelling: We define the response and covariate notation used throughout the rest of the chapter.
  • Comparing ZIP to simpler alternatives: We compare Binary Logistic Regression and Classical Poisson Regression to clarify what each simpler model captures and misses.
  • Data modelling: We formally define the Zero-Inflated Poisson response distribution and its two regression components before moving into estimation.
  • Estimation and model fitting: We fit the ZIP model numerically and show the full workflow in both R and Python.
  • Interpretation of fitted results: We read the fitted coefficient tables for both components and translate the results into insurance-claims language.
  • Inference for model parameters: We discuss standard errors, confidence intervals, p-values, and inferential statements for both the count and zero-inflation components.
  • Hypothesis testing: We test individual covariates, compare nested ZIP models, and discuss when formal comparisons against simpler alternatives are useful.
  • Prediction with the ZIP model: We generate predicted expected counts, predicted zero probabilities, probabilities of specific counts, simulated outcomes, and evaluate prediction quality on held-out data.
  • Model assessment and diagnostics: We assess whether the fitted model captures the observed zero frequency and count distribution, and whether it improves meaningfully over simpler models.
  • Practical considerations and interpretation cautions: We discuss common pitfalls, related models such as hurdle and zero-inflated negative binomial models, and the importance of substantive justification.

Heads-up on further documented use-cases!

ZIP models are not only teaching examples. Table 12.1 summarizes several documented applications where zero-inflated count models help separate an excess-zero process from a count-generating process.

Table 12.1: Examples of documented applied uses of zero-inflated count models.
Paper Main author(s) Brief description Outcome variable explored (\(Y\)) Research question Methods in general Main result or modelling lesson
Zero-Inflated Poisson Regression, With an Application to Defects in Manufacturing Lambert (1992) Introduces ZIP regression through a printed wiring-board soldering-defect application, where some production conditions can generate a nearly perfect zero-defect state while imperfect states still produce counts. Number of soldering defects per area on printed wiring boards. Which manufacturing conditions affect the probability of a perfect zero-defect state and the expected number of defects when defects are possible? ZIP regression with covariates in both the structural-zero probability and the Poisson mean; comparison to log-linear Poisson models and likelihood-based inference. The ZIP framework revealed that two conditions with similar overall means could differ in why those means were low: one could have a higher chance of being in the perfect state, while another could have a lower mean among imperfect items.
Zero-Inflated Poisson Regression Analysis on Frequency of Health Insurance Claim PT. XYZ Kusuma and Purwono (2019) Applies ZIP regression to private health-insurance claim-frequency data with many zeros and compares it with ordinary Poisson regression. Health-insurance claim frequency for insured individuals. Which insured characteristics are associated with claim frequency, and is ZIP more suitable than ordinary Poisson regression for these data? Poisson regression and ZIP regression, with model comparison using Vuong’s test and information criteria such as AIC and BIC. The study reports that ZIP regression is more suitable than ordinary Poisson regression for the claim-frequency data and can support insurance premium-pricing considerations.
Zero-inflated and hurdle models of count data with extra zeros: examples from an HIV-risk reduction intervention trial Hu, Pavlicova, and Nunes (2011) Reviews count models for extra zeros in behavioural-health trials and illustrates how different distributional assumptions change the estimated intervention effect. Count of unprotected sexual occasions in an HIV-risk reduction intervention trial. How should intervention effects be estimated when behavioural count outcomes contain excess zeros and overdispersion? Comparison of Poisson, Negative Binomial, ZIP, Poisson hurdle, Zero-Inflated Negative Binomial, and Negative Binomial hurdle models. The Zero-Inflated Negative Binomial model provided the best fit in the example, illustrating that using a model that mismatches the distribution can bias intervention-effect estimates upward or downward.
Zero-inflated Poisson regression analysis of factors associated with under-five mortality in Ethiopia using 2019 Ethiopian mini demographic and health survey data Argawu and Mekebo (2023) Uses national Ethiopian survey data to identify factors associated with under-five mortality while accounting for excess zeros in the count response. Number of children per woman who died before age five. Which maternal, child, household, and regional factors are associated with under-five mortality in Ethiopia? Count regression model comparison, with ZIP selected based on model-comparison criteria. ZIP was selected as the best model among the compared count models; several factors, including place of residence, delivery place, maternal age, birth order, birth type, cooking fuel, and water-access time, were statistically associated with under-five mortality.

Tip on model selection for count variables

When deciding between Chapter 10, Chapter 11, and Chapter 12, do not rely only on the number of observed zeros. Combine the empirical evidence with a subject-matter explanation for why some observations may come from a different zero-generating mechanism (Lambert 1992; Cameron and Trivedi 2013).

12.2 Running Example and Data Context

To motivate ZIP regression, we use the synthetic insurance-claims data prepared for this chapter of the Regression Cookbook. The CSV is available from the cookbook GitHub repository: raw-data/zero_inflated_poisson.csv (Tai, Man-Yeung (Andy) 2026). We treat this file as the chapter’s teaching dataset rather than as an external real-world insurance portfolio.

Each row in the dataset represents one policyholder, and the main outcome records how many insurance claims that policyholder filed during the observation window. The response variable is claims, a nonnegative integer-valued count: \(0, 1, 2, \dots\)

The dataset contains the following variables.

Variables in the zero-inflated insurance-claims dataset.
Variable Name Coding Name Alias Type Scale Model Role Notes
Number of Insurance Claims (past year) claims Discrete Nonnegative count; positively unbounded in principle Response Zero-inflated count outcome. A value of \(0\) means no claims were filed during the observation window.
Driver Age (years) driver_age Continuous Bounded by design: 18 - 75 years Regressor Age of the policyholder or driver.
Annual Mileage (km/year) annual_mileage Continuous Bounded by design: 2,000 - 40,000 km/year Regressor Total kilometers driven per year.
Vehicle Age (years) vehicle_age Discrete Bounded integer: 0 - 20 years Regressor Age of the insured vehicle.
Sex Indicator (female or male) male Discrete Bounded binary indicator: \(0\) or \(1\) Regressor \(1\) indicates male and \(0\) indicates female, according to the dataset coding.
Driving Environment (rural or urban) urban_area Discrete Bounded binary indicator: \(0\) or \(1\) Regressor \(1\) indicates urban driving environment and \(0\) indicates rural driving environment.
Prior Claims Indicator (no or yes) prior_claims Discrete Bounded binary indicator: \(0\) or \(1\) Regressor \(1\) indicates at least one prior claim and \(0\) indicates no prior claims.

A value of zero for the response means that the policyholder filed no claims during the observation period. Importantly, that zero can be interpreted in more than one way. In some cases, the policyholder may be effectively outside the claims-generating process for that period, or had such limited exposure that a positive claim count was structurally unlikely. In other cases, the policyholder may have been fully at risk of filing a claim but simply happened not to do so. This distinction is central to the two-part structure of the ZIP model, which will be discussed later in the data-modelling section.

12.2.1 Study design: inferential and predictive inquiries

The synthetic insurance-claims example supports two related but distinct modelling inquiries. Keeping them separate is important because the evidence used to interpret associations is not identical to the evidence used to evaluate predictions.

The inferential inquiry asks:

How are policyholder and vehicle characteristics associated with the structural-zero probability, the count-generating mean, and the resulting marginal expected number of claims?

This inquiry motivates the use of the two ZIP components. A regressor may be associated with whether a policyholder belongs to the latent structural-zero state, with the expected number of claims among policyholders in the count-generating state, or with both mechanisms. Later coefficient and fitted-quantity interpretations will therefore need to distinguish the structural-zero probability \(\pi_i\), the count-state mean \(\lambda_i\), and the marginal expected count \((1-\pi_i)\lambda_i\).

The predictive inquiry asks:

How well can the available policyholder and vehicle characteristics predict claim-related quantities for policyholders not used to fit the model?

For ZIP regression, prediction can refer to more than one quantity. Later in the chapter, the fitted training model can be used to predict the marginal expected number of claims, the probability of an observed zero, and probabilities of specific claim counts for the held-out testing observations. Predictive performance must be evaluated using data that were not used to estimate the model.

Table 12.2: Inferential and predictive inquiries for the synthetic insurance-claims running example.
Inquiry type Main question Primary quantities of interest Evidence used later
Inferential How are the regressors associated with the two ZIP mechanisms and the overall response, and are those patterns reasonably stable across the split? \(\pi_i\), \(\lambda_i\), component coefficients, marginal fitted quantities, uncertainty Coefficients and joint covariance from the frozen specification refitted on the testing data, interpreted alongside the corresponding training estimates
Predictive How accurately does the training-fitted model describe policyholders not used to estimate it? Marginal expected claims, zero probabilities, count probabilities Predictions from the training model evaluated against the testing responses

Because the data are synthetic, these inquiries are used to demonstrate ZIP modelling and interpretation. They do not support claims about a real insurance population, causal effects, premium-setting policy, or the latent status of any particular policyholder.

12.2.2 Loading and previewing the data

The following scripts load the cookbook CSV directly from GitHub and create the has_claim indicator used during the EDA. The human-readable file page is available at raw-data/zero_inflated_poisson.csv, while the code below uses the raw CSV URL so that R and Python can read the file directly (Tai, Man-Yeung (Andy) 2026). The two languages use the same column names, but they store objects in language-specific data structures: a tibble in R and a pandas DataFrame in Python.

library(readr)
library(dplyr)

zip_data_url <- "https://raw.githubusercontent.com/andytai7/cookbook/main/raw-data/zero_inflated_poisson.csv"

ZIP_data <- read_csv(zip_data_url, show_col_types = FALSE) |>
  mutate(
    has_claim = as.integer(claims > 0),
    male = as.integer(male),
    urban_area = as.integer(urban_area),
    prior_claims = as.integer(prior_claims)
  )

data <- ZIP_data
head(data, 10)
import pandas as pd

zip_data_url = "https://raw.githubusercontent.com/andytai7/cookbook/main/raw-data/zero_inflated_poisson.csv"

data = pd.read_csv(zip_data_url)
data["has_claim"] = (data["claims"] > 0).astype(int)
for col in ["male", "urban_area", "prior_claims"]:
    data[col] = data[col].astype(int)

data.head(10)
Table 12.3: First 10 rows of the zero-inflated insurance-claims dataset using R.
Table 12.4: First 10 rows of the zero-inflated insurance-claims dataset using Python.

The preview should show seven original variables plus the derived has_claim indicator. The GitHub CSV used for this chapter contains 1,000 data rows plus the header row, the expected seven original columns, and no missing values in the version used for this draft (Tai, Man-Yeung (Andy) 2026).

12.3 Data Splitting

Following the data science workflow introduced in Section 1.4, we split the data before conducting EDA or fitting models. The training set is used for exploratory analysis, candidate-model fitting, specification decisions, and goodness-of-fit diagnostics. The testing set is held back while those decisions are made.

After the training-stage specification has been assessed and frozen, the testing observations serve two later purposes:

  1. the unchanged ZIP specification is refitted on the testing observations to obtain a split-sample set of coefficient estimates, standard errors, confidence intervals, and hypothesis tests; and
  2. the ZIP model fitted on the training data is applied to the testing regressors to evaluate held-out predictive performance.

These are distinct operations. The testing-set refit estimates a new parameter vector for the inferential comparison. The predictive assessment does not use that refitted model; it evaluates predictions produced by the original training fit.

Freeze the specification before using the testing results

The testing observations should not be used to revise the regressors, transformations, component formulas, link functions, optimizer settings, or model family after the training-stage diagnostics have been completed.

For the inferential section, refit the same frozen specification on the testing observations and compare its estimates with the training estimates. For the predictive section, retain the training-fitted coefficients and evaluate their predictions against the testing responses.

Because the same testing outcomes contribute to both the split-sample inferential comparison and the predictive assessment, these results should not be described as two independent validation exercises. The predictions are nevertheless out of sample relative to the training-fitted model.

set.seed(123)

split_data <- data |>
  mutate(row_id = row_number(), .before = 1)

n <- nrow(split_data)
split_index <- floor(0.8 * n)
shuffled_rows <- sample(seq_len(n), size = n, replace = FALSE)

train_data <- split_data[shuffled_rows[seq_len(split_index)], ]
test_data <- split_data[shuffled_rows[(split_index + 1):n], ]

split_check_r <- tibble(
  split = c("training", "testing"),
  n = c(nrow(train_data), nrow(test_data)),
  proportion = c(nrow(train_data), nrow(test_data)) / nrow(split_data)
)

# Share the canonical R split with Python for all later computations.
py$training_data <- r_to_py(train_data)
py$testing_data <- r_to_py(test_data)
rng = np.random.default_rng(123)

data_with_row_id = data.copy()
if "row_id" not in data_with_row_id.columns:
    data_with_row_id.insert(0, "row_id", np.arange(1, len(data_with_row_id) + 1))

n = len(data_with_row_id)
split_index = int(np.floor(0.8 * n))
shuffled_rows = rng.permutation(n)

training_data_independent = data_with_row_id.iloc[shuffled_rows[:split_index]].copy()
testing_data_independent = data_with_row_id.iloc[shuffled_rows[split_index:]].copy()

split_check_py_independent = pd.DataFrame({
    "split": ["training", "testing"],
    "n": [len(training_data_independent), len(testing_data_independent)],
    "proportion": [
        len(training_data_independent) / len(data_with_row_id),
        len(testing_data_independent) / len(data_with_row_id),
    ],
})

# The canonical Python objects used later are supplied by R through reticulate:
# training_data and testing_data
Table 12.5: Training and testing split check using the shuffled R split.
Table 12.6: Training and testing split check using the independently shuffled Python split.

Although both languages use the same seed and the same 80/20 shuffled-split idea, they are not expected to select the same rows. From this point forward, the EDA and model fitting are based on the canonical R training set only. In the Python chunks, the objects training_data and testing_data are copies of the canonical R split, passed through reticulate.

12.4 Exploratory Data Analysis (EDA)

Before fitting any model, we examine whether the empirical distribution of claims in the training data is consistent with a simple Poisson pattern. The main EDA question is not merely “Are there zeros?” Count data often include zeros. The question is whether there are more zeros than the Poisson mean-variance structure would lead us to expect, and whether the covariates show patterns that make a two-component model plausible.

Because the split was performed before EDA, the numerical summaries in this section should be interpreted as training-set summaries. The exact values are the same in R and Python because both languages now use the canonical R split.

12.4.1 Response distribution and zero inflation

A natural first step is to summarise and visualise the count response claims in the training data. Because this is a count variable, a bar plot of observed counts is usually more informative than a density plot.

claim_counts <- train_data |>
  count(claims, name = "n")

ggplot(claim_counts, aes(x = factor(claims), y = n)) +
  geom_col() +
  labs(
    x = "Number of claims",
    y = "Number of policyholders"
  ) +
  zip_theme
claim_counts = (
    training_data["claims"]
    .astype("int64")
    .value_counts()
    .sort_index()
    .reset_index()
)
claim_counts.columns = ["claims", "n"]

fig, ax = plt.subplots(figsize=ZIP_FIGSIZE)
sns.barplot(
    data=claim_counts,
    x=claim_counts["claims"].astype(str),
    y="n",
    color=ZIP_BAR_COLOR,
    ax=ax
)
ax.set_xlabel("Number of claims")
ax.set_ylabel("Number of policyholders")
zip_clean_axis(ax)
plt.tight_layout()
plt.show()
Figure 12.2: Observed distribution of the insurance-claims response in the canonical training data using R.
Figure 12.3: Observed distribution of the insurance-claims response in the canonical training data using Python.

As shown in Figure 12.2 and Figure 12.3, the training-data distribution remains strongly concentrated at zero and then declines through the positive counts. In the training set, there are 408 zero-claim policyholders out of 800 training observations, while the maximum observed count is 14. This visual pattern is the first sign that a one-process Poisson model may not be flexible enough.

The next table compares the observed zero rate in the training data with the zero rate implied by a Poisson distribution whose mean equals the training-set sample mean.

claims_summary <- train_data |>
  summarise(
    `Number of observations` = n(),
    `Number of zeros` = sum(claims == 0, na.rm = TRUE),
    `Proportion of zeros` = mean(claims == 0, na.rm = TRUE),
    `Sample mean` = mean(claims, na.rm = TRUE),
    `Sample variance` = var(claims, na.rm = TRUE),
    `Variance-to-mean ratio` = var(claims, na.rm = TRUE) / mean(claims, na.rm = TRUE),
    `Poisson expected zero rate` = exp(-mean(claims, na.rm = TRUE)),
    `Excess zero rate` = mean(claims == 0, na.rm = TRUE) - exp(-mean(claims, na.rm = TRUE)),
    `Maximum` = max(claims, na.rm = TRUE)
  ) |>
  pivot_longer(
    cols = everything(),
    names_to = "Summary",
    values_to = "Value"
  )

claims_summary |>
  fmt_table() |>
    print_as_dt()
y_train_eda = training_data["claims"]

claims_summary = pd.Series({
    "Number of observations": len(y_train_eda),
    "Number of zeros": int((y_train_eda == 0).sum()),
    "Proportion of zeros": (y_train_eda == 0).mean(),
    "Sample mean": y_train_eda.mean(),
    "Sample variance": y_train_eda.var(ddof=1),
    "Variance-to-mean ratio": y_train_eda.var(ddof=1) / y_train_eda.mean(),
    "Poisson expected zero rate": np.exp(-y_train_eda.mean()),
    "Excess zero rate": (y_train_eda == 0).mean() - np.exp(-y_train_eda.mean()),
    "Maximum": y_train_eda.max()
}).reset_index()
claims_summary.columns = ["Summary", "Value"]
Table 12.7: Summary of the insurance-claims response in the canonical training data using R.
Table 12.8: Summary of the insurance-claims response in the canonical training data using Python.

This table formalises the visual insight from Figure 12.2. In the training data, the sample mean is 1.449, the sample variance is 3.725, and the variance-to-mean ratio is 2.571. A Poisson distribution with the same mean would imply an expected zero rate of about 0.2349, but the observed zero rate is 0.51. The difference, 0.2751, is a simple empirical measure of excess zeros.

12.4.2 Zero claims versus nonzero claims

The next comparison keeps the count response intact, but splits the training data into observations with zero claims and observations with at least one claim. This table is especially useful because ZIP regression is motivated by the possibility that the zero and count-generating parts of the data behave differently.

zero_group_summary <- train_data |>
  group_by(has_claim) |>
  summarise(
    n = n(),
    mean_driver_age = mean(driver_age, na.rm = TRUE),
    mean_annual_mileage = mean(annual_mileage, na.rm = TRUE),
    mean_vehicle_age = mean(vehicle_age, na.rm = TRUE),
    male_rate = mean(male, na.rm = TRUE),
    urban_rate = mean(urban_area, na.rm = TRUE),
    prior_claims_rate = mean(prior_claims, na.rm = TRUE),
    mean_claims = mean(claims, na.rm = TRUE),
    .groups = "drop"
  ) |>
  mutate(
    claim_status = if_else(has_claim == 0, "Zero claims", "At least one claim")
  ) |>
  select(claim_status, everything(), -has_claim)

zero_group_summary_display <- zero_group_summary |>
  mutate(
    claim_status = factor(
      claim_status,
      levels = c("Zero claims", "At least one claim")
    )
  ) |>
  pivot_longer(
    cols = -claim_status,
    names_to = "Statistic",
    values_to = "Value"
  ) |>
  mutate(
    Statistic = recode(
      Statistic,
      n = "Number of observations",
      mean_driver_age = "Mean driver age",
      mean_annual_mileage = "Mean annual mileage",
      mean_vehicle_age = "Mean vehicle age",
      male_rate = "Male rate",
      urban_rate = "Urban-area rate",
      prior_claims_rate = "Prior-claims rate",
      mean_claims = "Mean claims"
    )
  ) |>
  pivot_wider(
    names_from = claim_status,
    values_from = Value
  )

zero_group_summary_display |>
  fmt_table() |>
    print_as_dt()
zero_group_summary = (
    training_data.groupby("has_claim")
    .agg(
        n=("claims", "size"),
        mean_driver_age=("driver_age", "mean"),
        mean_annual_mileage=("annual_mileage", "mean"),
        mean_vehicle_age=("vehicle_age", "mean"),
        male_rate=("male", "mean"),
        urban_rate=("urban_area", "mean"),
        prior_claims_rate=("prior_claims", "mean"),
        mean_claims=("claims", "mean")
    )
    .reset_index()
)

zero_group_summary["claim_status"] = zero_group_summary["has_claim"].map({
    0: "Zero claims",
    1: "At least one claim"
})

zero_group_summary = zero_group_summary.drop(columns="has_claim")

statistic_labels = {
    "n": "Number of observations",
    "mean_driver_age": "Mean driver age",
    "mean_annual_mileage": "Mean annual mileage",
    "mean_vehicle_age": "Mean vehicle age",
    "male_rate": "Male rate",
    "urban_rate": "Urban-area rate",
    "prior_claims_rate": "Prior-claims rate",
    "mean_claims": "Mean claims",
}

statistic_order = list(statistic_labels.values())
claim_status_order = ["Zero claims", "At least one claim"]

zero_group_summary_display = zero_group_summary.melt(
    id_vars="claim_status",
    var_name="Statistic",
    value_name="Value"
)
zero_group_summary_display["Statistic"] = zero_group_summary_display["Statistic"].map(statistic_labels)
zero_group_summary_display["Statistic"] = pd.Categorical(
    zero_group_summary_display["Statistic"],
    categories=statistic_order,
    ordered=True
)
zero_group_summary_display["claim_status"] = pd.Categorical(
    zero_group_summary_display["claim_status"],
    categories=claim_status_order,
    ordered=True
)

zero_group_summary_display = (
    zero_group_summary_display
    .pivot(index="Statistic", columns="claim_status", values="Value")
    .reset_index()
)
zero_group_summary_display.columns.name = None
zero_group_summary_display = zero_group_summary_display[
    ["Statistic", "Zero claims", "At least one claim"]
]
Table 12.9: covariate comparison between zero-claim and nonzero-claim policyholders in the canonical training data using R.
Table 12.10: covariate comparison between zero-claim and nonzero-claim policyholders in the canonical training data using Python.

The training-data EDA shows that the nonzero-claim group drives more miles on average: 17020 annual miles compared with 13570 for the zero-claim group. The prior-claims rate is also higher among policyholders with at least one claim during the study period: 0.3214 compared with 0.1225. This does not prove a causal mechanism, but it suggests that mileage and prior claims may help distinguish the zero and nonzero portions of the response.

12.4.3 Binary covariates

The binary covariates provide a compact way to inspect whether group membership is associated with different average counts and different zero rates in the training data.

binary_cols <- c("male", "urban_area", "prior_claims")

binary_summary <- purrr::map_dfr(binary_cols, function(col) {
  train_data |>
    group_by(value = .data[[col]]) |>
    summarise(
      n = n(),
      mean_claims = mean(claims, na.rm = TRUE),
      var_claims = var(claims, na.rm = TRUE),
      zero_rate = mean(claims == 0, na.rm = TRUE),
      nonzero_rate = mean(claims > 0, na.rm = TRUE),
      max_claims = max(claims, na.rm = TRUE),
      .groups = "drop"
    ) |>
    mutate(variable = col, .before = 1)
})

binary_summary |>
  fmt_table() |>
    print_as_dt()
binary_cols = ["male", "urban_area", "prior_claims"]
binary_summary = []

for col in binary_cols:
    summary = (
        training_data.groupby(col)
        .agg(
            n=("claims", "size"),
            mean_claims=("claims", "mean"),
            var_claims=("claims", "var"),
            zero_rate=("claims", lambda x: (x == 0).mean()),
            nonzero_rate=("claims", lambda x: (x > 0).mean()),
            max_claims=("claims", "max")
        )
        .reset_index()
        .rename(columns={col: "value"})
    )
    summary.insert(0, "variable", col)
    binary_summary.append(summary)

binary_summary = pd.concat(binary_summary, ignore_index=True)
Table 12.11: Claims summary by binary covariates in the canonical training data using R.
Table 12.12: Claims summary by binary covariates in the canonical training data using Python.

The strongest binary-covariate contrast in the training-data EDA is expected to remain prior_claims. Policyholders with prior claims have a mean of about 2.477 claims and a zero rate of about 0.2841; those without prior claims have a mean of about 1.159 claims and a zero rate of about 0.5737. By contrast, the urban_area groups differ by about 0.1358 in mean claims and 0.04536 in zero rate in this training set.

12.4.5 Correlation summary

The final EDA table gives a compact numerical summary of the marginal associations between each covariate, the original count response, and the binary has_claim indicator.

correlation_summary <- train_data |>
  select(driver_age, annual_mileage, vehicle_age, male, urban_area, prior_claims, claims, has_claim) |>
  summarise(across(
    c(driver_age, annual_mileage, vehicle_age, male, urban_area, prior_claims),
    list(
      corr_with_claims = ~ cor(.x, claims),
      corr_with_has_claim = ~ cor(.x, has_claim)
    ),
    .names = "{.col}_{.fn}"
  )) |>
  pivot_longer(
    cols = everything(),
    names_to = c("variable", ".value"),
    names_pattern = "(.*)_(corr_with_.*)"
  )

correlation_summary |>
  fmt_table() |>
    print_as_dt()
corr = training_data[[
    "driver_age", "annual_mileage", "vehicle_age", "male",
    "urban_area", "prior_claims", "claims", "has_claim"
]].corr()

correlation_summary = pd.DataFrame({
    "corr_with_claims": corr["claims"].drop(["claims", "has_claim"]),
    "corr_with_has_claim": corr["has_claim"].drop(["claims", "has_claim"])
}).reset_index(names="variable")
Table 12.15: Correlation of covariates with claims and has_claim in the canonical training data using R.
Table 12.16: Correlation of covariates with claims and has_claim in the canonical training data using Python.

The correlation summary reinforces the graphical EDA. In the training data, annual_mileage has the strongest correlation with claims, about 0.4062, and with has_claim, about 0.3384. prior_claims is also notable, with correlations of about 0.2832 with claims and 0.24 with has_claim. These correlations do not establish causality, but they help explain why these covariates are sensible choices for the model components.

One caution is worth keeping in mind before moving from EDA to modelling. These marginal summaries inspect each covariate mostly one at a time, but the fitted regression model will estimate the contribution of each regressor while holding the others fixed. If two covariates tend to move together, the apparent pattern for one variable may partly reflect the influence of another. For example, the plots and summaries suggest strong patterns for annual_mileage and prior_claims, but later coefficient interpretation should still be read as a model-based adjusted statement rather than as a direct copy of the marginal EDA pattern.

12.4.6 EDA summary

The exploratory analysis points to two connected conclusions. First, claims is a count response with a large concentration at zero. Second, the covariates do not all show the same marginal relationship with the response, so the later ZIP model should be allowed to separate the zero-generating mechanism from the count-generating mechanism.

TLDR summary of the EDA findings for the zero-inflated insurance-claims training data.
EDA Theme TLDR Dynamic Evidence Modelling Implication
Response shape The response is heavily concentrated at zero, with a smaller right tail of positive claim counts. There are 408 zero-claim observations out of 800 training observations; the largest observed count is 14. A count model is needed, but the zero pile-up should be modelled explicitly.
Mean - variance pattern The response is more variable than a simple equidispersed Poisson pattern would suggest. The sample mean is 1.449, the sample variance is 3.725, and the variance-to-mean ratio is 2.571. A one-process Classical Poisson model may be too restrictive.
Zero inflation check The observed zero rate is larger than the zero rate implied by a Poisson model with the same mean. The observed zero rate is 0.51, while the Poisson-expected zero rate is 0.2349; the excess zero rate is 0.2751. This is direct empirical motivation for a zero-inflated model.
Zero versus nonzero profiles Policyholders with at least one claim tend to have higher mileage and a higher prior-claims rate. Mean annual mileage is 17020 for nonzero-claim policyholders versus 13570 for zero-claim policyholders; the prior-claims rate is 0.3214 versus 0.1225. annual_mileage and prior_claims are plausible regressors for both claim frequency and the zero/nonzero distinction.
Binary covariates prior_claims shows the clearest binary-covariate contrast; urban_area is weaker in this training split. With prior claims, mean claims are 2.477 and the zero rate is 0.2841; without prior claims, mean claims are 1.159 and the zero rate is 0.5737. The urban groups differ by about 0.1358 in mean claims and 0.04536 in zero rate. prior_claims should be treated as an important candidate covariate; urban_area may still be retained for substantive insurance interpretation.
Continuous covariates annual_mileage has the clearest positive marginal association with the response. Mean claims rise from 0.3421 in the lowest mileage bin to 4.45 in the highest mileage bin; the zero rate falls from 0.8158 to 0.1. Its correlations are 0.4062 with claims and 0.3384 with has_claim. annual_mileage is a natural candidate for the count component and the zero-inflation component.
Covariate interpretation caution Marginal EDA patterns are useful, but they do not isolate each regressor’s adjusted contribution. annual_mileage and prior_claims both show strong relationships with claims and has_claim, so their fitted coefficients should later be interpreted conditionally on the other model terms. Later model interpretation should distinguish descriptive marginal patterns from adjusted regression effects.

12.5 Preparing for Modelling

The data schema confirms that the response is a zero-inflated count and that the available regressors are either continuous, integer-valued, or binary. There are no multi-category nominal covariates in this dataset, so we do not need to create a baseline category plus a collection of dummy variables. The binary covariates are already coded as \(0/1\) indicators, and the continuous or integer-valued regressors can enter the model directly unless a later modelling choice calls for centering, scaling, or nonlinear transformations.

For policyholder \(i\), define the response as

\[Y_i = \texttt{claims}_i,\]

where \(Y_i\) is the number of claims filed during the observation window. The candidate covariates are indexed in the same order as the variable table above, excluding the response.

Table 12.17: Covariate notation for the zero-inflated insurance-claims model.
Symbol Coding Name Alias Variable Meaning Type Binary Coding
\(x_{1,i}\) driver_age Age of policyholder \(i\), measured in years. Continuous Not binary.
\(x_{2,i}\) annual_mileage Total kilometers driven per year by policyholder \(i\). Continuous Not binary.
\(x_{3,i}\) vehicle_age Age of the insured vehicle for policyholder \(i\), measured in years. Discrete Not binary; integer-valued from 0 to 20.
\(x_{4,i}\) male Sex indicator for policyholder \(i\). Discrete \(1\) means male; \(0\) means female.
\(x_{5,i}\) urban_area Primary driving-environment indicator for policyholder \(i\). Discrete \(1\) means urban; \(0\) means rural.
\(x_{6,i}\) prior_claims Prior-claims-history indicator for policyholder \(i\). Discrete \(1\) means the driver filed claims in previous years; \(0\) means no prior claims.

Using this notation, a compact covariate vector for the full set of candidate regressors is

\[\mathbf{x}_i = \left(1, x_{1,i}, x_{2,i}, x_{3,i}, x_{4,i}, x_{5,i}, x_{6,i}\right)\]

Where the leading \(1\) represents the intercept. In the ZIP model, this covariate vector can be used to build two linked regression components: a count component for the expected number of claims among policyholders in the count-generating process, and a zero-inflation component for the probability of belonging to the extra-zero group. Later sections can choose whether both components use the same covariates or whether one component uses a smaller, substantively motivated subset.

12.6 Comparing to Other Approaches

Before introducing the full Zero-Inflated Poisson (ZIP) model, it is useful to compare it with two simpler approaches that each captures only part of the modelling problem. The goal of this comparison is not only to fit two baselines, but also to see what each baseline reveals about the insurance-claims data.

First, we can turn the count response into a binary response. Define \(H_i = \mathbb{I}(Y_i > 0)\) where \(Y_i\) is the number of claims for policyholder \(i\), and \(\mathbb{I}\) is the indicator function, which outputs \(1\) in the case that \(Y_i>1\), and \(0\) in any other case. A Binary Logistic Regression model for has_claim then describes whether a policyholder filed at least one claim. This is directly connected to the large zero-versus-nonzero split observed in Figure 12.2 and Table 12.7, but it does not distinguish between one claim and several claims.

Second, we can keep the original count response and fit a Classical Poisson Regression model for claims. This model describes the expected number of claims directly, so it keeps the count scale used in Figure 12.4 and Table 12.13. However, it treats all observations as coming from a single count-generating process. In particular, it ties the zero rate to the same mean parameter that governs the positive counts.

These two models are not replacements for ZIP regression in this chapter. Instead, they give us useful comparison points. Logistic Regression focuses on the zero-versus-nonzero distinction. Classical Poisson Regression focuses on the count scale. ZIP regression combines these ideas by allowing a separate zero-generating component and a count-generating component.

12.6.1 Binary Logistic Regression for has_claim

Model definition

The Logistic Regression alternative uses the derived binary response in Equation 12.1.

\[H_i = \begin{cases} 1, & \text{if policyholder } i \text{ filed at least one claim}, \\ 0, & \text{if policyholder } i \text{ filed no claims}. \end{cases} \tag{12.1}\]

The probabilistic assumption is given in Equation 12.2, where \(\pi_i = P(H_i = 1 \mid \mathbf{x}_i)\) is the probability that policyholder \(i\) filed at least one claim.

\[H_i \mid \mathbf{x}_i \sim \operatorname{Bernoulli}(\pi_i) \tag{12.2}\]

The link function is the logit link in Equation 12.3.

\[\operatorname{logit}(\pi_i) = \log\left(\frac{\pi_i}{1 - \pi_i}\right) \tag{12.3}\]

Using the six covariates from the running example, the systematic component is shown in Equation 12.4.

\[\log\left(\frac{\pi_i}{1 - \pi_i}\right) = \alpha_0 + \alpha_1 x_{1,i} + \alpha_2 x_{2,i} + \alpha_3 x_{3,i} + \alpha_4 x_{4,i} + \alpha_5 x_{5,i} + \alpha_6 x_{6,i} \tag{12.4}\]

In Equation 12.4, there are \(7\) coefficients, \(\alpha_0, \alpha_1, \ldots, \alpha_6\), which change the log-odds of having at least one claim. The intercept \(\alpha_0\) is the baseline log-odds when all covariates are equal to zero, while \(\alpha_j\) for \(j \in \{1, 2, \ldots, 6\}\) represents the change in log-odds for a one-unit increase in the corresponding regressor \(x_{j,i}\), holding the other covariates fixed.

As in Chapter 8, this “one-unit increase” interpretation should be read according to the type of covariate. For a continuous covariate, such as driver_age or annual_mileage, \(\alpha_j\) describes the change in log-odds associated with increasing that covariate by one unit, holding the others fixed. For an integer-valued covariate, such as vehicle_age, the interpretation is similar, but the one-unit change corresponds to one additional year of vehicle age. For a binary indicator, such as male, urban_area, or prior_claims, \(\alpha_j\) compares the group coded \(1\) with the reference group coded \(0\). If a nominal categorical covariate with more than two categories were included, its coefficients would be interpreted relative to the omitted reference category, rather than as a literal one-unit increase.

In this formulation, the model describes the probability of at least one claim. It intentionally ignores the difference between one claim and multiple claims.

Heads-up on the connection to Chapter 8!

The logit link, Bernoulli assumption, and odds-ratio interpretation are introduced in Chapter 8. Here we use them only as a comparison point for the ZIP model, not as a full reintroduction of Binary Logistic Regression.

Fitting the model

For this comparison, we fit the model using the canonical training data created earlier in the chapter. The binary response has_claim is created explicitly in both languages so that the transformation from claims to \(H_i\) is visible.

train_data <- train_data |>
  mutate(has_claim = as.integer(claims > 0))

lr_model_r <- glm(
  has_claim ~ driver_age + annual_mileage + vehicle_age + male + urban_area + prior_claims,
  data = train_data,
  family = binomial(link = "logit")
)

broom::tidy(lr_model_r)
training_data = training_data.copy()
training_data["has_claim"] = (training_data["claims"] > 0).astype(int)

covariates = [
    "driver_age",
    "annual_mileage",
    "vehicle_age",
    "male",
    "urban_area",
    "prior_claims",
]

X = sm.add_constant(training_data[covariates], has_constant="add")
H = training_data["has_claim"]

lr_model_py = sm.Logit(H, X).fit(disp=False)

lr_coef_py = pd.DataFrame({
    "term": lr_model_py.params.index,
    "estimate": lr_model_py.params.values,
    "std.error": lr_model_py.bse.values,
    "statistic": lr_model_py.tvalues.values,
    "p.value": lr_model_py.pvalues.values,
})
Table 12.18: Binary Logistic Regression coefficient table for the canonical training data using R.
Table 12.19: Binary Logistic Regression coefficient table for the canonical training data using Python.

Heads-up on R and Python model summaries!

The two outputs may not be formatted identically. R and Python use different summary conventions, and their numerical optimizers can differ in small implementation details. Because both chunks use the same canonical training split, the fitted coefficients should nevertheless be within similar ranges.

The coefficient table in Table 12.18 already points to the main event-probability story. The strongest positive fitted associations with has_claim are attached to annual_mileage and prior_claims, matching the EDA pattern in which higher-mileage policyholders and policyholders with prior claims were less concentrated at zero. driver_age is also positive in this binary model, but the fitted evidence is weaker than for mileage and prior claims. By contrast, vehicle_age, male, and urban_area are much flatter on the zero-versus-nonzero scale in this fit.

Interpreting the coefficients

The raw Logistic Regression coefficients are on the log-odds scale. To make them easier to read, the next table exponentiates scaled coefficient changes. The continuous covariates are rescaled to more meaningful comparisons: 10 years for driver_age, 10,000 km for annual_mileage, and 5 years for vehicle_age. Binary covariates are interpreted as the change from \(0\) to \(1\).

zip_interpret_scales <- tibble(
  term = c("driver_age", "annual_mileage", "vehicle_age", "male", "urban_area", "prior_claims"),
  comparison = c(
    "+10 years of driver age",
    "+10,000 km of annual mileage",
    "+5 years of vehicle age",
    "male (1) versus female (0)",
    "urban (1) versus rural (0)",
    "prior claims (1) versus none (0)"
  ),
  change = c(10, 10000, 5, 1, 1, 1)
)

coef_tbl <- broom::tidy(lr_model_r)
ci_tbl <- confint.default(lr_model_r) |>
  as.data.frame() |>
  tibble::rownames_to_column("term") |>
  rename(conf.low = `2.5 %`, conf.high = `97.5 %`)

lr_effects_r <- coef_tbl |>
  left_join(ci_tbl, by = "term") |>
  inner_join(zip_interpret_scales, by = "term") |>
  transmute(
    covariate = term,
    comparison,
    log_scale_change = estimate * change,
    odds_ratio = exp(estimate * change),
    lower_95 = exp(conf.low * change),
    upper_95 = exp(conf.high * change),
    percent_change = 100 * (exp(estimate * change) - 1),
    p_value = p.value
  )
scale_rows = pd.DataFrame({
    "term": covariates,
    "comparison": [
        "+10 years of driver age",
        "+10,000 km of annual mileage",
        "+5 years of vehicle age",
        "male (1) versus female (0)",
        "urban (1) versus rural (0)",
        "prior claims (1) versus none (0)",
    ],
    "change": [10, 10000, 5, 1, 1, 1],
})

ci = lr_model_py.conf_int()
ci.columns = ["conf.low", "conf.high"]
coef = pd.DataFrame({
    "term": lr_model_py.params.index,
    "estimate": lr_model_py.params.values,
    "conf.low": ci["conf.low"].values,
    "conf.high": ci["conf.high"].values,
    "p_value": lr_model_py.pvalues.values,
})

lr_effects_py = coef.merge(scale_rows, on="term", how="inner")
lr_effects_py["log_scale_change"] = lr_effects_py["estimate"] * lr_effects_py["change"]
lr_effects_py["odds_ratio"] = np.exp(lr_effects_py["log_scale_change"])
lr_effects_py["lower_95"] = np.exp(lr_effects_py["conf.low"] * lr_effects_py["change"])
lr_effects_py["upper_95"] = np.exp(lr_effects_py["conf.high"] * lr_effects_py["change"])
lr_effects_py["percent_change"] = 100 * (lr_effects_py["odds_ratio"] - 1)
Table 12.20: Scaled odds-ratio interpretation for the Binary Logistic Regression model using R.
Table 12.21: Scaled odds-ratio interpretation for the Binary Logistic Regression model using Python.

An odds ratio greater than \(1\) indicates higher odds of at least one claim for the stated comparison, holding the other covariates fixed. An odds ratio below \(1\) indicates lower odds. These are odds-scale statements, not direct probability differences.

The scaled effects in Table 12.20 make the size of the binary-response patterns clearer. Holding the other covariates fixed, a +10,000 km comparison in annual_mileage multiplies the fitted odds of at least one claim by about 5.448, while moving from no prior claims to prior claims multiplies the fitted odds by about 4.672. The +10 year driver_age comparison is positive but smaller, with an odds ratio of about 1.183. The remaining comparisons are much closer to the neutral value of \(1\) in this Logistic Regression model.

Visualizing the fitted Logistic Regression patterns

The next figures overlay empirical training-set summaries with fitted probabilities from the Logistic Regression model. For continuous covariates, the empirical points are binned averages. For binary covariates, the empirical points are group averages. The fitted curves or fitted line segments vary one covariate at a time while holding the remaining covariates at typical training-set values.

# Fitted probabilities were computed by varying one covariate at a time
# while holding the remaining covariates at typical training-set values.

ggplot() +
  geom_point(
    data = lr_observed_r,
    aes(x = x, y = observed),
    alpha = 0.85,
    size = 2
  ) +
  geom_line(
    data = lr_fitted_r,
    aes(x = x, y = fitted),
    linewidth = 1.1
  ) +
  facet_wrap(~ covariate_label, scales = "free_x") +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1), limits = c(0, 1)) +
  labs(
    x = "Covariate value",
    y = "Probability of at least one claim"
  ) +
  zip_theme
# Fitted probabilities are computed by varying one covariate at a time
# while holding the remaining covariates at typical training-set values.

continuous_covariates = ["driver_age", "annual_mileage", "vehicle_age"]
binary_covariates = ["male", "urban_area", "prior_claims"]
labels = {
    "driver_age": "Driver age",
    "annual_mileage": "Annual mileage",
    "vehicle_age": "Vehicle age",
    "male": "Male indicator",
    "urban_area": "Urban-area indicator",
    "prior_claims": "Prior-claims indicator",
}

reference = {
    "driver_age": training_data["driver_age"].median(),
    "annual_mileage": training_data["annual_mileage"].median(),
    "vehicle_age": training_data["vehicle_age"].median(),
    "male": int(training_data["male"].mode().iloc[0]),
    "urban_area": int(training_data["urban_area"].mode().iloc[0]),
    "prior_claims": int(training_data["prior_claims"].mode().iloc[0]),
}

fig, axes = plt.subplots(2, 3, figsize=ZIP_WIDE_FIGSIZE, sharey=True)
axes = axes.flatten()

for ax, covariate in zip(axes, continuous_covariates + binary_covariates):
    if covariate in binary_covariates:
        grid_values = np.array([0, 1])
        observed = (
            training_data.groupby(covariate)["has_claim"]
            .mean()
            .reset_index()
            .rename(columns={covariate: "x", "has_claim": "observed"})
        )
    else:
        grid_values = np.linspace(training_data[covariate].min(), training_data[covariate].max(), 100)
        temp = training_data[[covariate, "has_claim"]].copy()
        temp["bin"] = pd.cut(temp[covariate], bins=6, include_lowest=True)
        observed = (
            temp.groupby("bin", observed=True)
            .agg(x=(covariate, "mean"), observed=("has_claim", "mean"))
            .reset_index(drop=True)
        )

    grid = pd.DataFrame([reference] * len(grid_values))
    grid[covariate] = grid_values
    X_grid = sm.add_constant(grid[zip_model_covariates_py], has_constant="add")
    fitted = lr_model_py.predict(X_grid)

    ax.scatter(observed["x"], observed["observed"], alpha=0.85, s=35)
    ax.plot(grid_values, fitted, linewidth=1.8)
    ax.set_title(labels[covariate])
    ax.set_xlabel("Covariate value")
    ax.set_ylabel("Probability of at least one claim")
    ax.set_ylim(0, 1)
    zip_clean_axis(ax)

plt.tight_layout()
plt.show()
Figure 12.8: Observed event rates and fitted Logistic Regression probabilities by covariate using R.
Figure 12.9: Observed event rates and fitted Logistic Regression probabilities by covariate using Python.

The fitted patterns in Figure 12.8 show the same message visually. When other covariates are held at typical training-set values, the fitted probability of at least one claim rises from about 7.035% at the low end of the mileage range to about 89.74% at the high end. The fitted prior-claims contrast is also visible: the fitted probability changes from about 41.49% for policyholders without prior claims to about 76.81% for policyholders with prior claims. The other panels are comparatively flatter, which is consistent with the smaller odds-ratio contrasts in Table 12.20.

This is exactly what Logistic Regression is meant to do: describe the probability that a policyholder enters the nonzero group. Its limitation is also visible from the original response distribution. Among training observations with at least one claim, the average positive count is 2.957, the maximum positive count is 14, and about 76.79% of nonzero-claim policyholders have more than one claim. After converting claims to has_claim, all of that frequency information is collapsed into \(H_i = 1\).

12.6.2 Classical Poisson Regression for claims

Model definition

The Classical Poisson Regression alternative keeps the original count response, defined in Equation 12.5.

\[Y_i = \text{number of claims filed by policyholder } i \tag{12.5}\]

The probabilistic assumption is shown in Equation 12.6, where \(\lambda_i = \mathbb{E}(Y_i \mid \mathbf{x}_i)\) is the expected number of claims for policyholder \(i\).

\[Y_i \mid \mathbf{x}_i \sim \operatorname{Poisson}(\lambda_i) \tag{12.6}\]

The link function is the log link in Equation 12.7.

\[g(\lambda_i) = \log(\lambda_i) \tag{12.7}\]

Using the same six covariates, the systematic component is given in Equation 12.8.

\[\log(\lambda_i) = \beta_0 + \beta_1 x_{1,i} + \beta_2 x_{2,i} + \beta_3 x_{3,i} + \beta_4 x_{4,i} + \beta_5 x_{5,i} + \beta_6 x_{6,i} \tag{12.8}\]

In Equation 12.8, there are \(7\) coefficients, \(\beta_0, \beta_1, \ldots, \beta_6\), which change the log-mean number of claims. The intercept \(\beta_0\) is the baseline log-mean when all covariates are equal to zero, while \(\beta_j\) for \(j \in \{1, 2, \ldots, 6\}\) represents the change in log-mean claims for a one-unit increase in the corresponding regressor \(x_{j,i}\), holding the other covariates fixed.

As in Chapter 10, this coefficient interpretation also depends on how the regressor is coded. For a continuous covariate, such as driver_age or annual_mileage, \(\beta_j\) describes the change in the log expected count for a one-unit increase in that covariate, holding the others fixed. For an integer-valued covariate, such as vehicle_age, the one-unit comparison corresponds to one additional year of vehicle age. For binary indicators, such as male, urban_area, or prior_claims, \(\beta_j\) compares the expected count for the group coded \(1\) against the reference group coded \(0\). If a nominal categorical covariate with more than two categories were included, its coefficients would compare each included category with the omitted reference category.

This model works directly on the count scale through \(\lambda_i\), but it also imposes the Poisson mean-variance relationship in Equation 12.9.

\[\mathbb{E}(Y_i \mid \mathbf{x}_i) = \operatorname{Var}(Y_i \mid \mathbf{x}_i) = \lambda_i \tag{12.9}\]

Heads-up on the connection to Chapter 10!

The Poisson probability model, log link, and rate-ratio interpretation are introduced in Chapter 10. Here we use Classical Poisson Regression as a baseline count model before moving to ZIP regression.

Fitting the model

cpr_model_r <- glm(
  claims ~ driver_age + annual_mileage + vehicle_age + male + urban_area + prior_claims,
  data = train_data,
  family = poisson(link = "log")
)

broom::tidy(cpr_model_r)
X = sm.add_constant(training_data[covariates], has_constant="add")
Y = training_data["claims"]

cpr_model_py = sm.GLM(
    Y,
    X,
    family=sm.families.Poisson()
).fit()

cpr_coef_py = pd.DataFrame({
    "term": cpr_model_py.params.index,
    "estimate": cpr_model_py.params.values,
    "std.error": cpr_model_py.bse.values,
    "statistic": cpr_model_py.tvalues.values,
    "p.value": cpr_model_py.pvalues.values,
})
Table 12.22: Classical Poisson Regression coefficient table for the canonical training data using R.
Table 12.23: Classical Poisson Regression coefficient table for the canonical training data using Python.

Heads-up on R and Python model summaries!

As with the Logistic Regression output, the two outputs may not be formatted identically. R and Python use different summary conventions, and their numerical optimizers can differ in small implementation details. Because both chunks use the same canonical training split, the fitted coefficients should nevertheless be within similar ranges.

The coefficient table in Table 12.22 tells a count-scale story rather than a zero-versus-nonzero story. annual_mileage and prior_claims remain strong positive predictors, but vehicle_age and male now also show clearer positive fitted associations with the expected number of claims. This is an important difference from the Logistic Regression fit: a covariate may be weak for predicting whether any claim occurs, but still matter for the expected number of claims once the count scale is preserved.

Interpreting the coefficients

Poisson Regression coefficients are on the log-mean scale. Exponentiating a coefficient gives a multiplicative effect on the expected count. The next table uses the same scaling choices as above so that the coefficient interpretation is easier to compare across the two approaches.

coef_tbl <- broom::tidy(cpr_model_r)
ci_tbl <- confint.default(cpr_model_r) |>
  as.data.frame() |>
  tibble::rownames_to_column("term") |>
  rename(conf.low = `2.5 %`, conf.high = `97.5 %`)

cpr_effects_r <- coef_tbl |>
  left_join(ci_tbl, by = "term") |>
  inner_join(zip_interpret_scales, by = "term") |>
  transmute(
    covariate = term,
    comparison,
    log_scale_change = estimate * change,
    rate_ratio = exp(estimate * change),
    lower_95 = exp(conf.low * change),
    upper_95 = exp(conf.high * change),
    percent_change = 100 * (exp(estimate * change) - 1),
    p_value = p.value
  )
ci = cpr_model_py.conf_int()
ci.columns = ["conf.low", "conf.high"]
coef = pd.DataFrame({
    "term": cpr_model_py.params.index,
    "estimate": cpr_model_py.params.values,
    "conf.low": ci["conf.low"].values,
    "conf.high": ci["conf.high"].values,
    "p_value": cpr_model_py.pvalues.values,
})

cpr_effects_py = coef.merge(scale_rows, on="term", how="inner")
cpr_effects_py["log_scale_change"] = cpr_effects_py["estimate"] * cpr_effects_py["change"]
cpr_effects_py["rate_ratio"] = np.exp(cpr_effects_py["log_scale_change"])
cpr_effects_py["lower_95"] = np.exp(cpr_effects_py["conf.low"] * cpr_effects_py["change"])
cpr_effects_py["upper_95"] = np.exp(cpr_effects_py["conf.high"] * cpr_effects_py["change"])
cpr_effects_py["percent_change"] = 100 * (cpr_effects_py["rate_ratio"] - 1)
Table 12.24: Scaled rate-ratio interpretation for the Classical Poisson Regression model using R.
Table 12.25: Scaled rate-ratio interpretation for the Classical Poisson Regression model using Python.

A rate ratio greater than \(1\) means that the expected number of claims is higher for the stated comparison, holding the other covariates fixed. A rate ratio below \(1\) means that the expected number of claims is lower.

The scaled rate ratios in Table 12.24 show that the largest count-scale comparison is again annual_mileage: a +10,000 km comparison multiplies the fitted expected number of claims by about 2.889. The fitted rate ratio for prior_claims is about 2.237, and the +5 year vehicle_age comparison has a fitted rate ratio of about 1.306. These CPR effects are not identical to the Logistic Regression effects because they answer a different question: how the expected count changes, not only whether the count is positive.

Visualizing the fitted Poisson Regression patterns

The next figures overlay empirical mean claims with fitted Poisson means. As before, continuous covariates use binned empirical summaries, binary covariates use group summaries, and the fitted curves vary one covariate at a time while holding the remaining covariates fixed at typical training-set values.

ggplot() +
  geom_point(
    data = cpr_observed_r,
    aes(x = x, y = observed),
    alpha = 0.85,
    size = 2
  ) +
  geom_line(
    data = cpr_fitted_r,
    aes(x = x, y = fitted),
    linewidth = 1.1
  ) +
  facet_wrap(~ covariate_label, scales = "free_x") +
  labs(
    x = "Covariate value",
    y = "Mean number of claims"
  ) +
  zip_theme
fig, axes = plt.subplots(2, 3, figsize=ZIP_WIDE_FIGSIZE, sharey=False)
axes = axes.flatten()

for ax, covariate in zip(axes, continuous_covariates + binary_covariates):
    if covariate in binary_covariates:
        grid_values = np.array([0, 1])
        observed = (
            training_data.groupby(covariate)["claims"]
            .mean()
            .reset_index()
            .rename(columns={covariate: "x", "claims": "observed"})
        )
    else:
        grid_values = np.linspace(training_data[covariate].min(), training_data[covariate].max(), 100)
        temp = training_data[[covariate, "claims"]].copy()
        temp["bin"] = pd.cut(temp[covariate], bins=6, include_lowest=True)
        observed = (
            temp.groupby("bin", observed=True)
            .agg(x=(covariate, "mean"), observed=("claims", "mean"))
            .reset_index(drop=True)
        )

    grid = pd.DataFrame([reference] * len(grid_values))
    grid[covariate] = grid_values
    X_grid = sm.add_constant(grid[zip_model_covariates_py], has_constant="add")
    fitted = cpr_model_py.predict(X_grid)

    ax.scatter(observed["x"], observed["observed"], alpha=0.85, s=35)
    ax.plot(grid_values, fitted, linewidth=1.8)
    ax.set_title(labels[covariate])
    ax.set_xlabel("Covariate value")
    ax.set_ylabel("Mean number of claims")
    zip_clean_axis(ax)

plt.tight_layout()
plt.show()
Figure 12.10: Observed mean claims and fitted Classical Poisson Regression means by covariate using R.
Figure 12.11: Observed mean claims and fitted Classical Poisson Regression means by covariate using Python.

The fitted patterns in Figure 12.10 show why the Poisson baseline is informative. The fitted mean count increases from about 0.2656 to about 5.188 across the mileage range, and from about 0.8247 to about 1.742 across the vehicle-age range, with other covariates held at typical training-set values. The prior-claims panel also shows a clear fitted increase, from about 1.077 to about 2.41.

Classical Poisson Regression therefore preserves the count response and gives a direct model for claim frequency. The fitted patterns in Figure 12.10 and Figure 12.11 are useful because they show the same directional signals already suggested by the EDA: mileage, prior claims, and vehicle age are associated with higher expected counts. At the same time, the fitted Poisson curves are pulled toward the many zero observations. In practical terms, this means that a one-process Poisson model can follow the broad trend but still understate the expected count in parts of the covariate range where the empirical mean is high, such as the upper annual-mileage bins. The model is trying to represent both the zero pile-up and the positive-count pattern with one mean function, so the excess zeros can pull the fitted mean downward.

This is the key limitation for the present chapter. If many zeros arise from a separate mechanism, a single Poisson mean may have difficulty representing both the large mass at zero and the positive-count distribution. The next check makes this limitation explicit by comparing the observed zero frequency with the zero frequency implied by the fitted Poisson means.

The calculation is straightforward once the fitted Poisson means are available. For each policyholder, the fitted Classical Poisson Regression model gives a fitted mean \(\widehat{\lambda}_i\). Under the Poisson model, the probability of observing zero claims for that same policyholder is \(\exp(-\widehat{\lambda}_i)\). Averaging these fitted zero probabilities gives the model-implied zero rate; summing them gives the expected number of zero-claim policyholders under the fitted Poisson model.

# Step 1: extract the fitted Poisson means for the training rows.
cpr_fitted_mu_r <- predict(cpr_model_r, type = "response")

# Step 2: convert each fitted mean into its implied zero probability.
cpr_fitted_zero_prob_r <- exp(-cpr_fitted_mu_r)

# Step 3: compare the observed and model-implied zero frequencies.
cpr_zero_check_r <- tibble(
  Summary = c(
    "Observed zero rate",
    "Average fitted Poisson zero probability",
    "Observed minus fitted zero rate",
    "Observed number of zeros",
    "Expected number of zeros under fitted Poisson"
  ),
  Value = c(
    mean(train_data$claims == 0, na.rm = TRUE),
    mean(cpr_fitted_zero_prob_r, na.rm = TRUE),
    mean(train_data$claims == 0, na.rm = TRUE) -
      mean(cpr_fitted_zero_prob_r, na.rm = TRUE),
    sum(train_data$claims == 0, na.rm = TRUE),
    sum(cpr_fitted_zero_prob_r, na.rm = TRUE)
  )
)

cpr_zero_check_r |>
  fmt_table() |>
    print_as_dt()
# Step 1: recreate the design matrix used by the fitted Poisson model.
X_cpr = sm.add_constant(
    training_data[zip_model_covariates_py].astype(float),
    has_constant="add"
)

# Step 2: extract the fitted Poisson means for the training rows.
cpr_fitted_mu_py = cpr_model_py.predict(X_cpr)

# Step 3: convert each fitted mean into its implied zero probability.
cpr_fitted_zero_prob_py = np.exp(-cpr_fitted_mu_py)

# Step 4: compare the observed and model-implied zero frequencies.
observed_zero_rate_py = (training_data["claims"] == 0).mean()
observed_zero_n_py = int((training_data["claims"] == 0).sum())

cpr_zero_check_py = pd.DataFrame({
    "Summary": [
        "Observed zero rate",
        "Average fitted Poisson zero probability",
        "Observed minus fitted zero rate",
        "Observed number of zeros",
        "Expected number of zeros under fitted Poisson",
    ],
    "Value": [
        observed_zero_rate_py,
        cpr_fitted_zero_prob_py.mean(),
        observed_zero_rate_py - cpr_fitted_zero_prob_py.mean(),
        observed_zero_n_py,
        cpr_fitted_zero_prob_py.sum(),
    ],
})
Table 12.26: Observed zero frequency compared with the zero frequency implied by the fitted Classical Poisson Regression model using R.
Table 12.27: Observed zero frequency compared with the zero frequency implied by the fitted Classical Poisson Regression model using Python.

In Table 12.26 and Table 12.27, the observed zero rate is 51%, while the average zero probability implied by the fitted Classical Poisson model is about 32.87%. The gap is about 18.13%, or roughly 408 observed zeros versus 262.9 expected zeros under the fitted Poisson means. This does not mean the Poisson model is useless; it captures important count-scale gradients. It does mean that the model has no separate mechanism for the extra zeros, and that the same fitted mean must compromise between explaining zero observations and positive counts.

12.6.3 Why ZIP can be useful here

The two simpler approaches highlight the motivation for ZIP regression.

Summary comparison of Binary Logistic Regression, Classical Poisson Regression, and Zero-Inflated Poisson Regression for the insurance-claims running example.
Approach Response Used What the fitted comparison shows here Main Limitation in This Example
Binary Logistic Regression \(H_i = \mathbb{I}(Y_i > 0)\), implemented as has_claim Table 12.20 and Figure 12.8 show a strong zero-versus-nonzero signal for annual_mileage and prior_claims; the fitted odds ratios are about 5.448 and 4.672 for the scaled comparisons. It collapses all positive counts into one category. In the training data, positive counts average 2.957 and can reach 14, so a binary response discards meaningful claim-frequency information.
Classical Poisson Regression \(Y_i\), implemented as claims Table 12.24 and Figure 12.10 show clear count-scale gradients, especially for annual_mileage, prior_claims, and vehicle_age; their scaled fitted rate ratios are about 2.889, 2.237, and 1.306. It assumes a single Poisson count-generating process. As shown in Table 12.26 and Table 12.27, its fitted zero probability is about 32.87%, below the observed zero rate of 51%. The excess zeros also pull the fitted count curve downward, which can understate the empirical mean count in high-risk regions of the covariate space.
Zero-Inflated Poisson Regression \(Y_i\), implemented as claims The EDA and the two baseline fits point to two simultaneous features: a strong zero-versus-nonzero process and meaningful variation in the positive count scale. It is more complex, so it should be used when the EDA and subject-matter context justify a separate zero-generating mechanism.

In the insurance-claims setting, the EDA suggested a large zero-claim group and a positive-count pattern among the remaining observations. Logistic Regression describes the first piece: who is likely to file at least one claim. Classical Poisson Regression describes the second piece: how expected claim counts change with the covariates, but it has to use the same mean structure to explain both the many zeros and the positive-count trend. ZIP regression is useful because it gives these two pieces separate but connected roles. One component models extra zeros, while the other models claim counts among observations that remain in the count-generating process.

12.7 Data Modelling

The previous section used Binary Logistic Regression and Classical Poisson Regression as baseline comparisons. We now define the model that this chapter is actually about: Zero-Inflated Poisson Regression. The goal of this section is to move from the empirical motivation to the formal modelling equations that will later be estimated in R and Python.

We first describe the model generically, without attaching the covariates to the insurance example. After that, we translate the notation back to the variables defined in Table 12.17.

12.7.1 Response distribution: a zero-inflated Poisson random variable

Let \(Y_i\) be a nonnegative count response for observational unit \(i\), where \(i = 1, 2, 3, \ldots, n\), and \(n\) is the number of observations. A Zero-Inflated Poisson model assumes that each observation can arise from one of two latent states:

  1. A structural-zero state, where the response is forced to be zero.
  2. A count-generating state, where the response follows an ordinary Poisson distribution and can still equal zero by chance.

To represent this idea, let’s define a latent indicator \(S_i\) which will work as an auxiliary variable to represent the presence of a structural zero. We have then that \(S_i = 1\) means that observation \(i\) belongs to the structural-zero state, and \(S_i = 0\) means that observation \(i\) belongs to the Poisson count-generating state. Let

\[S_i \sim \operatorname{Bernoulli}(\pi_i), \tag{12.10}\]

where \(\pi_i = P(S_i = 1)\) is the probability that observation \(i\) belongs to the structural-zero state. Conditional on this latent state, the response is generated as follows:

\[Y_i \mid S_i = \begin{cases} 0, & \text{if } S_i = 1, \\ \operatorname{Poisson}(\lambda_i), & \text{if } S_i = 0. \end{cases} \tag{12.11}\]

The parameter \(\lambda_i > 0\) is the Poisson mean in the count-generating state. The structural-zero state is important because it adds zeros that cannot be explained by the ordinary Poisson process alone. In other words, some zeros are structural zeros, while other zeros are ordinary sampling zeros generated by the Poisson distribution.

Using Equation 12.10 and Equation 12.11, the probability of observing zero can be built by separating the two latent states. The event \(Y_i = 0\) can happen in two ways:

  1. the observation belongs to the structural-zero state, or
  2. the observation belongs to the count-generating state and the Poisson random variable happens to equal zero.

The law of total probability gives

\[\begin{aligned} P(Y_i = 0) &= P(Y_i = 0, S_i = 1) + P(Y_i = 0, S_i = 0) \\[6pt] &= \underbrace{P(S_i = 1)}_{\substack{\text{structural-zero} \\ \text{state}}} + \underbrace{P(S_i = 0)}_{\substack{\text{count-generating} \\ \text{state}}} \underbrace{P(Y_i = 0 \mid S_i = 0)}_{\substack{\text{ordinary Poisson} \\ \text{zero}}} \\[6pt] &= \underbrace{\pi_i}_{\substack{\text{extra-zero} \\ \text{probability}}} + \underbrace{(1 - \pi_i)}_{\substack{\text{probability of being} \\ \text{in the count state}}} \quad \cdot \quad \underbrace{\exp(-\lambda_i)}_{\substack{\text{Poisson probability} \\ \text{of zero}}} \\[6pt] &= \pi_i + (1 - \pi_i)\exp(-\lambda_i). \end{aligned} \tag{12.12}\]

The first term is the extra mass placed at zero by the structural-zero state. The second term is the ordinary Poisson zero probability, but it is weighted by \(1 - \pi_i\) because it can occur only among observations in the count-generating state.

For a positive count \(y_i = 1, 2, 3, \ldots\), the structural-zero state cannot produce the observed value. Therefore, the only contributing path is the count-generating state followed by a Poisson draw equal to \(y_i\):

\[\begin{aligned} P(Y_i = y_i) &= P(Y_i = y_i, S_i = 1) + P(Y_i = y_i, S_i = 0) \\[6pt] &= \underbrace{P(S_i = 1)P(Y_i = y_i \mid S_i = 1)}_{\substack{=\,0 \\ \text{structural-zero state cannot} \\ \text{produce a positive count}}} + \underbrace{P(S_i = 0)}_{\substack{\text{count-generating} \\ \text{state}}} \underbrace{P(Y_i = y_i \mid S_i = 0)}_{\substack{\text{Poisson probability} \\ \text{of } y_i}} \\[6pt] &= 0 + \underbrace{(1 - \pi_i)}_{\substack{\text{probability of being} \\ \text{in the count state}}} \quad \cdot \quad \underbrace{\frac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!}}_{\substack{\text{Poisson PMF} \\ \text{at } y_i}} \\[6pt] &= (1 - \pi_i)\frac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!}, \qquad y_i = 1, 2, 3, \ldots \end{aligned} \tag{12.13}\]

Equations Equation 12.12 and Equation 12.13 define the Zero-Inflated Poisson probability model.

More formally, this distribution is represented as the following Probability Mass Function (PMF):

\[P(Y_i=y_i)= \begin{cases} \pi_i+(1-\pi_i)\exp(-\lambda_i), & \text{if } y_i = 0 \\[6pt] (1-\pi_i)\dfrac{\exp(-\lambda_i) \lambda_i^{y_i}}{y_i!}, & \text{if } y_i = 1, 2, 3 \dots \end{cases} \tag{12.14}\]

This also shows why the ZIP model can produce more zeros than an ordinary Poisson model: the zero probability is not only \(\exp(-\lambda_i)\), but \(\pi_i + (1 - \pi_i)\exp(-\lambda_i)\).

The conditional mean under this model is

\[\mathbb{E}(Y_i) = \sum_{y_i=0}^\infty y_i P(Y_i=y_i) = (1 - \pi_i)\lambda_i. \tag{12.15}\]

Thus, the expected count depends on both components. A larger \(\lambda_i\) increases the expected count among observations in the count-generating state, while a larger \(\pi_i\) lowers the marginal expected count by moving more observations into the structural-zero state.

Tip on deriving the expected value of a ZIP random variable

A convenient way to derive the expected value of a Zero-Inflated Poisson random variable is to start directly from its PMF and then notice that the zero term contributes nothing to the expectation.

Suppose that, for policyholder \(i\),

\[P(Y_i = y_i) = \begin{cases} \pi_i + (1 - \pi_i)\exp(-\lambda_i), & y_i = 0, \\[6pt] (1 - \pi_i)\dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!}, & y_i = 1, 2, 3, \ldots \end{cases}\]

where \(\pi_i\) is the probability of belonging to the structural-zero state, and \(\lambda_i\) is the Poisson mean in the count-generating state.

The expectation is

\[\mathbb{E}(Y_i) = \sum_{y_i = 0}^{\infty} y_i P(Y_i = y_i).\]

The first term of this sum corresponds to \(y_i = 0\). Since it is multiplied by zero, it drops out:

\[\mathbb{E}(Y_i) = \sum_{y_i = 1}^{\infty} y_i (1 - \pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!}.\]

Now factor out the terms that do not depend on \(y_i\):

\[\mathbb{E}(Y_i) = (1 - \pi_i)\exp(-\lambda_i) \sum_{y_i = 1}^{\infty} \dfrac{y_i\lambda_i^{y_i}}{y_i!}.\]

Since

\[\dfrac{y_i}{y_i!} = \dfrac{1}{(y_i - 1)!},\]

we can rewrite the sum as

\[\mathbb{E}(Y_i) = (1 - \pi_i)\exp(-\lambda_i) \sum_{y_i = 1}^{\infty} \dfrac{\lambda_i^{y_i}}{(y_i - 1)!}.\]

Now change the index by letting \(p = y_i - 1\). When \(y_i = 1\), \(p = 0\), so

\[\mathbb{E}(Y_i) = (1 - \pi_i)\exp(-\lambda_i) \sum_{p = 0}^{\infty} \dfrac{\lambda_i^{p + 1}}{p!}.\]

Factor out one \(\lambda_i\) from \(\lambda_i^{p+1}\):

\[\mathbb{E}(Y_i \mid \mathbf{x}_i) = (1 - \pi_i)\exp(-\lambda_i) \sum_{p = 0}^{\infty} \dfrac{\lambda_i^{p}\lambda_i}{p!} = (1 - \pi_i)\exp(-\lambda_i)\lambda_i \sum_{p = 0}^{\infty} \dfrac{\lambda_i^p}{p!}.\]

Finally, recall the exponential McLaurin series expansion

\[\exp(x) = \sum_{n = 0}^{\infty} \dfrac{x^n}{n!}\] where \(x\) is equivalent to \(\lambda_i\), and \(n\) is equivalent to \(p\).

Therefore,

\[\mathbb{E}(Y_i) = (1 - \pi_i)\exp(-\lambda_i)\lambda_i\exp(\lambda_i) = (1 - \pi_i)\exp(-\lambda_i + \lambda_i) \cdot \lambda_i = (1 - \pi_i)\lambda_i.\]

So, for a ZIP model,

\[\boxed{ \mathbb{E}(Y_i) = (1 - \pi_i)\lambda_i }\]

This result is intuitive: the count-generating Poisson process has mean \(\lambda_i\), but it is active only with probability \(1 - \pi_i\). The structural-zero group contributes no counts to the expectation.

12.7.2 Marginal variance of the ZIP response

The marginal variance also depends on both ZIP components. Conditional on the covariates,

\[ \operatorname{Var}(Y_i \mid \mathbf{x}_i) = (1-\pi_i)\lambda_i \left( 1+\pi_i\lambda_i \right). \tag{12.16}\]

The first factor,

\[ (1-\pi_i)\lambda_i, \]

is the marginal mean from Equation 12.15. The additional multiplier,

\[ 1+\pi_i\lambda_i, \]

captures the extra variability created by mixing a structural-zero state with a Poisson count-generating state. When \(\pi_i=0\), the ZIP model reduces to an ordinary Poisson distribution and Equation 12.16 reduces to \(\operatorname{Var}(Y_i\mid\mathbf{x}_i)=\lambda_i\).

When \(\pi_i>0\) and \(\lambda_i>0\),

\[ \operatorname{Var}(Y_i \mid \mathbf{x}_i) > \mathbb{E}(Y_i \mid \mathbf{x}_i). \]

Thus, zero inflation creates marginal overdispersion relative to the ZIP marginal mean. This does not mean that every source of overdispersion is adequately explained by a ZIP model; remaining positive-count heterogeneity may still motivate alternatives such as a Zero-Inflated Negative Binomial model.

Tip on deriving the variance of a ZIP random variable

A convenient derivation uses the law of total variance and the latent state \(S_i\) introduced in Equation 12.10:

\[ \operatorname{Var}(Y_i \mid \mathbf{x}_i) = \mathbb{E}\!\left[ \operatorname{Var}(Y_i \mid S_i,\mathbf{x}_i) \mid \mathbf{x}_i \right] + \operatorname{Var}\!\left[ \mathbb{E}(Y_i \mid S_i,\mathbf{x}_i) \mid \mathbf{x}_i \right]. \]

We evaluate the two terms separately.

For the first term, the structural-zero state has variance zero, while the count-generating state has Poisson variance \(\lambda_i\). Therefore,

\[ \begin{aligned} \mathbb{E}\!\left[ \operatorname{Var}(Y_i \mid S_i,\mathbf{x}_i) \mid \mathbf{x}_i \right] &= \pi_i(0) + (1-\pi_i)\lambda_i \\ &= (1-\pi_i)\lambda_i. \end{aligned} \]

For the second term, the conditional mean equals zero in the structural-zero state and \(\lambda_i\) in the count-generating state. Hence,

\[ \mathbb{E}(Y_i \mid S_i,\mathbf{x}_i) = \begin{cases} 0, & S_i=1,\\[4pt] \lambda_i, & S_i=0. \end{cases} \]

This two-point random quantity has mean

\[ \pi_i(0)+(1-\pi_i)\lambda_i = (1-\pi_i)\lambda_i, \]

and variance

\[ \begin{aligned} \operatorname{Var}\!\left[ \mathbb{E}(Y_i \mid S_i,\mathbf{x}_i) \mid \mathbf{x}_i \right] &= \pi_i \left[ 0-(1-\pi_i)\lambda_i \right]^2 \\ &\quad+ (1-\pi_i) \left[ \lambda_i-(1-\pi_i)\lambda_i \right]^2 \\ &= \pi_i(1-\pi_i)^2\lambda_i^2 + (1-\pi_i)\pi_i^2\lambda_i^2 \\ &= \pi_i(1-\pi_i)\lambda_i^2. \end{aligned} \]

Adding the two parts gives

\[ \begin{aligned} \operatorname{Var}(Y_i \mid \mathbf{x}_i) &= (1-\pi_i)\lambda_i + \pi_i(1-\pi_i)\lambda_i^2 \\ &= (1-\pi_i)\lambda_i \left( 1+\pi_i\lambda_i \right). \end{aligned} \]

Therefore,

\[ \boxed{ \operatorname{Var}(Y_i \mid \mathbf{x}_i) = (1-\pi_i)\lambda_i \left( 1+\pi_i\lambda_i \right) }. \]

The first term represents expected within-state Poisson variability. The second represents between-state variability created by mixing a certain-zero state with a positive-mean count state.

12.7.3 Modelling the parameters with covariates

Now suppose that each observational unit has \(k\) candidate covariates. A compact covariate vector can be written as

\[\mathbf{x}_i = (1, x_{1,i}, x_{2,i}, \ldots, x_{k,i})^\top, \tag{12.17}\]

The main implication of combining a structural-zero state with a count-generating state is that the model has two systematic components instead of one. One component describes the structural-zero probability \(\pi_i\) from Equation 12.10, and the other describes the Poisson mean \(\lambda_i\) from Equation 12.11. This is the main difference from the single-component GLM examples introduced earlier in the cookbook.

For this chapter, we use \(\alpha\) coefficients for the structural-zero component and \(\beta\) coefficients for the count component.

The structural-zero probability is modelled with a logit link:

\[\operatorname{logit}(\pi_i) = \log\left(\frac{\pi_i}{1 - \pi_i}\right) = \alpha_0 + \alpha_1x_{1,i} + \alpha_2x_{2,i} + \cdots + \alpha_kx_{k,i}. \tag{12.18}\]

The fraction inside the logarithm,

\[\frac{\pi_i}{1 - \pi_i},\]

is an odds. In this ZIP setting, it compares the probability of belonging to the structural-zero state, \(\pi_i\), with the probability of not belonging to that state, \(1 - \pi_i\). In other words, the logit link models the log of the ratio

\[\frac{\text{probability of structural-zero membership}}{\text{probability of count-generating membership}}.\]

The right-hand side of Equation 12.18 is the linear systematic component. It is called linear because the coefficients enter additively on the link-function scale: an intercept plus one coefficient-weighted contribution from each covariate. The model is not claiming that \(\pi_i\) itself is a linear function of the covariates. Instead, it claims that the log-odds of structural-zero membership are linear in the covariates.

Alternatively we can also define the \(\boldsymbol{\alpha}\) vector as

\[\boldsymbol{\alpha} = (\alpha_0, \alpha_{1}, \alpha_{2}, \ldots, \alpha_{k})^\top, \tag{12.19}\]

and in matrix-vector product form, the same equation is

\[\operatorname{logit}(\pi_i) = \mathbf{x}_i^\top \boldsymbol{\alpha}. \tag{12.20}\]

Equivalently,

\[\pi_i = \frac{\exp(\mathbf{x}_i^\top \boldsymbol{\alpha})}{1 + \exp(\mathbf{x}_i^\top \boldsymbol{\alpha})}. \tag{12.21}\]

A positive \(\alpha_j\) means that larger values of \(x_{j,i}\) are associated with higher log-odds of belonging to the structural-zero state, holding the other covariates fixed. On the exponential scale, \(\exp(\alpha_j)\) is an odds ratio for structural-zero membership. The exact interpretation depends on the type of covariate:

  • If \(x_{j,i}\) is continuous, then \(\alpha_j\) is the change in the log-odds of structural-zero membership for a one-unit increase in that covariate, holding all other covariates fixed. In practice, the one-unit change should be chosen carefully. For example, a one-kilometre change in annual mileage may be too small to communicate clearly, so a later interpretation may use \(10{,}000\alpha_j\) and \(\exp(10{,}000\alpha_j)\) instead.
  • If \(x_{j,i}\) is an ordered discrete or integer-valued covariate, then \(\alpha_j\) is still interpreted as a one-unit increase, but the unit has the meaning of the variable. For example, if vehicle age is measured in years, then \(\alpha_j\) is the change in log-odds associated with one additional year of vehicle age, holding the other covariates fixed.
  • If \(x_{j,i}\) is a binary indicator, then \(\alpha_j\) compares the group coded \(1\) with the group coded \(0\). For example, if prior_claims is coded as \(1\) for prior claims and \(0\) for no prior claims, then \(\exp(\alpha_j)\) is the structural-zero odds ratio for policyholders with prior claims relative to policyholders without prior claims, holding the other covariates fixed.
  • If \(x_{j,i}\) represents a nominal categorical variable with more than two categories, the interpretation depends on the dummy or indicator coding. Each coefficient compares one category with the reference category, not with a one-unit numerical increase. For instance, if vehicle type had categories such as sedan, SUV, and truck, and sedan were the reference category, then the SUV coefficient would compare SUVs with sedans, holding the other covariates fixed.

The Poisson count mean is modelled with a log link:

\[\log(\lambda_i) = \beta_0 + \beta_1x_{1,i} + \beta_2x_{2,i} + \cdots + \beta_mx_{m,i}. \tag{12.22}\]

The log link plays a similar role for the count-generating mean. The left-hand side, \(\log(\lambda_i)\), is the logarithm of the Poisson mean among observations that remain in the count-generating state. The right-hand side is another linear systematic component: an intercept plus coefficient-weighted covariate contributions. This means that the model is linear on the log-mean scale, while \(\lambda_i\) itself remains positive after applying the inverse link in Equation 12.25.

Alternatively we can also define the \(\boldsymbol{\beta}\) vector as

\[\boldsymbol{\beta} = (\beta_0, \beta_{1}, \beta_{2}, \ldots, \beta_{k})^\top, \tag{12.23}\]

and in matrix-vector product form, the same equation is

\[\log(\lambda_i) = \mathbf{x}_i^\top \boldsymbol{\beta}. \tag{12.24}\]

Equivalently,

\[\lambda_i = \exp(\mathbf{x}_i^\top \boldsymbol{\beta}). \tag{12.25}\]

A positive \(\beta_j\) means that larger values of \(x_{j,i}\) are associated with a higher log mean in the Poisson count-generating state, holding the other covariates fixed. On the exponential scale, \(\exp(\beta_j)\) is a rate ratio for the Poisson mean among observations that remain in the count-generating state. As with the \(\alpha\) coefficients, the exact interpretation depends on the type of covariate:

  • If \(x_{j,i}\) is continuous, then \(\beta_j\) is the change in the log mean count for a one-unit increase in the covariate, holding the other covariates fixed. The rate ratio for a larger change \(c\) is \(\exp(c\beta_j)\).
  • If \(x_{j,i}\) is an ordered discrete or integer-valued covariate, then \(\beta_j\) is the change in the log mean count for one additional unit of that variable. For example, if vehicle age is measured in years, then \(\exp(\beta_j)\) is the fitted multiplicative change in the count-generating mean for one additional year of vehicle age.
  • If \(x_{j,i}\) is a binary indicator, then \(\exp(\beta_j)\) compares the fitted count-generating mean for the group coded \(1\) with the group coded \(0\), holding the other covariates fixed.
  • If \(x_{j,i}\) represents a nominal categorical variable with more than two categories, each dummy-variable coefficient compares that category with the reference category. The coefficient should not be read as a numerical one-unit increase through the category labels.

In the current insurance-claims dataset, the available categorical variables are binary indicators. However, this nominal-categorical distinction is important for future applications of ZIP regression where variables such as region, policy type, vehicle class, or occupation group may enter the model.

Putting both components together shows how the two link functions determine the marginal mean of the observed count response. The count component contributes \(\lambda_i = \exp(\mathbf{x}_i^\top\boldsymbol{\beta})\), while the zero-inflation component contributes the probability of not being in the structural-zero state, \(1 - \pi_i\). Therefore, using Equation 12.15, Equation 12.21, and Equation 12.25, the overall mean can be written as follows:

\[\begin{aligned} \mathbb{E}(Y_i \mid \mathbf{x}_i) &= (1-\pi_i)\lambda_i \\[10pt] &= \bigg(1-\frac{\exp(\mathbf{x}_i^\top \boldsymbol{\alpha})}{1 + \exp(\mathbf{x}_i^\top \boldsymbol{\alpha})}\bigg)\cdot \exp(\mathbf{x}_i^\top \boldsymbol{\beta})\\[10pt] &=\bigg(\frac{1}{1+\exp(\mathbf{x}_i^\top \boldsymbol{\alpha})} \bigg)\cdot \exp(\mathbf{x}_i^\top \boldsymbol{\beta})\\[10pt] &=\frac{\exp(\mathbf{x}_i^\top \boldsymbol{\beta})}{1+\exp(\mathbf{x}_i^\top \boldsymbol{\alpha})}\\[10pt] &=\dfrac{\exp(\beta_0+\beta_1 x_{1,i} + \beta_2 x_{2,i} + \dots +\beta_k x_{k,i})}{1+\exp(\alpha_0+\alpha_1 x_{1,i} + \alpha_2 x_{2,i} + \dots +\alpha_k x_{k,i})} \end{aligned} \tag{12.26}\]

Heads-up on using the same covariates in both components!

The notation above uses the same covariate vector \(\mathbf{x}_i\) in both components for simplicity and for consistency with the running example. In practice, the zero-inflation component and the count component can use different covariate sets. For example, one component could use all candidate regressors, while the other uses a smaller subset selected for substantive reasons: nature of the problem, feature selection, reducing model complexity, etc.

12.7.4 Assumptions behind the ZIP formulation

The ZIP model is useful only when its two-component story is plausible. In this chapter, the main assumptions are:

  • Count response: The response \(Y_i\) is a nonnegative integer-valued count. This is the scale assumed by the ZIP PMF in Equation 12.14. In the running example, claims satisfies this requirement because it records \(0, 1, 2, \ldots\) claims.

  • Independent observations: Conditional on the covariates and model parameters, observations are treated as independent. In practical terms, the model is not explicitly accounting for repeated measurements on the same policyholder, household clustering, geographic clustering, or time-series dependence. If those structures exist, the basic ZIP model may need to be extended.

  • Two zero sources: It is substantively plausible that some zeros are structural zeros, while other zeros arise from the Poisson count-generating process. This is the distinction encoded by \(S_i\) in Equation 12.10 and Equation 12.11. Without a credible two-source explanation for zeros, the extra zero component may be difficult to justify.

  • Correct component interpretation: The zero-inflation component models \(\pi_i\), the probability of belonging to the structural-zero state. The count component models \(\lambda_i\), the Poisson mean among observations that remain in the count-generating state. These are not interchangeable. A covariate in the \(\alpha\) component changes the structural-zero mechanism; a covariate in the \(\beta\) component changes the count-generating mean.

  • Link-function structure: The logit link in Equation 12.18 is assumed to be a reasonable way to connect covariates to \(\pi_i\), and the log link in Equation 12.22 is assumed to be a reasonable way to connect covariates to \(\lambda_i\). This means the model is additive and linear on the link scales, not necessarily on the original probability or mean scales.

  • Poisson count-generating state: Conditional on being in the count-generating state, the Poisson mean-variance relationship is a reasonable starting point. The ZIP model adds extra zeros, but it does not by itself solve every kind of overdispersion in the positive-count process.

  • Enough information for two components: There are enough positive counts, enough zeros, and enough covariate variation to estimate both the \(\alpha\) and \(\beta\) components without severe instability. Because both components are estimated at the same time, sparse data or weakly separated groups can make the two sets of coefficients difficult to identify precisely.

If the count-generating part is still strongly overdispersed after accounting for excess zeros, then a Zero-Inflated Negative Binomial model may be a more appropriate extension. If there is no substantive reason to distinguish structural zeros from ordinary sampling zeros, then a simpler count model may be easier to justify and communicate.

Heads-up on severe instability in ZIP models

In this context, severe instability means that the two-component ZIP model does not have enough information to estimate the structural-zero and count-generating mechanisms reliably. Symptoms may include convergence warnings, extremely large coefficient estimates, very wide standard errors, fitted probabilities very close to \(0\) or \(1\), or coefficient estimates that change dramatically after small changes to the data or covariate set.

This matters because the ZIP model estimates both \(\boldsymbol{\alpha}\) and \(\boldsymbol{\beta}\). If the data contain many zeros but very few positive counts, the model may struggle to decide whether a covariate belongs mainly in the structural-zero story, the count-generating story, or both. In those cases, coefficient tables should be interpreted cautiously, and predicted probabilities, fitted means, sensitivity checks, or simpler comparison models may be more informative.

Tip on Bayesian extensions for limited data

The ZIP model has a naturally hierarchical interpretation: an observation first belongs either to a structural-zero state or to a count-generating state, and then the count-generating state follows a Poisson model. When the dataset is limited, this two-component structure can make the fitted coefficients and their standard errors sensitive to small changes in the data.

A Bayesian version of ZIP regression can sometimes help in this situation by placing prior distributions on the \(\alpha\) and \(\beta\) coefficients. If those priors are sufficiently informative, relevant to the problem context, and carefully justified, they can regularize unstable estimates and make the uncertainty in both components more explicit.

That said, a Bayesian ZIP model is not automatically better. Weak or poorly chosen priors may not solve the instability problem, and overly strong priors can dominate the data. Bayesian ZIP regression is therefore a useful extension to know about, especially when data are sparse, but exploring it in detail is outside the scope of this chapter and outside the main purpose of this cookbook.

12.7.5 Interpretation caveats

This can produce results that feel counter-intuitive at first. For example, a covariate could have a positive \(\alpha_j\) and a positive \(\beta_j\). In that case, higher values of the covariate are associated with higher odds of being in the structural-zero state, but also with a higher expected count among observations that are not structural zeros. These statements are not contradictory because they refer to different latent parts of the model.

An example could be a public-health outreach programme. Suppose the response is the number of emergency department visits in a year, and one covariate indicates whether a person is enrolled in an intensive care-management programme. Enrollment might have a positive zero-inflation coefficient if many enrolled people are stable, closely monitored, and therefore unlikely to visit the emergency department at all. At the same time, enrollment might have a positive count-component coefficient because, among the enrolled people who are not in the structural-zero group, many are high-need patients who can have repeated emergency visits. The same covariate can therefore point toward more zeros in one latent subgroup and larger counts in the remaining at-risk subgroup.

A concrete insurance example, using a covariate not present in the current dataset, is enrollment in a dash-cam-based safe-driving programme. Such a programme could be associated with higher odds of structural-zero membership if many enrolled drivers are cautious drivers who rarely file claims. However, among enrolled drivers who are still in the count-generating state, claim counts could be higher if the programme is especially attractive to high-exposure drivers, fleet drivers, or drivers who report minor incidents more consistently because the dash-cam system records them. In that case, the zero-inflation coefficient and the count-component coefficient could both be positive without implying a contradiction.

The marginal expected count in Equation 12.15 depends on both \(\pi_i\) and \(\lambda_i\). Therefore, a coefficient in one component should not automatically be interpreted as the total effect of a covariate on the observed count. For a continuous covariate that appears in both components, the marginal mean combines the two linear predictors through Equation 12.26, so the direction of the overall fitted mean can depend on both \(\alpha_j\) and \(\beta_j\), as well as on the current value of \(\pi_i\).

Tip on reading ZIP coefficients

A positive count-component coefficient and a positive zero-inflation coefficient do not mean the model is wrong. They may indicate a population where a covariate separates two kinds of observations: a subgroup increasingly likely to have no events at all, and a remaining at-risk subgroup with larger expected counts. This is one reason predicted probabilities, fitted means, and marginal effects are often more intuitive than coefficient tables alone.

12.7.6 ZIP model for the insurance-claims running example

We now return to the notation from Table 12.17. For policyholder \(i\), the response is \(Y_i = \texttt{claims}_i\), and the six candidate covariates are

\[\mathbf{x}_i = \left(1, x_{1,i}, x_{2,i}, x_{3,i}, x_{4,i}, x_{5,i}, x_{6,i}\right)^\top, \tag{12.27}\]

where \(x_{1,i}\) is driver_age, \(x_{2,i}\) is annual_mileage, \(x_{3,i}\) is vehicle_age, \(x_{4,i}\) is male, \(x_{5,i}\) is urban_area, and \(x_{6,i}\) is prior_claims.

For the zero-inflation component, we write

\[\log\left(\frac{\pi_i}{1 - \pi_i}\right) = \alpha_0 + \alpha_1x_{1,i} + \alpha_2x_{2,i} + \alpha_3x_{3,i} + \alpha_4x_{4,i} + \alpha_5x_{5,i} + \alpha_6x_{6,i}. \tag{12.28}\]

Here, \(\pi_i\) is the probability that policyholder \(i\) belongs to the structural-zero group. For example, \(\alpha_2\) describes how annual mileage is associated with the log-odds of being in that structural-zero group, holding the other covariates fixed.

For the count component, we write

\[\log(\lambda_i) = \beta_0 + \beta_1x_{1,i} + \beta_2x_{2,i} + \beta_3x_{3,i} + \beta_4x_{4,i} + \beta_5x_{5,i} + \beta_6x_{6,i}. \tag{12.29}\]

Here, \(\lambda_i\) is the expected number of claims for policyholder \(i\) conditional on being in the count-generating state. For example, \(\beta_2\) describes how annual mileage is associated with the log mean claim count among policyholders who remain in the count-generating process, holding the other covariates fixed.

Together, Equation 12.28 and Equation 12.29 define the working ZIP model for the insurance-claims example. This specification uses the same six covariates in both components, which is useful for teaching because it lets us compare how the same regressor can behave differently in the structural-zero and count-generating parts of the model.

The combination of these two would look like this for the mean response, recalling Equation 12.26:

\[\mathbb{E}(Y_i \mid x_{1,i}, x_{2,i}, \dots, x_{6,i}) = \dfrac{\exp(\beta_0+\beta_1 x_{1,i} + \dots + \beta_6 x_{6,i})}{1 + \exp(\alpha_0+\alpha_1 x_{1,i} + \dots + \alpha_6 x_{6,i})} \tag{12.30}\]

12.8 Estimation

The general likelihood framework and the role of Maximum Likelihood Estimation (MLE) were introduced in Section 2.3. Binary Logistic Regression and Classical Poisson Regression then applied that framework to the single-component models in Chapter 8 and Chapter 10. Here, we focus only on what changes for a Zero-Inflated Poisson (ZIP) model: the structural-zero coefficients \(\boldsymbol{\alpha}\) and the count-component coefficients \(\boldsymbol{\beta}\) must be estimated jointly.

Let \(\mathbf{y}=(y_1,\ldots,y_n)^\top\) denote the observed response vector, and let \(\mathbf{X}\) denote the design matrix whose \(i\)th row is \(\mathbf{x}_i^\top\). Under the working specification developed in the preceding section, the same covariate vector enters both ZIP components. The estimation argument extends directly to specifications that use different covariate sets in the two components.

12.8.1 The observed-data likelihood

The latent variable \(S_i\) indicates whether observation \(i\) belongs to the structural-zero state or the Poisson count-generating state. Although \(S_i\) is useful for defining the model, its value is not observed.

A positive response identifies the latent state indirectly: when \(y_i>0\), the observation must have come from the count-generating state. An observed zero is different because it may be either a structural zero or an ordinary Poisson zero. Estimation must therefore use the marginal ZIP PMF in Equation 12.14, where the latent state has already been summed out.

To write the two PMF branches compactly, define the observed zero indicator

\[ d_i = \mathbb{I}(y_i=0) = \begin{cases} 1, & y_i=0,\\ 0, & y_i>0. \end{cases} \tag{12.31}\]

The quantity \(d_i\) records whether the observed response is zero. It should not be confused with \(S_i\): we observe \(d_i\), but for a zero response we do not observe which latent state produced it.

The likelihood contribution from observation \(i\) is

\[ \begin{aligned} \mathcal{L}_i \left( \boldsymbol{\alpha},\boldsymbol{\beta}; y_i,\mathbf{x}_i \right) ={}& \left[ \pi_i+(1-\pi_i)\exp(-\lambda_i) \right]^{d_i} \\[4pt] &\times \left[ (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!} \right]^{1-d_i}. \end{aligned} \tag{12.32}\]

The semicolon separates the unknown parameters being varied from the observed data being treated as fixed when the expression is viewed as a likelihood.

The indicator exponents select the appropriate ZIP probability. When \(y_i=0\), \(d_i=1\) and the contribution is

\[ \mathcal{L}_i = \underbrace{\pi_i}_{\text{structural-zero route}} + \underbrace{(1-\pi_i)\exp(-\lambda_i)}_{\text{Poisson-zero route}}. \]

When \(y_i>0\), \(d_i=0\) and only the count-generating state can contribute:

\[ \mathcal{L}_i = (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!}. \]

Assuming conditional independence across observations, the observed-data likelihood is the product of the individual contributions:

\[ \begin{aligned} \mathcal{L} \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) = \prod_{i=1}^{n} &\left[ \pi_i+(1-\pi_i)\exp(-\lambda_i) \right]^{d_i} \\ &\times \left[ (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!} \right]^{1-d_i}. \end{aligned} \tag{12.33}\]

Equivalently, separating the zero and positive observations gives

\[ \begin{aligned} \mathcal{L} \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) ={}& \prod_{i:y_i=0} \left[ \pi_i+(1-\pi_i)\exp(-\lambda_i) \right] \\[6pt] &\times \prod_{i:y_i>0} \left[ (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!} \right]. \end{aligned} \tag{12.34}\]

This separated expression highlights the feature that distinguishes ZIP estimation from Classical Poisson estimation. Every positive response has a weighted Poisson contribution, whereas every observed zero combines two possible sources.

12.8.2 The ZIP log-likelihood

As in Section 2.3, it is more convenient to maximize the logarithm of the likelihood. Taking logs of Equation 12.33 gives

\[ \begin{aligned} \ell \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) ={}& \sum_{i=1}^{n} d_i \log\left[ \pi_i+(1-\pi_i)\exp(-\lambda_i) \right] \\[6pt] &+ \sum_{i=1}^{n} (1-d_i) \log\left[ (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!} \right]. \end{aligned} \tag{12.35}\]

Expanding the positive-count term produces

\[ \begin{aligned} \ell \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) ={}& \sum_{i=1}^{n} d_i \log\left[ \pi_i+(1-\pi_i)\exp(-\lambda_i) \right] \\[6pt] &+ \sum_{i=1}^{n} (1-d_i) \left[ \log(1-\pi_i) -\lambda_i +y_i\log(\lambda_i) -\log(y_i!) \right]. \end{aligned} \tag{12.36}\]

At this stage, the log-likelihood is written in terms of the observation-specific parameters \(\pi_i\) and \(\lambda_i\). Estimating the regression coefficients requires substituting the logit and log inverse links from Equation 12.21 and Equation 12.25.

12.8.3 Substituting the regression components

From the inverse-logit expression,

\[ 1-\pi_i = \dfrac{1}{1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})}, \]

and the Poisson mean is

\[ \lambda_i = \exp(\mathbf{x}_i^\top\boldsymbol{\beta}). \]

For an observed zero, substitution into the ZIP zero probability gives

\[ \begin{aligned} \pi_i+(1-\pi_i)\exp(-\lambda_i) &= \dfrac{\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})} {1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})} + \dfrac{\exp\left[-\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right]} {1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})} \\[6pt] &= \dfrac{ \exp(\mathbf{x}_i^\top\boldsymbol{\alpha}) + \exp\left[-\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right] } {1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})}. \end{aligned} \tag{12.37}\]

For an observed positive count, the corresponding contribution becomes

\[ \begin{aligned} (1-\pi_i) \dfrac{\exp(-\lambda_i)\lambda_i^{y_i}}{y_i!} &= \dfrac{1}{1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})} \dfrac{ \exp\left[-\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right] \left[\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right]^{y_i} }{y_i!} \\[6pt] &= \dfrac{ \exp\left[ -\exp(\mathbf{x}_i^\top\boldsymbol{\beta}) +y_i\mathbf{x}_i^\top\boldsymbol{\beta} \right] } {\left[1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha})\right]y_i!}. \end{aligned} \tag{12.38}\]

Substituting these expressions into Equation 12.35 gives the coefficient-based ZIP log-likelihood:

\[ \begin{aligned} \ell \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) = \sum_{i=1}^{n} \Bigg[ &-\log\left\{ 1+\exp(\mathbf{x}_i^\top\boldsymbol{\alpha}) \right\} \\ &+ d_i \log\Bigg\{ \exp(\mathbf{x}_i^\top\boldsymbol{\alpha}) + \exp\left[-\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right] \Bigg\} \\ &+ (1-d_i) \Bigg\{ -\exp(\mathbf{x}_i^\top\boldsymbol{\beta}) +y_i\mathbf{x}_i^\top\boldsymbol{\beta} -\log(y_i!) \Bigg\} \Bigg]. \end{aligned} \tag{12.39}\]

The term \(-\log(y_i!)\) does not depend on either coefficient vector. It may therefore be omitted while numerically locating the maximizing coefficient values. It must be retained when calculating the complete maximized log-likelihood and likelihood-based quantities such as the Akaike Information Criterion (AIC) or Bayesian Information Criterion (BIC).

12.8.4 The joint optimization problem

The Maximum Likelihood Estimates are the coefficient values that jointly maximize Equation 12.39:

\[ \boxed{ \left( \widehat{\boldsymbol{\alpha}}, \widehat{\boldsymbol{\beta}} \right) = \underset{\boldsymbol{\alpha},\boldsymbol{\beta}} {\operatorname{arg\,max}} \; \ell \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right). } \tag{12.40}\]

Equivalently, software may minimize the negative log-likelihood:

\[ \boxed{ \left( \widehat{\boldsymbol{\alpha}}, \widehat{\boldsymbol{\beta}} \right) = \underset{\boldsymbol{\alpha},\boldsymbol{\beta}} {\operatorname{arg\,min}} \left[ -\ell \left( \boldsymbol{\alpha},\boldsymbol{\beta}; \mathbf{y},\mathbf{X} \right) \right]. } \tag{12.41}\]

There is no closed-form solution for these estimates. In particular, the observed-zero term contains

\[ \log\Bigg\{ \exp(\mathbf{x}_i^\top\boldsymbol{\alpha}) + \exp\left[-\exp(\mathbf{x}_i^\top\boldsymbol{\beta})\right] \Bigg\}, \]

which couples the structural-zero and count-component coefficients inside the same logarithm. Consequently, the ZIP model cannot generally be estimated by fitting one ordinary Logistic Regression and one ordinary Poisson Regression separately. Changing either coefficient vector changes the probability assigned to every observed zero, so an iterative numerical optimizer must search over \(\boldsymbol{\alpha}\) and \(\boldsymbol{\beta}\) jointly.

Different software implementations may use different optimization routines, starting values, convergence tolerances, and numerically stable ways to evaluate the logarithmic terms. The fitting process should therefore be checked for successful convergence, finite coefficient estimates, and sensitivity to unusually sparse information in either component.

12.8.5 Estimated uncertainty

Fitting the ZIP model gives us estimates of the coefficients in both components:

  • \(\widehat{\boldsymbol{\alpha}}\) for the structural-zero component; and
  • \(\widehat{\boldsymbol{\beta}}\) for the Poisson count component.

We can collect all these estimates into one parameter vector:

\[ \boldsymbol{\theta} = \begin{pmatrix} \boldsymbol{\alpha}\\ \boldsymbol{\beta} \end{pmatrix}. \tag{12.42}\]

This notation does not mean that each component has only two coefficients. It means that the complete ZIP model has two groups of coefficients. In this model, each group contains an intercept and \(k\) regressor coefficients:

\[ \boldsymbol{\alpha} = (\alpha_0,\alpha_1,\ldots,\alpha_k)^\top \]

and

\[ \boldsymbol{\beta} = (\beta_0,\beta_1,\ldots,\beta_k)^\top. \]

The full ZIP model therefore estimates \(2k+2\) coefficients altogether. Given that we have 6 regressors for both the structural zero and the count components, for our insurance case that will imply a total of 14 parameters.

After finding the Maximum Likelihood Estimates, we also need to measure how uncertain those estimates are. This uncertainty is summarized using standard errors.

The main idea is to examine the shape of the log-likelihood near its maximum:

  • If the log-likelihood has a narrow, sharply defined maximum, small changes in the coefficients reduce the likelihood quickly. The coefficient estimates are then relatively precise, so their standard errors tend to be smaller.
  • If the log-likelihood is fairly flat near its maximum, many nearby coefficient values fit the data almost equally well. The estimates are then less precise, so their standard errors tend to be larger.

The Hessian matrix summarizes this curvature. It contains the second derivatives of the log-likelihood with respect to all the coefficients:

\[ \mathbf{H}(\boldsymbol{\theta}) = \nabla_{\boldsymbol{\theta}}^2 \ell(\boldsymbol{\theta}). \tag{12.43}\]

Because the model is fitted jointly, the Hessian contains information about:

  • relationships among coefficients in the structural-zero component;
  • relationships among coefficients in the count component; and
  • relationships between coefficients from the two different components.

The final group is important because an observed zero provides information about both mechanisms. A zero may be structural, but it may also be an ordinary zero from the Poisson count process. The uncertainty in the two components should therefore be estimated together rather than as if they were unrelated models.

The model-based covariance matrix is estimated by taking the inverse of the negative Hessian evaluated at the fitted coefficients:

\[ \widehat{\operatorname{Var}} \left( \widehat{\boldsymbol{\theta}} \right) = \left[ -\mathbf{H} \left( \widehat{\boldsymbol{\theta}} \right) \right]^{-1}. \tag{12.44}\]

The diagonal entries of this matrix are the estimated variances of the individual coefficient estimates. The standard error of coefficient \(\widehat{\theta}_j\) is the square root of its corresponding diagonal entry:

\[ \operatorname{SE} \left( \widehat{\theta}_j \right) = \sqrt{ \left[ \widehat{\operatorname{Var}} \left( \widehat{\boldsymbol{\theta}} \right) \right]_{jj} }. \tag{12.45}\]

In practice, the software performs these calculations automatically. In R, pscl::zeroinfl() uses the numerical Hessian obtained during optimization. In Python, statsmodels calculates the covariance matrix after likelihood optimization and reports the standard errors through the bse attribute.

These standard errors rely on a large-sample approximation. If the likelihood is very flat, or if the two model components are difficult to distinguish, the Hessian may be nearly singular. In that case, the reported standard errors may be very large or numerically unstable even when the optimizer reports that it converged. For this reason, convergence, coefficient size, standard errors, and sensitivity to starting values should be considered together.

Tip on alternatives when the Hessian approximation is unreliable

The inverse-Hessian standard errors are the usual starting point. In more difficult applications, uncertainty can also be examined using profile-likelihood intervals or bootstrap procedures. These alternatives can be more computationally expensive, so they are usually considered after the basic fitted model and its numerical stability have been reviewed.

The next section applies this joint estimation and uncertainty framework to the insurance-claims training data using R and Python.

12.9 Model Fitting

The estimation section established that the zero-inflation coefficients \(\boldsymbol{\alpha}\) and the count coefficients \(\boldsymbol{\beta}\) must be estimated jointly. We now fit that model using the canonical training data created in Section 12.3.

The working specification uses the same six regressors in both components. This is useful for the running example because it lets us compare how the same policyholder characteristic enters the structural-zero and count-generating mechanisms. The model is fitted only on the training observations. The testing observations remain untouched for the later prediction and final assessment section.

12.9.1 Rescaling continuous regressors for numerical fitting

Before fitting, we express the continuous regressors in the same units that will later be used for interpretation:

  • driver_age_10 represents driver age in units of 10 years;
  • annual_mileage_10k represents annual mileage in units of 10,000 kilometres;
  • vehicle_age_5 represents vehicle age in units of 5 years.

This is a linear change of units, not a change to the underlying statistical model. It improves numerical scaling and makes a one-unit coefficient correspond to a practically meaningful comparison. The binary indicators remain coded as \(0/1\).

Heads-up on scaling and fitted values

Dividing a regressor by a positive constant changes the numerical value and interpretation unit of its coefficient, but it does not change the fitted model when the corresponding coefficient is estimated freely. For example, the coefficient of annual_mileage_10k describes a 10,000-km increase directly. This rescaling is useful because annual mileage is numerically much larger than the other regressors, and poorly scaled design matrices can make likelihood optimization more difficult.

12.9.2 Fitting the ZIP model in R and Python

In the R formula, the terms before the vertical bar define the Poisson count component, while the terms after the vertical bar define the zero-inflation component. In Python, the same distinction is represented by the exog and exog_infl design matrices.

zip_training_r <- train_data |>
  mutate(
    driver_age_10 = driver_age / 10,
    annual_mileage_10k = annual_mileage / 10000,
    vehicle_age_5 = vehicle_age / 5
  )

zip_formula_r <-
  claims ~
    driver_age_10 + annual_mileage_10k + vehicle_age_5 +
    male + urban_area + prior_claims |
    driver_age_10 + annual_mileage_10k + vehicle_age_5 +
    male + urban_area + prior_claims

zip_model_r <- pscl::zeroinfl(
  formula = zip_formula_r,
  data = zip_training_r,
  dist = "poisson",
  link = "logit",
  control = pscl::zeroinfl.control(
    method = "BFGS",
    maxit = 10000,
    trace = FALSE
  )
)

summary(zip_model_r)
zip_training_py = training_data.copy()

zip_training_py["driver_age_10"] = zip_training_py["driver_age"] / 10
zip_training_py["annual_mileage_10k"] = zip_training_py["annual_mileage"] / 10000
zip_training_py["vehicle_age_5"] = zip_training_py["vehicle_age"] / 5

zip_covariates_py = [
    "driver_age_10",
    "annual_mileage_10k",
    "vehicle_age_5",
    "male",
    "urban_area",
    "prior_claims",
]

for col in zip_covariates_py + ["claims"]:
    zip_training_py[col] = pd.to_numeric(
        zip_training_py[col],
        errors="coerce"
    )

zip_training_py = zip_training_py.dropna(
    subset=zip_covariates_py + ["claims"]
).copy()

X_count_py = sm.add_constant(
    zip_training_py[zip_covariates_py].astype(float),
    has_constant="add"
)

X_zero_py = X_count_py.copy()
y_zip_py = zip_training_py["claims"].astype(int)

zip_model_py = ZeroInflatedPoisson(
    endog=y_zip_py,
    exog=X_count_py,
    exog_infl=X_zero_py,
    inflation="logit"
)

zip_result_py = zip_model_py.fit(
    method="bfgs",
    maxiter=1000,
    disp=False,
    full_output=True,
    cov_type="nonrobust"
)

print(zip_result_py.summary())

The two functions use maximum likelihood but expose the components differently. pscl::zeroinfl() labels the count and zero-inflation coefficient blocks separately. statsmodels prefixes zero-inflation terms with inflate_; terms without that prefix belong to the count component.

The fitted models can now be summarized using a common coefficient layout so that the R and Python results are easier to compare.

12.9.3 Fitted coefficient tables

The coefficient tables report estimates and model-based standard errors for both ZIP components. At this stage, the purpose is to verify that the two blocks were estimated and to identify their parameter names. The next major interpretation section will translate the estimates into component-specific odds ratios, rate ratios, and marginal fitted quantities.

Table 12.28: Fitted ZIP coefficient table for the canonical training data using R.
Table 12.29: Fitted ZIP coefficient table for the canonical training data using Python.

The exact formatting and final decimal values may differ slightly across languages because the software implementations can use different starting-value rules, stopping tolerances, derivative calculations, and covariance calculations. The substantive comparison should focus on whether both fits converge to similar maximized log-likelihoods and coefficient ranges, not on requiring every displayed digit to match.

12.9.4 Basic numerical completion checks

A successful optimizer flag is necessary, but it is not sufficient for declaring the fitted ZIP model reliable. The following table records only basic fitting checks: the optimizer, convergence flag, maximized log-likelihood, number of estimated parameters, and whether all reported standard errors are finite.

Table 12.30: Basic ZIP optimization checks for the canonical training fit using R.
Table 12.31: Basic ZIP optimization checks for the canonical training fit using Python.

The training fit is numerically consistent across the two implementations. As shown in Table 12.30 and Table 12.31, both optimizers report convergence, all reported standard errors are finite, and the model contains 14 estimated parameters. The R maximized log-likelihood is -1136, and the Python value agrees to the displayed precision. The coefficient estimates in Table 12.28 and Table 12.29 likewise agree closely in sign and magnitude. These checks support moving to the training-stage diagnostics, but convergence and cross-language agreement alone do not establish that the fitted ZIP distribution adequately represents the data.

Tip on optimization methods for ZIP regression in R and Python

ZIP likelihoods are smooth but can be numerically difficult because every observed zero couples the zero-inflation and count parameters. Different optimization algorithms search the same likelihood surface in different ways.

In R: pscl::zeroinfl() maximizes the likelihood through optim(). Its default method is BFGS, a quasi-Newton method that uses gradients and updates an approximation to the inverse Hessian. zeroinfl() can also pass another optim() method through zeroinfl.control(). For example, Nelder–Mead is derivative-free and can be useful as a slower fallback, while CG uses conjugate-gradient search directions. The package can use an EM algorithm to construct starting values, but the documented zeroinfl() implementation then performs the final maximum-likelihood optimization through optim() (Jackman 2024; Fletcher 1987). See the zeroinfl.control() documentation for the available controls.

In Python: statsmodels.discrete.count_model.ZeroInflatedPoisson.fit() uses BFGS by default and also supports methods including Newton–Raphson, Nelder–Mead, L-BFGS, Powell, conjugate gradient, Newton-conjugate gradient, and SciPy’s generic minimize() interface. L-BFGS is a memory-reduced quasi-Newton method, Newton methods use explicit curvature and can be fast near a well-behaved optimum, and Powell or Nelder–Mead do not require gradients but can require more function evaluations (Seabold and Perktold 2010; Virtanen et al. 2020). See the statsmodels ZIP fitting documentation for the current solver list.

The optimizer should not be selected by whichever method produces the preferred coefficient signs. A reasonable workflow is to use a documented default, inspect convergence and standard errors, and then use one or two alternative methods or starting values as a sensitivity check when the fit appears unstable.

Tip on how the software obtains the reported standard errors

Both fits report model-based standard errors derived from the curvature of the joint ZIP likelihood. In R, the complete covariance matrix is available through

zip_vcov_r <- vcov(zip_model_r)
zip_se_r <- sqrt(diag(zip_vcov_r))

The pscl documentation states that these standard errors are obtained numerically from the Hessian returned by optim() (Jackman 2024).

In Python, the same quantities are available through

zip_vcov_py = zip_result_py.cov_params()
zip_se_py = zip_result_py.bse

By default, statsmodels calculates an inverse-Hessian covariance matrix after likelihood optimization unless Hessian calculation is explicitly skipped. These standard errors are joint: the covariance matrix contains both zero-inflation and count parameters rather than treating the two blocks as unrelated regressions (Seabold and Perktold 2010).

Finite standard errors do not prove that the model is well identified. Very large standard errors, a nearly singular covariance matrix, or strong sensitivity to the optimizer can indicate that the data do not distinguish the two components clearly enough.

This section has fitted the working ZIP model and verified its basic numerical completion. The next sections should assess whether the fitted distribution represents the training data adequately before making final component-level or marginal interpretations.

12.10 Goodness of Fit and Diagnostics

The ZIP model has now been fitted on the canonical training data. Successful numerical optimization is necessary, but it does not by itself establish that the fitted distribution represents the observed counts adequately. We therefore evaluate the complete fitted ZIP distribution before interpreting the coefficients or applying the model to the testing observations.

These diagnostics return to both inquiries introduced in Section 12.2.1:

  • for the inferential inquiry, poor fit can make coefficient-level conclusions misleading;
  • for the predictive inquiry, a model that reproduces only the average count but misses the zero frequency or positive-count distribution may assign poor probabilities to new observations.

The diagnostics in this section use the training data because they remain part of model development and specification assessment.

12.10.1 Diagnostic targets in a ZIP model

For policyholder \(i\), the fitted model provides

\[ \widehat{\pi}_i = \widehat{P}(S_i=1\mid\mathbf{x}_i), \tag{12.46}\]

the fitted probability of structural-zero membership;

\[ \widehat{\lambda}_i = \widehat{\mathbb{E}}(Y_i\mid S_i=0,\mathbf{x}_i), \tag{12.47}\]

the fitted Poisson mean within the count-generating state;

\[ \widehat{\mu}_i = (1-\widehat{\pi}_i)\widehat{\lambda}_i, \tag{12.48}\]

the fitted marginal expected number of claims; and

\[ \widehat{p}_{0,i} = \widehat{\pi}_i + (1-\widehat{\pi}_i)e^{-\widehat{\lambda}_i}, \tag{12.49}\]

the fitted probability of observing zero claims.

The structural-zero state is latent. Therefore, \(\widehat{\pi}_i\) cannot be checked against an observed structural-zero label. The observable calibration target is \(\widehat{p}_{0,i}\) because the dataset records whether \(Y_i=0\), but not which latent mechanism generated that zero.

12.10.2 Computing the fitted diagnostic quantities

zip_training_diagnostics_r <- zip_training_r |>
  mutate(
    fitted_pi = as.numeric(
      predict(zip_model_r, type = "zero")
    ),
    fitted_lambda = as.numeric(
      predict(zip_model_r, type = "count")
    ),
    fitted_mu = as.numeric(
      predict(zip_model_r, type = "response")
    ),
    fitted_p_zero =
      fitted_pi +
      (1 - fitted_pi) * exp(-fitted_lambda),
    fitted_variance =
      (1 - fitted_pi) * fitted_lambda *
      (1 + fitted_pi * fitted_lambda),
    pearson_residual =
      (claims - fitted_mu) / sqrt(fitted_variance)
  )
zip_training_diagnostics_py = zip_training_py.copy()

zip_training_diagnostics_py["fitted_mu"] = zip_result_py.predict(
    which="mean"
)
zip_training_diagnostics_py["fitted_lambda"] = zip_result_py.predict(
    which="mean-main"
)
zip_training_diagnostics_py["fitted_pi"] = (
    1 - zip_result_py.predict(which="prob-main")
)
zip_training_diagnostics_py["fitted_p_zero"] = zip_result_py.predict(
    which="prob-zero"
)
zip_training_diagnostics_py["fitted_variance"] = zip_result_py.predict(
    which="var"
)
zip_training_diagnostics_py["pearson_residual"] = (
    zip_training_diagnostics_py["claims"]
    - zip_training_diagnostics_py["fitted_mu"]
) / np.sqrt(
    zip_training_diagnostics_py["fitted_variance"]
)

The fitted variance follows Equation 12.16. The R prediction types follow the pscl::predict.zeroinfl() interface, while the Python predictions use the which options provided by statsmodels (Jackman 2024; Seabold and Perktold 2010).

These fitted quantities are the inputs for the calibration, count-frequency, residual, and relative-fit diagnostics below.

12.10.3 Overall mean and zero-frequency check

The first check compares two coarse summaries of the observed training response with the averages implied by the fitted ZIP distribution:

  • Mean claim count: compares the sample mean of claims with the average fitted marginal mean from Equation 12.48.
  • Zero-claim rate: compares the observed proportion of zeros with the average fitted observed-zero probability from Equation 12.49.

Agreement here is useful, but it is only a first check. A model can reproduce these two totals while still fitting poorly within subgroups or at specific count values.

zip_gof_summary_r <- tibble(
  diagnostic = c(
    "Mean claim count",
    "Zero-claim rate"
  ),
  observed = c(
    mean(zip_training_diagnostics_r$claims),
    mean(zip_training_diagnostics_r$claims == 0)
  ),
  fitted = c(
    mean(zip_training_diagnostics_r$fitted_mu),
    mean(zip_training_diagnostics_r$fitted_p_zero)
  )
) |>
  mutate(
    observed_minus_fitted = observed - fitted
  )
zip_gof_summary_py = pd.DataFrame({
    "diagnostic": [
        "Mean claim count",
        "Zero-claim rate",
    ],
    "observed": [
        zip_training_diagnostics_py["claims"].mean(),
        (zip_training_diagnostics_py["claims"] == 0).mean(),
    ],
    "fitted": [
        zip_training_diagnostics_py["fitted_mu"].mean(),
        zip_training_diagnostics_py["fitted_p_zero"].mean(),
    ],
})

zip_gof_summary_py["observed_minus_fitted"] = (
    zip_gof_summary_py["observed"]
    - zip_gof_summary_py["fitted"]
)
Table 12.32: Observed and fitted training-set summaries for the ZIP model using R.
Table 12.33: Observed and fitted training-set summaries for the ZIP model using Python.

The aggregate fit in Table 12.32 and Table 12.33 is very close. The observed training-set mean is 1.449 claims, compared with an average fitted marginal mean of 1.451, an absolute difference of only 0.001976 claims. The observed zero-claim rate is 51.0%, while the average fitted probability of an observed zero is 51.1%. Their absolute difference is about 0.09 percentage points. Neither aggregate discrepancy is substantively large in this training sample. However, agreement in these two totals does not show whether the model is calibrated across different fitted-risk regions or whether it reproduces the complete count distribution.

12.10.4 Calibration of the marginal expected count

The overall mean can hide systematic errors across policyholder profiles. We therefore group observations by \(\widehat{\mu}_i\) and compare the observed and fitted mean claim count within each group.

The code below divides the training observations into ten groups according to their fitted marginal mean. Within each group, we compare the average fitted value with the average observed count. A well-calibrated model should place the grouped points reasonably close to the 45-degree reference line, without a systematic pattern of points remaining mostly above or below it.

zip_mean_calibration_r <- zip_training_diagnostics_r |>
  mutate(
    calibration_group = dplyr::ntile(fitted_mu, 10)
  ) |>
  group_by(calibration_group) |>
  summarise(
    n = n(),
    observed_mean = mean(claims),
    fitted_mean = mean(fitted_mu),
    .groups = "drop"
  )

ggplot(
  zip_mean_calibration_r,
  aes(x = fitted_mean, y = observed_mean)
) +
  geom_abline(
    intercept = 0,
    slope = 1,
    linetype = "dashed"
  ) +
  geom_point(size = 2.5) +
  labs(
    x = "Mean fitted marginal count",
    y = "Observed mean count"
  ) +
  zip_theme
zip_training_diagnostics_py["mean_group"] = pd.qcut(
    zip_training_diagnostics_py["fitted_mu"],
    q=10,
    duplicates="drop",
)

zip_mean_calibration_py = (
    zip_training_diagnostics_py
    .groupby("mean_group", observed=False)
    .agg(
        n=("claims", "size"),
        observed_mean=("claims", "mean"),
        fitted_mean=("fitted_mu", "mean"),
    )
    .reset_index()
)

fig, ax = plt.subplots(figsize=ZIP_FIGSIZE)

calibration_min = min(
    zip_mean_calibration_py["fitted_mean"].min(),
    zip_mean_calibration_py["observed_mean"].min(),
)
calibration_max = max(
    zip_mean_calibration_py["fitted_mean"].max(),
    zip_mean_calibration_py["observed_mean"].max(),
)

ax.plot(
    [calibration_min, calibration_max],
    [calibration_min, calibration_max],
    linestyle="--",
)

ax.scatter(
    zip_mean_calibration_py["fitted_mean"],
    zip_mean_calibration_py["observed_mean"],
    s=45,
)

ax.set_xlabel("Mean fitted marginal count")
ax.set_ylabel("Observed mean count")
zip_clean_axis(ax)
plt.tight_layout()
plt.show()
Figure 12.12: Observed and fitted mean claim counts across groups of the fitted marginal mean using R.
Figure 12.13: Observed and fitted mean claim counts across groups of the fitted marginal mean using Python.

The grouped points in Figure 12.12 and Figure 12.13 remain reasonably close to the 45-degree line, so there is no broad failure of marginal-mean calibration. The deviations are local rather than uniformly in one direction: the model tends to overpredict the observed mean in some lower-middle groups, underpredict through several middle-to-upper groups, and then slightly overpredict again in the highest fitted-mean group. The largest absolute discrepancy occurs in calibration group 10, where the observed mean is 3.612 claims and the fitted mean is 3.873. The resulting gap of about 0.2607 claims is modest relative to the fitted mean in that group, although the alternating deviations suggest that the calibration is not perfectly smooth across the fitted range.

12.10.5 Calibration of the observed-zero probability

The next diagnostic groups observations by \(\widehat{p}_{0,i}\) and compares the fitted zero probability with the empirical zero rate. We use \(\widehat{p}_{0,i}\) rather than \(\widehat{\pi}_i\) because only the observed event \(Y_i=0\) can be checked directly.

Here the observable event is whether claims == 0. We therefore group policyholders by the fitted probability \(\widehat{p}_{0,i}\) from Equation 12.49 and compare that probability with the empirical zero rate in each group.

The distinction between \(\widehat{\pi}_i\) and \(\widehat{p}_{0,i}\) matters. Structural-zero membership is latent and cannot be checked directly from the observed response. The event \(Y_i=0\), in contrast, is observed.

zip_zero_calibration_r <- zip_training_diagnostics_r |>
  mutate(
    calibration_group = dplyr::ntile(fitted_p_zero, 10)
  ) |>
  group_by(calibration_group) |>
  summarise(
    n = n(),
    observed_zero_rate = mean(claims == 0),
    fitted_zero_probability = mean(fitted_p_zero),
    .groups = "drop"
  )

ggplot(
  zip_zero_calibration_r,
  aes(
    x = fitted_zero_probability,
    y = observed_zero_rate
  )
) +
  geom_abline(
    intercept = 0,
    slope = 1,
    linetype = "dashed"
  ) +
  geom_point(size = 2.5) +
  scale_x_continuous(labels = scales::percent_format()) +
  scale_y_continuous(labels = scales::percent_format()) +
  labs(
    x = "Mean fitted probability of an observed zero",
    y = "Observed zero rate"
  ) +
  zip_theme
zip_training_diagnostics_py["zero_group"] = pd.qcut(
    zip_training_diagnostics_py["fitted_p_zero"],
    q=10,
    duplicates="drop",
)

zip_zero_calibration_py = (
    zip_training_diagnostics_py
    .groupby("zero_group", observed=False)
    .agg(
        n=("claims", "size"),
        observed_zero_rate=(
            "claims",
            lambda values: (values == 0).mean(),
        ),
        fitted_zero_probability=("fitted_p_zero", "mean"),
    )
    .reset_index()
)

fig, ax = plt.subplots(figsize=ZIP_FIGSIZE)
ax.plot([0, 1], [0, 1], linestyle="--")

ax.scatter(
    zip_zero_calibration_py["fitted_zero_probability"],
    zip_zero_calibration_py["observed_zero_rate"],
    s=45,
)

ax.set_xlabel("Mean fitted probability of an observed zero")
ax.set_ylabel("Observed zero rate")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
zip_clean_axis(ax)
plt.tight_layout()
plt.show()
Figure 12.14: Observed zero rates and fitted observed-zero probabilities across calibration groups using R.
Figure 12.15: Observed zero rates and fitted observed-zero probabilities across calibration groups using Python.

The zero-probability calibration in Figure 12.14 and Figure 12.15 is also broadly close to the 45-degree line, particularly in the higher fitted-zero-probability groups. The lower and middle portions show somewhat more movement around the reference line, with both underprediction and overprediction rather than a single directional bias. The largest absolute discrepancy occurs in calibration group 2: the observed zero rate is 16.2%, compared with an average fitted zero probability of 26.0%. The absolute gap is therefore about 9.8 percentage points. Thus, the almost exact agreement in the overall zero rate does not translate into perfect group-level calibration, but the departures are local rather than evidence of a systematic failure across the full probability range.

12.10.6 Observed versus fitted count frequencies

For count value \(k\), define the observed frequency

\[ O_k = \sum_{i=1}^{n} \mathbb{I}(Y_i=k) \tag{12.50}\]

and the fitted expected frequency

\[ E_k = \sum_{i=1}^{n} \widehat{P}(Y_i=k\mid\mathbf{x}_i). \tag{12.51}\]

The comparison is distributional rather than only mean-based. It asks whether the fitted ZIP model assigns the right amount of probability mass to zero, to the common positive counts, and to the upper tail.

zip_count_grid_r <- 0:max(zip_training_r$claims)

zip_probability_matrix_r <- predict(
  zip_model_r,
  type = "prob",
  at = zip_count_grid_r
)

zip_count_fit_r <- tibble(
  claims = zip_count_grid_r,
  observed = vapply(
    zip_count_grid_r,
    \(count_value) sum(zip_training_r$claims == count_value),
    numeric(1)
  ),
  expected = colSums(zip_probability_matrix_r)
)

zip_count_fit_r |>
  pivot_longer(
    cols = c(observed, expected),
    names_to = "frequency_type",
    values_to = "frequency"
  ) |>
  mutate(
    frequency_type = recode(
      frequency_type,
      observed = "Observed",
      expected = "Fitted expected"
    )
  ) |>
  ggplot(
    aes(
      x = factor(claims),
      y = frequency,
      fill = frequency_type
    )
  ) +
  geom_col(
    position = position_dodge(width = 0.8),
    width = 0.75
  ) +
  labs(
    x = "Number of claims",
    y = "Number of policyholders",
    fill = NULL
  ) +
  zip_theme
zip_count_grid_py = np.arange(
    0,
    int(zip_training_py["claims"].max()) + 1,
)

zip_probability_matrix_py = np.asarray(
    zip_result_py.predict(
        which="prob",
        y_values=zip_count_grid_py,
    ),
    dtype=float,
)

zip_count_fit_py = pd.DataFrame({
    "claims": zip_count_grid_py,
    "observed": [
        int((zip_training_py["claims"] == value).sum())
        for value in zip_count_grid_py
    ],
    "expected": zip_probability_matrix_py.sum(axis=0),
})

plot_data = zip_count_fit_py.melt(
    id_vars="claims",
    value_vars=["observed", "expected"],
    var_name="frequency_type",
    value_name="frequency",
)

plot_data["frequency_type"] = plot_data["frequency_type"].map({
    "observed": "Observed",
    "expected": "Fitted expected",
})

fig, ax = plt.subplots(figsize=ZIP_FIGSIZE)

sns.barplot(
    data=plot_data,
    x="claims",
    y="frequency",
    hue="frequency_type",
    ax=ax,
)

ax.set_xlabel("Number of claims")
ax.set_ylabel("Number of policyholders")
zip_clean_axis(ax)
plt.tight_layout()
plt.show()
Figure 12.16: Observed and fitted expected claim-count frequencies in the training data using R.
Figure 12.17: Observed and fitted expected claim-count frequencies in the training data using Python.

The fitted count distribution in Figure 12.16 and Figure 12.17 reproduces the main shape of the training response closely. At zero claims, the model expects about 408.7 policyholders compared with 408 observed, so the large zero mass is represented very accurately. The largest absolute frequency discrepancy occurs at 2 claims, with 93 observed policyholders versus 98.82 expected, a difference of about 5.825 policyholders. The common positive counts are similarly close overall. The upper tail is less exact because very large counts are rare: the fitted model spreads a small amount of probability over some high count values with no observations, while the single observed count at the extreme of the training range is difficult to reproduce precisely. In absolute terms, however, these tail discrepancies involve very few policyholders.

12.10.7 Pearson residual diagnostics

Using Equation 12.16, the ZIP Pearson residual is

\[ r_{P,i} = \frac{ y_i-\widehat{\mu}_i }{ \sqrt{ (1-\widehat{\pi}_i) \widehat{\lambda}_i \left( 1+\widehat{\pi}_i\widehat{\lambda}_i \right) } }. \tag{12.52}\]

A residual plot against the fitted marginal mean can reveal systematic curves, changing spread, or isolated observations not explained by the fitted ZIP variance.

The residual should be interpreted against the ZIP model’s own fitted marginal variance. We look primarily for:

  • residuals centred around zero rather than shifted systematically upward or downward;
  • no strong curved pattern in the smooth;
  • no obvious increase or decrease in residual spread across the fitted-mean range;
  • no small set of extreme observations dominating the plot.
ggplot(
  zip_training_diagnostics_r,
  aes(x = fitted_mu, y = pearson_residual)
) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_point(alpha = 0.45) +
  geom_smooth(method = "loess", se = FALSE) +
  labs(
    x = "Fitted marginal mean",
    y = "Pearson residual"
  ) +
  zip_theme
fig, ax = plt.subplots(figsize=ZIP_FIGSIZE)

sns.regplot(
    data=zip_training_diagnostics_py,
    x="fitted_mu",
    y="pearson_residual",
    lowess=True,
    scatter_kws={"alpha": 0.45},
    line_kws={"linewidth": 1.5},
    ax=ax,
)

ax.axhline(0, linestyle="--")
ax.set_xlabel("Fitted marginal mean")
ax.set_ylabel("Pearson residual")
zip_clean_axis(ax)
plt.tight_layout()
plt.show()
Figure 12.18: ZIP Pearson residuals against the fitted marginal mean in the training data using R.
Figure 12.19: ZIP Pearson residuals against the fitted marginal mean in the training data using Python.

The residual pattern in Figure 12.18 and Figure 12.19 is centred close to zero overall. The mean ZIP Pearson residual is -0.003174, and its standard deviation is 0.9833. The smooth remains near zero through much of the fitted-mean range, although it drifts downward at the largest fitted means, suggesting some local overprediction in that region. A small number of observations have comparatively large residuals: 4.2% have absolute residuals above 2, and the largest absolute residual is 4.657. These observations warrant attention, but the residual cloud does not show a large global shift or a strong curvature pattern across most of the fitted range. The interpretation is based on the ZIP marginal variance in Equation 12.52, not on the Classical Poisson rule that variance should equal the mean.

Do not reuse the Classical Poisson dispersion rule unchanged

Classical Poisson regression assumes that the conditional variance equals the conditional mean. ZIP regression does not make that assumption. Its marginal variance includes the additional mixture term in Equation 12.16.

The relevant question is whether systematic dispersion, tail behaviour, or calibration error remains after accounting for the fitted ZIP distribution. A Classical Poisson Pearson dispersion statistic should not be applied into this approach and interpreted by expecting the ZIP result to be close to one.

12.10.8 Relative model comparison

The graphical diagnostics above ask whether the fitted ZIP distribution reproduces important features of the training data. We can complement those checks with relative penalized-likelihood comparisons among ZIP specifications fitted to the same response and observations.

For a model with maximized log-likelihood \(\widehat{\ell}\) and \(k\) estimated parameters, the Akaike Information Criterion is

\[ \operatorname{AIC} = -2\widehat{\ell}+2k, \tag{12.53}\]

while the Bayesian Information Criterion is

\[ \operatorname{BIC} = -2\widehat{\ell} + k\log(n), \tag{12.54}\]

where \(n\) is the number of training observations.

For both criteria, smaller values indicate a better trade-off between fitted likelihood and model complexity. These criteria are relative: they tell us which of the compared specifications is preferred by the criterion, but they do not establish that any model is adequate in an absolute sense (Cameron and Trivedi 2013; Hilbe 2014).

Here we compare the full ZIP model with three reduced ZIP baselines.

Specification Count component Zero-inflation component Interpretive purpose
Full ZIP All regressors All regressors Working specification
Zero-component null All regressors Intercept only Asks whether the zero-component regressors improve relative fit
Count-component null Intercept only All regressors Asks whether the count-component regressors improve relative fit
Complete null ZIP Intercept only Intercept only Baseline with no covariate information in either ZIP mechanism

The three reduced models are not alternative data-generating stories introduced for their own sake. They are benchmarks inside the same ZIP family. This makes the comparison useful for asking where the covariate information is contributing before the chapter later compares ZIP with other regression families.

zip_zero_null_r <- pscl::zeroinfl(
  claims ~
    driver_age_10 +
    annual_mileage_10k +
    vehicle_age_5 +
    male +
    urban_area +
    prior_claims |
    1,
  data = zip_training_r,
  dist = "poisson",
  link = "logit",
  control = pscl::zeroinfl.control(
    method = "BFGS",
    maxit = 10000,
    trace = FALSE
  )
)

zip_count_null_r <- pscl::zeroinfl(
  claims ~
    1 |
    driver_age_10 +
    annual_mileage_10k +
    vehicle_age_5 +
    male +
    urban_area +
    prior_claims,
  data = zip_training_r,
  dist = "poisson",
  link = "logit",
  control = pscl::zeroinfl.control(
    method = "BFGS",
    maxit = 10000,
    trace = FALSE
  )
)

zip_complete_null_r <- pscl::zeroinfl(
  claims ~ 1 | 1,
  data = zip_training_r,
  dist = "poisson",
  link = "logit",
  control = pscl::zeroinfl.control(
    method = "BFGS",
    maxit = 10000,
    trace = FALSE
  )
)

zip_information_criterion_row_r <- function(
  model,
  model_name,
  n_obs
) {
  model_log_likelihood <- logLik(model)

  log_likelihood <-
    as.numeric(model_log_likelihood)

  number_of_parameters <-
    attr(
      model_log_likelihood,
      "df"
    )

  tibble(
    model = model_name,
    AIC =
      -2 * log_likelihood +
      2 * number_of_parameters,
    BIC =
      -2 * log_likelihood +
      log(n_obs) *
      number_of_parameters
  )
}

zip_information_criteria_r <- bind_rows(
  zip_information_criterion_row_r(
    zip_model_r,
    "Full ZIP",
    nrow(zip_training_r)
  ),
  zip_information_criterion_row_r(
    zip_zero_null_r,
    "Zero-component null",
    nrow(zip_training_r)
  ),
  zip_information_criterion_row_r(
    zip_count_null_r,
    "Count-component null",
    nrow(zip_training_r)
  ),
  zip_information_criterion_row_r(
    zip_complete_null_r,
    "Complete null ZIP",
    nrow(zip_training_r)
  )
) |>
  mutate(
    delta_AIC =
      AIC - min(AIC),
    delta_BIC =
      BIC - min(BIC)
  )
X_intercept_py = pd.DataFrame(
    {
        "const":
            np.ones(
                len(zip_training_py)
            )
    },
    index=zip_training_py.index,
)

zip_zero_null_model_py = ZeroInflatedPoisson(
    endog=y_zip_py,
    exog=X_count_py,
    exog_infl=X_intercept_py,
    inflation="logit",
)

zip_zero_null_result_py = (
    zip_zero_null_model_py.fit(
        method="bfgs",
        maxiter=10000,
        disp=0,
    )
)

zip_count_null_model_py = ZeroInflatedPoisson(
    endog=y_zip_py,
    exog=X_intercept_py,
    exog_infl=X_zero_py,
    inflation="logit",
)

zip_count_null_result_py = (
    zip_count_null_model_py.fit(
        method="bfgs",
        maxiter=10000,
        disp=0,
    )
)

zip_complete_null_model_py = ZeroInflatedPoisson(
    endog=y_zip_py,
    exog=X_intercept_py,
    exog_infl=X_intercept_py,
    inflation="logit",
)

zip_complete_null_result_py = (
    zip_complete_null_model_py.fit(
        method="bfgs",
        maxiter=10000,
        disp=0,
    )
)

def zip_information_criterion_row(
    result,
    model_name,
    n_obs,
):
    log_likelihood = float(
        result.llf
    )

    number_of_parameters = len(
        result.params
    )

    return {
        "model":
            model_name,
        "AIC":
            -2 * log_likelihood
            + 2 * number_of_parameters,
        "BIC":
            -2 * log_likelihood
            + np.log(n_obs)
            * number_of_parameters,
    }

zip_information_criteria_py = pd.DataFrame([
    zip_information_criterion_row(
        zip_result_py,
        "Full ZIP",
        len(zip_training_py),
    ),
    zip_information_criterion_row(
        zip_zero_null_result_py,
        "Zero-component null",
        len(zip_training_py),
    ),
    zip_information_criterion_row(
        zip_count_null_result_py,
        "Count-component null",
        len(zip_training_py),
    ),
    zip_information_criterion_row(
        zip_complete_null_result_py,
        "Complete null ZIP",
        len(zip_training_py),
    ),
])

zip_information_criteria_py["delta_AIC"] = (
    zip_information_criteria_py["AIC"]
    - zip_information_criteria_py["AIC"].min()
)

zip_information_criteria_py["delta_BIC"] = (
    zip_information_criteria_py["BIC"]
    - zip_information_criteria_py["BIC"].min()
)
Table 12.34: AIC and BIC comparison of the full and reduced ZIP training specifications using R.
Table 12.35: AIC and BIC comparison of the full and reduced ZIP training specifications using Python.

The raw AIC and BIC values can be compared directly across the four ZIP specifications because all models use the same response and training observations. The Delta AIC and Delta BIC columns measure each model’s difference from the smallest value of the corresponding criterion, so the criterion-preferred model has a delta of zero. To understand where the covariate information is contributing, compare each reduced model with the full ZIP specification:

  • If the zero-component null has noticeably larger AIC/BIC than the full ZIP model, the zero-component regressors improve penalized fit beyond an intercept-only zero component.
  • If the count-component null has noticeably larger AIC/BIC than the full ZIP model, the count-component regressors improve penalized fit beyond an intercept-only count component.
  • If the complete null ZIP is clearly worse than the full ZIP model, the covariates jointly contribute useful fitted information somewhere in the ZIP structure.
  • If a reduced model has the smaller criterion value, the likelihood improvement from the additional full-model regressors is not large enough, under that criterion, to offset their complexity.

AIC and BIC are not formal goodness-of-fit tests and do not replace the calibration, frequency, or residual diagnostics above.

The full ZIP specification has the smallest AIC and BIC in both Table 12.34 and Table 12.35. Relative to the full model, the zero-component-null specification increases AIC by 84.85 and BIC by 56.74, indicating that allowing the regressors to explain structural-zero membership adds substantial fitted information beyond an intercept-only zero component. The count-component-null model is even farther from the full specification, with increases of 104.8 in AIC and 76.72 in BIC, so covariate information in the count component is also important. Finally, the complete-null ZIP is worse by 260.4 AIC units and 204.2 BIC units. Thus, both ZIP components benefit from covariate information in the training data. These information criteria reinforce, rather than replace, the calibration, frequency, and residual diagnostics above.

12.10.9 Overall adequacy conclusion

The goodness-of-fit decision should combine the evidence rather than rely on one statistic.

Table 12.36: Diagnostic guide for deciding whether the fitted ZIP model is adequate enough to interpret and evaluate predictively.
Diagnostic theme Question Evidence used
Numerical stability Was the model estimated reliably? Convergence, finite standard errors, optimizer sensitivity
Marginal-mean calibration Does the model reproduce average claim counts across fitted-risk groups? Figure 12.12 and Figure 12.13
Zero calibration Does the model reproduce observed zeros across fitted-probability groups? Figure 12.14 and Figure 12.15
Count distribution Does the model reproduce \(0,1,2,\ldots\) claims? Figure 12.16 and Figure 12.17
Residual behaviour Are systematic discrepancies still visible? Figure 12.18 and Figure 12.19
Relative fit Do the full ZIP regressors improve penalized likelihood relative to reduced ZIP baselines? Table 12.34 and Table 12.35

Taken together, the training-stage diagnostics indicate that the fitted ZIP model represents the main features of the synthetic insurance-claims distribution adequately enough to carry forward. The overall mean and zero rate are reproduced almost exactly, the grouped calibration plots show modest local departures rather than a systematic failure, and the fitted count frequencies track both the zero mass and the common positive counts closely. The Pearson residuals are centred near zero overall, although a small number of large residuals and some drift at the upper end of the fitted-mean range remain. AIC and BIC also favour the full two-component specification over each reduced ZIP baseline. The model is therefore not treated as a perfect description of every training observation, but the evidence is sufficiently coherent to freeze the specification and proceed to the testing-set refit, fitted-results interpretation, and held-out predictive assessment.

12.11 Inference for Model Parameters

The training-stage diagnostics in Section 12.10 were used to assess and freeze the working ZIP specification. We now return to the inferential inquiry introduced in Section 12.2.1:

How are policyholder and vehicle characteristics associated with the structural-zero probability, the count-generating mean, and the resulting marginal expected number of claims?

For the workflow used in this chapter, the frozen ZIP specification is refitted on the testing observations. This testing-set fit supplies the coefficient estimates, standard errors, confidence intervals, and hypothesis tests reported in this section. The original training estimates are retained for a split-sample comparison.

This operation is distinct from held-out prediction. The predictive section continues to use the model fitted on the training data.

12.11.1 Fitting the frozen specification on the testing data

zip_testing_r <- test_data |>
  mutate(
    driver_age_10 = driver_age / 10,
    annual_mileage_10k = annual_mileage / 10000,
    vehicle_age_5 = vehicle_age / 5
  )

zip_test_model_r <- pscl::zeroinfl(
  formula = zip_formula_r,
  data = zip_testing_r,
  dist = "poisson",
  link = "logit",
  control = pscl::zeroinfl.control(
    method = "BFGS",
    maxit = 10000,
    trace = FALSE
  )
)

summary(zip_test_model_r)
zip_testing_py = testing_data.copy()

zip_testing_py["driver_age_10"] = (
    pd.to_numeric(zip_testing_py["driver_age"], errors="coerce") / 10
)
zip_testing_py["annual_mileage_10k"] = (
    pd.to_numeric(
        zip_testing_py["annual_mileage"],
        errors="coerce",
    ) / 10000
)
zip_testing_py["vehicle_age_5"] = (
    pd.to_numeric(zip_testing_py["vehicle_age"], errors="coerce") / 5
)

for column in zip_covariates_py + ["claims"]:
    zip_testing_py[column] = pd.to_numeric(
        zip_testing_py[column],
        errors="coerce",
    )

zip_testing_py = zip_testing_py.dropna(
    subset=zip_covariates_py + ["claims"]
).copy()

X_count_test_py = sm.add_constant(
    zip_testing_py[zip_covariates_py].astype(float),
    has_constant="add",
)
X_zero_test_py = X_count_test_py.copy()
y_zip_test_py = zip_testing_py["claims"].astype(int)

zip_test_model_py = ZeroInflatedPoisson(
    endog=y_zip_test_py,
    exog=X_count_test_py,
    exog_infl=X_zero_test_py,
    inflation="logit",
)

zip_test_result_py = zip_test_model_py.fit(
    method="bfgs",
    maxiter=1000,
    disp=False,
    full_output=True,
    cov_type="nonrobust",
)

print(zip_test_result_py.summary())

The testing fit must retain the same regressors, transformations, component formulas, links, and fitting settings used for the training specification. The testing results are used to evaluate the frozen specification, not to redesign it.

The testing-set fits can now be summarized using the same coefficient and convergence structure used for the training fit.

Table 12.37: Numerical completion checks for the frozen ZIP specification refitted on the testing data using R.
Table 12.38: Numerical completion checks for the frozen ZIP specification refitted on the testing data using Python.

The frozen testing-set refit completed successfully in both implementations. As shown in Table 12.37 and Table 12.38, both optimizers report convergence, all reported standard errors are finite, and both fits estimate 14 parameters. The R maximized log-likelihood is -276.6, and the Python result agrees to the displayed precision. There is therefore no immediate numerical warning that would prevent coefficient-level interpretation. The testing-set standard errors are nevertheless expected to be wider than the training-set standard errors because only 200 observations contribute to this refit, so the strength of the inferential evidence should be judged from the reported intervals and tests rather than from coefficient direction alone.

12.11.2 Wald inference for individual coefficients

Let \(\theta_j\) denote one coefficient from either the zero-inflation or count component. The Wald statistic is

\[ z_j = \frac{ \widehat{\theta}_j }{ \operatorname{SE}(\widehat{\theta}_j) }. \tag{12.55}\]

The corresponding two-sided hypotheses are

\[ H_0:\theta_j=0 \qquad\text{versus}\qquad H_A:\theta_j\ne0. \tag{12.56}\]

Under the usual large-sample approximation, \(z_j\) is compared with a standard Normal reference distribution. A Wald confidence interval is

\[ \widehat{\theta}_j \pm z_{1-\alpha/2} \operatorname{SE}(\widehat{\theta}_j). \tag{12.57}\]

The standard errors come from the joint testing-set covariance matrix. They should not be calculated by fitting separate Logistic and Poisson models to the two ZIP components.

12.11.3 The two component hypotheses answer different questions

For regressor \(x_j\), the zero-component null hypothesis is

\[ H_0:\alpha_j=0. \tag{12.58}\]

This asks whether \(x_j\) is associated with the log-odds of latent structural-zero membership, holding the other zero-component regressors fixed.

The count-component null hypothesis is

\[ H_0:\beta_j=0. \tag{12.59}\]

This asks whether \(x_j\) is associated with the log mean among policyholders in the count-generating state, holding the other count-component regressors fixed.

These are component-specific questions. Evidence against Equation 12.58 does not imply evidence against Equation 12.59, and vice versa.

12.11.4 Coefficient estimates, intervals, and transformed effects

The testing-set coefficient table brings together four related pieces of information for each ZIP coefficient:

  • Estimate: the fitted change on the component’s linear-predictor scale.
  • Standard Error: the estimated sampling uncertainty of that coefficient, obtained from the joint ZIP covariance matrix.
  • 95% Wald Confidence Interval: an approximate interval on the coefficient scale.
  • Transformed Effect: \(\exp(\widehat{\alpha}_j)\) for the zero component or \(\exp(\widehat{\beta}_j)\) for the count component, together with the transformed interval.

Because the continuous regressors were scaled before fitting, a one-unit comparison has a practical interpretation:

  • one unit of driver_age_10 is 10 years;
  • one unit of annual_mileage_10k is 10,000 kilometres per year;
  • one unit of vehicle_age_5 is five years;
  • a one-unit change in each binary regressor compares coding \(1\) with coding \(0\).

For the zero-inflation component, exponentiating a coefficient gives an odds ratio for latent structural-zero membership. It is not an odds ratio for observing zero claims. For the count component, exponentiating a coefficient gives a rate ratio for the Poisson mean within the count-generating state (Lambert 1992; Cameron and Trivedi 2013).

The table should therefore be read component by component first, and then connected through the joint and marginal analyses below.

zip_inference_table_r <- zip_test_coef_table_r |>
  mutate(
    conf_low = estimate - qnorm(0.975) * std_error,
    conf_high = estimate + qnorm(0.975) * std_error,
    transformed_effect = exp(estimate),
    transformed_low = exp(conf_low),
    transformed_high = exp(conf_high),
    effect_scale = if_else(
      component == "Zero inflation",
      "Structural-zero odds ratio",
      "Count-state rate ratio"
    )
  ) |>
  select(
    component,
    term,
    estimate,
    std_error,
    statistic,
    p_value,
    conf_low,
    conf_high,
    effect_scale,
    transformed_effect,
    transformed_low,
    transformed_high
  )
zip_inference_table_py = zip_test_coef_table_py.copy()

zip_inference_table_py["conf_low"] = (
    zip_inference_table_py["estimate"]
    - 1.96 * zip_inference_table_py["std_error"]
)

zip_inference_table_py["conf_high"] = (
    zip_inference_table_py["estimate"]
    + 1.96 * zip_inference_table_py["std_error"]
)

zip_inference_table_py["transformed_effect"] = np.exp(
    zip_inference_table_py["estimate"]
)

zip_inference_table_py["transformed_low"] = np.exp(
    zip_inference_table_py["conf_low"]
)

zip_inference_table_py["transformed_high"] = np.exp(
    zip_inference_table_py["conf_high"]
)

zip_inference_table_py["effect_scale"] = np.where(
    zip_inference_table_py["component"] == "Zero inflation",
    "Structural-zero odds ratio",
    "Count-state rate ratio",
)

zip_inference_table_py = zip_inference_table_py[[
    "component",
    "term",
    "estimate",
    "std_error",
    "statistic",
    "p_value",
    "conf_low",
    "conf_high",
    "effect_scale",
    "transformed_effect",
    "transformed_low",
    "transformed_high",
]]
Table 12.39: ZIP coefficient estimates, Wald intervals, and transformed effects from the frozen testing-set fit using R.
Table 12.40: ZIP coefficient estimates, Wald intervals, and transformed effects from the frozen testing-set fit using Python.

The testing-set count component in Table 12.39 and Table 12.40 provides the clearest evidence for annual mileage and prior claims. Holding the remaining regressors fixed, a 10,000-km increase in annual mileage multiplies the fitted count-state mean by 1.592, with an approximate 95% Wald interval from 1.271 to 1.995. Policyholders with prior claims have a fitted count-state mean multiplied by 1.75 relative to those without prior claims, with an interval from 1.31 to 2.338. The urban_area count-state rate ratio is 1.352, with its interval remaining just above 1. By contrast, the count-component intervals for driver age, vehicle age, and the male indicator include the neutral rate ratio of 1.

The zero-inflation component tells a complementary story. A 10,000-km mileage increase multiplies the fitted odds of structural-zero membership by 0.3037, with a 95% interval from 0.1499 to 0.6151. Prior claims similarly multiply the structural-zero odds by 0.2727, with an interval from 0.1193 to 0.6234. Both effects are below 1, associating higher mileage and prior claims with lower odds of belonging to the latent structural-zero state. The driver-age interval narrowly includes 1, while the intervals for vehicle age, the male indicator, and urban area are wider and also include 1. These zero-component odds ratios concern latent structural-zero membership; they are not odds ratios for the observed event claims == 0.

12.11.5 Joint tests across both ZIP components

The component-specific tests above answer two separate questions for each regressor. Sometimes, however, the broader question is:

Does this regressor contribute to the ZIP model through either mechanism?

For regressor \(x_j\), the joint null is

\[ H_0: \begin{pmatrix} \alpha_j\\ \beta_j \end{pmatrix} = \begin{pmatrix} 0\\ 0 \end{pmatrix}. \tag{12.60}\]

Under this null, the regressor has no coefficient contribution in either ZIP component. Rejecting it means that the pair of coefficients is inconsistent with both being zero simultaneously. It does not tell us which component is responsible; the component-specific results must still be inspected for that interpretation.

Collect the two estimates into

\[ \widehat{\boldsymbol{\delta}}_j = \begin{pmatrix} \widehat{\alpha}_j\\ \widehat{\beta}_j \end{pmatrix}. \tag{12.61}\]

Let \(\widehat{\mathbf{V}}_{\delta_j}\) be the corresponding \(2\times2\) block of the full testing-set covariance matrix. The joint Wald statistic is

\[ W_j = \widehat{\boldsymbol{\delta}}_j^\top \widehat{\mathbf{V}}_{\delta_j}^{-1} \widehat{\boldsymbol{\delta}}_j. \tag{12.62}\]

The statistic measures how far the estimated coefficient pair is from the joint-null point \((0,0)\) after accounting for the pair’s estimated uncertainty. The covariance term matters because \(\widehat{\alpha}_j\) and \(\widehat{\beta}_j\) were estimated as part of the same ZIP likelihood rather than as unrelated quantities.

Under the usual large-sample approximation, \(W_j\) is compared with a Chi-squared distribution with two degrees of freedom (Wasserman 2004; Cameron and Trivedi 2013).

Tip on reading the two-component Wald test

The joint test is an omnibus test for the coefficient pair.

  • A small joint \(p\)-value means that the data are difficult to reconcile with \(\alpha_j=\beta_j=0\) simultaneously.
  • A large joint \(p\)-value means that the data do not provide strong evidence against that joint null.
  • The test does not say that the two component effects are equal, have the same sign, or have the same practical importance.
  • A regressor can have a strong effect in one component and little evidence in the other and still produce a meaningful joint result.

Geometrically, the test asks whether the uncertainty region for the pair \((\alpha_j,\beta_j)\) is sufficiently far from the origin after accounting for the covariance between the two estimates. This is the multivariate extension of the one-coefficient Wald idea introduced earlier in the cookbook.

zip_test_parameters_r <- coef(zip_test_model_r)
zip_test_vcov_r <- vcov(zip_test_model_r)

zip_joint_terms_r <- c(
  "driver_age_10",
  "annual_mileage_10k",
  "vehicle_age_5",
  "male",
  "urban_area",
  "prior_claims"
)

zip_joint_wald_r <- purrr::map_dfr(
  zip_joint_terms_r,
  function(term_name) {
    coefficient_names <- c(
      paste0("zero_", term_name),
      paste0("count_", term_name)
    )

    joint_estimate <- zip_test_parameters_r[coefficient_names]

    joint_vcov <- zip_test_vcov_r[
      coefficient_names,
      coefficient_names,
      drop = FALSE
    ]

    joint_statistic <- as.numeric(
      t(joint_estimate) %*%
        solve(joint_vcov) %*%
        joint_estimate
    )

    tibble(
      term = term_name,
      statistic = joint_statistic,
      degrees_of_freedom = 2,
      p_value = pchisq(
        joint_statistic,
        df = 2,
        lower.tail = FALSE
      )
    )
  }
)
from scipy.stats import chi2

zip_test_parameters_py = zip_test_result_py.params
zip_test_vcov_py = zip_test_result_py.cov_params()

zip_joint_terms_py = [
    "driver_age_10",
    "annual_mileage_10k",
    "vehicle_age_5",
    "male",
    "urban_area",
    "prior_claims",
]

joint_rows_py = []

for term_name in zip_joint_terms_py:
    coefficient_names = [
        f"inflate_{term_name}",
        term_name,
    ]

    joint_estimate = (
        zip_test_parameters_py
        .loc[coefficient_names]
        .to_numpy()
    )

    joint_vcov = (
        zip_test_vcov_py
        .loc[coefficient_names, coefficient_names]
        .to_numpy()
    )

    joint_statistic = float(
        joint_estimate.T
        @ np.linalg.solve(joint_vcov, joint_estimate)
    )

    joint_rows_py.append({
        "term": term_name,
        "statistic": joint_statistic,
        "degrees_of_freedom": 2,
        "p_value": chi2.sf(joint_statistic, df=2),
    })

zip_joint_wald_py = pd.DataFrame(joint_rows_py)
Table 12.41: Joint two-component Wald tests for the frozen testing-set ZIP fit using R.
Table 12.42: Joint two-component Wald tests for the frozen testing-set ZIP fit using Python.

The joint tests in Table 12.41 and Table 12.42 reinforce the strongest component-specific findings. Annual mileage and prior claims both give very small joint \(p\)-values in R and Python, consistent with the preceding result that each regressor contributes through both the zero-inflation and count components. Driver age is weaker: the R joint test gives 0.040, whereas the corresponding Python value is slightly above 0.05. This is best treated as modest, implementation-sensitive evidence rather than as a robust two-component result. The urban-area coefficient has testing-set evidence in the count component alone, but its two-degree-of-freedom joint test is not below 0.05, illustrating that a single component-level result does not automatically imply rejection of the broader two-component null. Vehicle age and the male indicator do not show strong evidence in either component or in their joint tests.

12.11.6 Comparing the training and testing estimates

The testing-set refit uses the same frozen model specification on a different subset of observations. The comparison below is therefore a split-sample stability check: it asks whether the main coefficient directions and approximate magnitudes found in training are reproduced when the same specification is estimated on the testing subset.

This is not a new model-selection step. The testing results should not be used to redesign the model and then reported as if the same testing data were still untouched.

For a common coefficient \(\theta_j\), the difference between the two estimates is

\[ \widehat{\theta}_{j,\operatorname{test}} - \widehat{\theta}_{j,\operatorname{train}}. \tag{12.63}\]

Because the training and testing subsets were created by a disjoint random split, the large-sample variance of this difference is approximated by the sum of the two estimated variances. The standardized difference is therefore

\[ z_{\operatorname{diff},j} = \frac{ \widehat{\theta}_{j,\operatorname{test}} - \widehat{\theta}_{j,\operatorname{train}} }{ \sqrt{ \operatorname{SE}(\widehat{\theta}_{j,\operatorname{test}})^2 + \operatorname{SE}(\widehat{\theta}_{j,\operatorname{train}})^2 } }. \tag{12.64}\]

Values of \(z_{\operatorname{diff},j}\) near zero indicate that the observed split-to-split difference is small relative to its estimated uncertainty. Large absolute values indicate a larger discrepancy relative to that uncertainty.

We can also compare the complete common parameter vector jointly:

\[ W_{\operatorname{diff}} = \left( \widehat{\boldsymbol{\theta}}_{\operatorname{test}} - \widehat{\boldsymbol{\theta}}_{\operatorname{train}} \right)^\top \left( \widehat{\mathbf{V}}_{\operatorname{test}} + \widehat{\mathbf{V}}_{\operatorname{train}} \right)^{-1} \left( \widehat{\boldsymbol{\theta}}_{\operatorname{test}} - \widehat{\boldsymbol{\theta}}_{\operatorname{train}} \right). \tag{12.65}\]

This global statistic is an omnibus check of whether the two estimated parameter vectors differ more than would be expected from their estimated sampling uncertainty. Under strong large-sample regularity conditions, it can be compared with a Chi-squared distribution with degrees of freedom equal to the number of common coefficients.

The coefficient-level table and the global statistic answer complementary questions. The first shows where discrepancies occur; the second summarizes whether the vector as a whole shows evidence of a split-to-split difference.

zip_training_compare_r <- zip_coef_table_r |>
  transmute(
    component,
    term,
    training_estimate = estimate,
    training_std_error = std_error,
    training_conf_low =
      estimate - qnorm(0.975) * std_error,
    training_conf_high =
      estimate + qnorm(0.975) * std_error
  )

zip_testing_compare_r <- zip_test_coef_table_r |>
  transmute(
    component,
    term,
    testing_estimate = estimate,
    testing_std_error = std_error,
    testing_conf_low =
      estimate - qnorm(0.975) * std_error,
    testing_conf_high =
      estimate + qnorm(0.975) * std_error
  )

zip_split_comparison_r <- zip_training_compare_r |>
  inner_join(
    zip_testing_compare_r,
    by = c("component", "term")
  ) |>
  mutate(
    same_direction =
      sign(training_estimate) == sign(testing_estimate),
    standardized_difference =
      (testing_estimate - training_estimate) /
      sqrt(
        training_std_error^2 +
        testing_std_error^2
      ),
    difference_p_value =
      2 * pnorm(-abs(standardized_difference))
  )

zip_train_parameters_r <- coef(zip_model_r)
zip_test_parameters_r <- coef(zip_test_model_r)

zip_common_parameters_r <- intersect(
  names(zip_train_parameters_r),
  names(zip_test_parameters_r)
)

zip_parameter_difference_r <-
  zip_test_parameters_r[zip_common_parameters_r] -
  zip_train_parameters_r[zip_common_parameters_r]

zip_difference_vcov_r <-
  vcov(zip_test_model_r)[
    zip_common_parameters_r,
    zip_common_parameters_r,
    drop = FALSE
  ] +
  vcov(zip_model_r)[
    zip_common_parameters_r,
    zip_common_parameters_r,
    drop = FALSE
  ]

zip_split_global_statistic_r <- as.numeric(
  t(zip_parameter_difference_r) %*%
    solve(zip_difference_vcov_r) %*%
    zip_parameter_difference_r
)

zip_split_global_r <- tibble(
  statistic = zip_split_global_statistic_r,
  degrees_of_freedom = length(zip_common_parameters_r),
  p_value = pchisq(
    zip_split_global_statistic_r,
    df = length(zip_common_parameters_r),
    lower.tail = FALSE
  )
)
from scipy.stats import chi2

zip_training_compare_py = zip_coef_table_py[[
    "component",
    "term",
    "estimate",
    "std_error",
]].copy()

zip_training_compare_py = zip_training_compare_py.rename(columns={
    "estimate": "training_estimate",
    "std_error": "training_std_error",
})

zip_training_compare_py["training_conf_low"] = (
    zip_training_compare_py["training_estimate"]
    - 1.96 * zip_training_compare_py["training_std_error"]
)

zip_training_compare_py["training_conf_high"] = (
    zip_training_compare_py["training_estimate"]
    + 1.96 * zip_training_compare_py["training_std_error"]
)

zip_testing_compare_py = zip_test_coef_table_py[[
    "component",
    "term",
    "estimate",
    "std_error",
]].copy()

zip_testing_compare_py = zip_testing_compare_py.rename(columns={
    "estimate": "testing_estimate",
    "std_error": "testing_std_error",
})

zip_testing_compare_py["testing_conf_low"] = (
    zip_testing_compare_py["testing_estimate"]
    - 1.96 * zip_testing_compare_py["testing_std_error"]
)

zip_testing_compare_py["testing_conf_high"] = (
    zip_testing_compare_py["testing_estimate"]
    + 1.96 * zip_testing_compare_py["testing_std_error"]
)

zip_split_comparison_py = zip_training_compare_py.merge(
    zip_testing_compare_py,
    on=["component", "term"],
    how="inner",
)

zip_split_comparison_py["same_direction"] = (
    np.sign(zip_split_comparison_py["training_estimate"])
    == np.sign(zip_split_comparison_py["testing_estimate"])
)

zip_split_comparison_py["standardized_difference"] = (
    zip_split_comparison_py["testing_estimate"]
    - zip_split_comparison_py["training_estimate"]
) / np.sqrt(
    zip_split_comparison_py["training_std_error"] ** 2
    + zip_split_comparison_py["testing_std_error"] ** 2
)

zip_split_comparison_py["difference_p_value"] = chi2.sf(
    zip_split_comparison_py["standardized_difference"] ** 2,
    df=1,
)

zip_common_parameters_py = [
    name
    for name in zip_result_py.params.index
    if name in zip_test_result_py.params.index
]

zip_parameter_difference_py = (
    zip_test_result_py.params.loc[zip_common_parameters_py]
    - zip_result_py.params.loc[zip_common_parameters_py]
).to_numpy()

zip_train_vcov_py = pd.DataFrame(
    zip_result_py.cov_params(),
    index=zip_result_py.params.index,
    columns=zip_result_py.params.index,
)

zip_test_vcov_py = pd.DataFrame(
    zip_test_result_py.cov_params(),
    index=zip_test_result_py.params.index,
    columns=zip_test_result_py.params.index,
)

zip_difference_vcov_py = (
    zip_test_vcov_py.loc[
        zip_common_parameters_py,
        zip_common_parameters_py,
    ].to_numpy()
    +
    zip_train_vcov_py.loc[
        zip_common_parameters_py,
        zip_common_parameters_py,
    ].to_numpy()
)

zip_split_global_statistic_py = float(
    zip_parameter_difference_py.T
    @ np.linalg.solve(
        zip_difference_vcov_py,
        zip_parameter_difference_py,
    )
)

zip_split_global_py = pd.DataFrame({
    "statistic": [zip_split_global_statistic_py],
    "degrees_of_freedom": [len(zip_common_parameters_py)],
    "p_value": [
        chi2.sf(
            zip_split_global_statistic_py,
            df=len(zip_common_parameters_py),
        )
    ],
})
Table 12.43: Comparison of the training and testing ZIP coefficient estimates using R.
Table 12.44: Comparison of the training and testing ZIP coefficient estimates using Python.
Table 12.45: Joint comparison of the complete training and testing ZIP parameter vectors using R.
Table 12.46: Joint comparison of the complete training and testing ZIP parameter vectors using Python.

The split comparison in Table 12.43 and Table 12.44 shows that the main fitted directions are largely reproduced, but with wider testing-set intervals because the testing refit uses many fewer observations. All six non-intercept count-component coefficients retain the same sign across training and testing. In the zero-inflation component, the directions for driver age, annual mileage, the male indicator, and prior claims are also reproduced; only the comparatively weak vehicle_age_5 and urban_area estimates change sign. The largest absolute standardized coefficient difference in the R comparison is 1.113, occurring for Count / urban_area. None of the coefficient-by-coefficient difference tests gives strong evidence of a train-versus-test change.

The omnibus comparison in Table 12.45 reaches a statistic of 8.509 on 14 degrees of freedom, with \(p=\) 0.861; the Python result leads to the same conclusion. Thus, the observed split-to-split differences are compatible with sampling variation under this large-sample comparison. This supports describing annual mileage and prior claims as comparatively stable fitted patterns, while the weak zero-component effects for vehicle age and urban area are less stable in direction. The large omnibus \(p\)-value should not be described as proof that the two parameter vectors are equivalent.

A non-significant difference does not prove equivalence

A train-versus-test difference test starts from a null hypothesis of exact equality for the coefficient or parameter vector being compared. If the resulting \(p\)-value is not small, the correct conclusion is that the observed data do not provide enough evidence to reject that equality null under the stated approximation.

That conclusion is not the same as demonstrating that the two estimates are practically equivalent.

Why not? A non-significant result can occur for at least two very different reasons:

  1. the underlying difference is genuinely small; or
  2. the comparison is too imprecise to distinguish a meaningful difference from zero.

The second possibility is particularly relevant here because the testing subset is smaller than the training subset. Wider standard errors can make the difference test insensitive even when the numerical estimates are not especially close.

A formal equivalence analysis reverses the question. Before seeing the results, we would specify an interval of differences, such as \((-\Delta,\Delta)\), that is small enough to be considered practically negligible. We would then ask whether the data provide sufficient evidence that the true difference lies inside those pre-specified equivalence bounds. Procedures such as the two one-sided tests approach are designed for that purpose (Lakens 2017).

For this chapter, the train-versus-test comparison is best treated as a stability diagnostic, not as a formal equivalence study. Interpret the coefficient directions, magnitudes, confidence intervals, standardized differences, and numerical reliability together.

12.11.7 Inference for nonlinear fitted quantities

Coefficient inference is only one part of the inferential inquiry. For a realistic policyholder profile, the quantities we often want to communicate are

  • the structural-zero probability \(\pi_i\);
  • the count-state mean \(\lambda_i\);
  • the marginal expected count \(\mu_i=(1-\pi_i)\lambda_i\);
  • the observed-zero probability \(p_{0,i}=\pi_i+(1-\pi_i)e^{-\lambda_i}\).

These quantities are nonlinear functions of the fitted ZIP coefficients. Their uncertainty therefore cannot generally be read from one coefficient standard error or one component-specific confidence interval. When a fitted quantity depends on both ZIP components, the uncertainty calculation must also retain the estimated covariance between the zero-inflation and count coefficients.

A useful way to think about the problem is:

The fitted coefficient vector has uncertainty. If we move the coefficient vector to another plausible value allowed by that uncertainty, how much do the corresponding fitted probabilities and means move?

The scenario interpretation in Section 12.12.6 uses the delta method to propagate the testing-set joint covariance matrix to the marginal expected count. This extends the same large-sample Wald logic used for the coefficient tables to a nonlinear response-scale quantity. Coefficient simulation and bootstrap refitting provide alternative ways to propagate the same underlying estimation uncertainty and are discussed in the Tip in that subsection (Wasserman 2004; Cameron and Trivedi 2013).

One practical approach is coefficient simulation using the asymptotic joint covariance matrix.

  1. Obtain the fitted coefficient vector \(\widehat{\boldsymbol{\theta}}\) and covariance matrix \(\widehat{\mathbf V}\) from the testing-set ZIP fit.
  2. Generate many plausible coefficient vectors according to

\[ \boldsymbol{\theta}^{(b)} \sim N\left( \widehat{\boldsymbol{\theta}}, \widehat{\mathbf V} \right). \tag{12.66}\]

  1. For each draw, recompute the desired fitted quantity for the policyholder profile.
  2. Use the simulated distribution of that fitted quantity to summarize uncertainty, for example with its 2.5th and 97.5th percentiles.

This procedure propagates uncertainty through the nonlinear transformation while retaining the full cross-component covariance structure. The resulting interval can be asymmetric even though the coefficient simulation begins with a multivariate Normal approximation.

Tip on the underlying uncertainty calculation

If \(g(\boldsymbol{\theta})\) denotes a fitted quantity such as \(\mu_i\) or \(p_{0,i}\), there are several common ways to approximate uncertainty for \(g(\widehat{\boldsymbol{\theta}})\).

  • The delta method linearizes \(g\) around the fitted coefficient vector and propagates the covariance matrix through the gradient of \(g\).
  • Coefficient simulation repeatedly evaluates \(g\) at draws from the fitted asymptotic coefficient distribution.
  • A bootstrap repeatedly rebuilds the fitted model from resampled observations and therefore reproduces more of the estimation process, at greater computational cost.

All three approaches must respect the joint ZIP parameter vector when the fitted quantity depends on both components. For general asymptotic inference and transformations of estimators, see Wasserman (2004). For count-model likelihood inference, see Cameron and Trivedi (2013).

12.11.8 Returning to the inferential inquiry

The inferential conclusion should distinguish

  • evidence about latent structural-zero membership in the testing fit;
  • evidence about the testing-fit count-state mean;
  • evidence that a regressor contributes to either mechanism;
  • the degree to which the main coefficient patterns agree with the training fit;
  • uncertainty in the corresponding transformed and marginal fitted quantities.

Because the dataset is synthetic, the resulting statements demonstrate ZIP inference but do not support causal or real-population insurance conclusions.

Returning to the inferential inquiry, the clearest testing-set associations are for annual mileage and prior claims. Both are associated with lower structural-zero odds and higher count-state means, both have strong joint two-component Wald results, and both retain the same component directions found in training. Urban area has evidence of a positive count-state association but little evidence in the structural-zero component, while the broader two-component joint result is weaker. Driver age is also less decisive: its zero-component interval narrowly includes the neutral value and its joint result changes classification around the conventional 0.05 threshold across implementations. Vehicle age and the male indicator have comparatively wide testing intervals and do not show strong component-specific or joint evidence. Overall, the train-versus-test comparison does not reveal a large parameter-vector shift, but the wider testing-set intervals and the weak sign changes for some zero-component effects make those smaller patterns less stable than the annual-mileage and prior-claims results. These are adjusted associations within the synthetic ZIP example, not causal effects or conclusions about a real insurance population.

12.12 Interpretation of Fitted Results

The testing-set inferential results in Section 12.11 describe two connected but distinct regression components. This section translates those results into insurance-claims language and then combines the components through fitted marginal quantities. The scenario calculations use the frozen specification fitted on the testing observations, matching the coefficient evidence reported in the preceding section.

The interpretation returns to the inferential inquiry from Section 12.2.1:

How are policyholder and vehicle characteristics associated with the structural-zero probability, the count-generating mean, and the resulting marginal expected number of claims?

12.12.1 Interpreting the zero-inflation coefficients

The zero-inflation component is

\[ \operatorname{logit}(\pi_i) = \mathbf{x}_i^\top\boldsymbol{\alpha}. \tag{12.67}\]

For a one-unit increase in regressor \(x_j\),

\[ \exp(\alpha_j) \tag{12.68}\]

is the multiplicative change in the odds that a policyholder belongs to the latent structural-zero state, holding the other zero-component regressors fixed.

Use wording such as:

Holding the other zero-component regressors fixed, a one-unit increase in \(x_j\) is associated with multiplying the odds of latent structural-zero membership by \(\exp(\widehat{\alpha}_j)\).

Do not describe \(\exp(\widehat{\alpha}_j)\) as the odds ratio for observing zero claims. An observed zero can also arise from the Poisson count state.

12.12.2 Interpreting the count coefficients

The count component is

\[ \log(\lambda_i) = \mathbf{x}_i^\top\boldsymbol{\beta}. \tag{12.69}\]

For a one-unit increase in regressor \(x_j\),

\[ \exp(\beta_j) \tag{12.70}\]

is the multiplicative change in the expected number of claims among policyholders in the count-generating state, holding the other count-component regressors fixed.

Use wording such as:

Among policyholders in the count-generating state, and holding the other count-component regressors fixed, a one-unit increase in \(x_j\) is associated with multiplying the expected number of claims by \(\exp(\widehat{\beta}_j)\).

This is not generally the multiplicative change in the marginal expected count because the marginal mean also depends on \(\pi_i\).

The two coefficient blocks should first be interpreted on their own component-specific scales. Only after that should they be combined into marginal fitted quantities.

This order matters because an \(\alpha\) coefficient changes the odds of latent structural-zero membership, while a \(\beta\) coefficient changes the count-state mean. A reader should not infer the marginal expected-count effect from either coefficient alone (Lambert 1992; Cameron and Trivedi 2013).

12.12.3 Meaningful units for the running example

The scaled variables introduced during model fitting give the following one-unit comparisons:

  • driver_age_10: a 10-year increase in driver age;
  • annual_mileage_10k: a 10,000-kilometre increase in annual mileage;
  • vehicle_age_5: a five-year increase in vehicle age;
  • male: male coding \(1\) compared with female coding \(0\);
  • urban_area: urban coding \(1\) compared with rural coding \(0\);
  • prior_claims: prior-claims coding \(1\) compared with no-prior-claims coding \(0\).

These units should be used consistently in the coefficient table, written interpretation, and scenario comparisons.

12.12.4 When the two component effects reinforce or compete

A ZIP regressor can affect the two mechanisms in directions that reinforce or compete with one another. For a continuous regressor that appears in both components,

\[ \frac{\partial\log(\mu_i)}{\partial x_{ij}} = \beta_j-\pi_i\alpha_j. \tag{12.71}\]

This derivative depends on the policyholder-specific structural-zero probability. There is generally no one constant marginal rate ratio analogous to Classical Poisson regression.

Table 12.47: How the directions of the two ZIP coefficients combine for the marginal mean.
\(\alpha_j\) \(\beta_j\) Effect on \(\pi_i\) Effect on \(\lambda_i\) Effect on \(\mu_i\)
Positive Positive Increases Increases Competing mechanisms
Negative Negative Decreases Decreases Competing mechanisms
Positive Negative Increases Decreases Both reduce the marginal mean
Negative Positive Decreases Increases Both increase the marginal mean

The case in which \(\alpha_j>0\) and \(\beta_j>0\) is not contradictory. It describes a more polarized fitted distribution: the policyholder is more likely to belong to the structural-zero state, but the expected count is larger among policyholders who remain in the count-generating state. The marginal expected count may increase or decrease depending on which mechanism dominates for the profile being examined.

12.12.5 Scenario-based marginal interpretation

The final substantive interpretation should compare realistic policyholder scenarios rather than relying only on coefficient signs. For each comparison, report

  • \(\widehat{\pi}\): structural-zero probability;
  • \(\widehat{\lambda}\): count-state mean;
  • \(\widehat{\mu}=(1-\widehat{\pi})\widehat{\lambda}\): marginal expected claims;
  • \(\widehat{p}_0\): probability of observing zero claims.
predict_zip_quantities_r <- function(model, new_data) {
  fitted_pi <- as.numeric(
    predict(
      model,
      newdata = new_data,
      type = "zero"
    )
  )

  fitted_lambda <- as.numeric(
    predict(
      model,
      newdata = new_data,
      type = "count"
    )
  )

  fitted_mu <- as.numeric(
    predict(
      model,
      newdata = new_data,
      type = "response"
    )
  )

  tibble(
    fitted_pi = fitted_pi,
    fitted_lambda = fitted_lambda,
    fitted_mu = fitted_mu,
    fitted_p_zero =
      fitted_pi +
      (1 - fitted_pi) * exp(-fitted_lambda)
  )
}
def predict_zip_quantities_py(result, X_count, X_zero):
    return pd.DataFrame({
        "fitted_pi": (
            1 - result.predict(
                exog=X_count,
                exog_infl=X_zero,
                which="prob-main",
            )
        ),
        "fitted_lambda": result.predict(
            exog=X_count,
            exog_infl=X_zero,
            which="mean-main",
        ),
        "fitted_mu": result.predict(
            exog=X_count,
            exog_infl=X_zero,
            which="mean",
        ),
        "fitted_p_zero": result.predict(
            exog=X_count,
            exog_infl=X_zero,
            which="prob-zero",
        ),
    })

The scenario comparisons below hold the remaining regressors at the same reference values and change one regressor at a time. This produces a direct before-versus-after comparison of the fitted ZIP quantities.

The table reports:

  • the change in structural-zero probability;
  • the ratio of count-state means;
  • the change in marginal expected claims;
  • the change in the probability of observing zero claims.
zip_reference_profile_r <- tibble(
  driver_age_10 = median(zip_testing_r$driver_age_10),
  annual_mileage_10k = median(zip_testing_r$annual_mileage_10k),
  vehicle_age_5 = median(zip_testing_r$vehicle_age_5),
  male = as.integer(
    names(sort(table(zip_testing_r$male), decreasing = TRUE))[1]
  ),
  urban_area = as.integer(
    names(sort(table(zip_testing_r$urban_area), decreasing = TRUE))[1]
  ),
  prior_claims = as.integer(
    names(sort(table(zip_testing_r$prior_claims), decreasing = TRUE))[1]
  )
)

zip_scenario_specs_r <- tribble(
  ~term, ~comparison, ~change,
  "driver_age_10", "+10 years of driver age", 1,
  "annual_mileage_10k", "+10,000 km of annual mileage", 1,
  "vehicle_age_5", "+5 years of vehicle age", 1,
  "male", "male (1) versus female (0)", 1,
  "urban_area", "urban (1) versus rural (0)", 1,
  "prior_claims", "prior claims (1) versus none (0)", 1
)

zip_scenario_interpretation_r <- purrr::pmap_dfr(
  zip_scenario_specs_r,
  function(term, comparison, change) {
    reference_profile <- zip_reference_profile_r
    comparison_profile <- zip_reference_profile_r

    if (term %in% c("male", "urban_area", "prior_claims")) {
      reference_profile[[term]] <- 0
      comparison_profile[[term]] <- 1
    } else {
      comparison_profile[[term]] <-
        reference_profile[[term]] + change
    }

    reference_fit <- predict_zip_quantities_r(
      zip_test_model_r,
      reference_profile
    )

    comparison_fit <- predict_zip_quantities_r(
      zip_test_model_r,
      comparison_profile
    )

    tibble(
      term = term,
      comparison = comparison,
      reference_pi = reference_fit$fitted_pi,
      comparison_pi = comparison_fit$fitted_pi,
      change_in_pi =
        comparison_fit$fitted_pi - reference_fit$fitted_pi,
      lambda_ratio =
        comparison_fit$fitted_lambda / reference_fit$fitted_lambda,
      reference_mu = reference_fit$fitted_mu,
      comparison_mu = comparison_fit$fitted_mu,
      change_in_mu =
        comparison_fit$fitted_mu - reference_fit$fitted_mu,
      reference_p_zero = reference_fit$fitted_p_zero,
      comparison_p_zero = comparison_fit$fitted_p_zero,
      change_in_p_zero =
        comparison_fit$fitted_p_zero - reference_fit$fitted_p_zero
    )
  }
)
zip_reference_profile_py = {
    "driver_age_10": zip_testing_py["driver_age_10"].median(),
    "annual_mileage_10k": zip_testing_py["annual_mileage_10k"].median(),
    "vehicle_age_5": zip_testing_py["vehicle_age_5"].median(),
    "male": int(zip_testing_py["male"].mode().iloc[0]),
    "urban_area": int(zip_testing_py["urban_area"].mode().iloc[0]),
    "prior_claims": int(zip_testing_py["prior_claims"].mode().iloc[0]),
}

zip_scenario_specs_py = [
    ("driver_age_10", "+10 years of driver age", 1),
    ("annual_mileage_10k", "+10,000 km of annual mileage", 1),
    ("vehicle_age_5", "+5 years of vehicle age", 1),
    ("male", "male (1) versus female (0)", 1),
    ("urban_area", "urban (1) versus rural (0)", 1),
    ("prior_claims", "prior claims (1) versus none (0)", 1),
]

scenario_rows_py = []

for term, comparison, change in zip_scenario_specs_py:
    reference_profile = zip_reference_profile_py.copy()
    comparison_profile = zip_reference_profile_py.copy()

    if term in ["male", "urban_area", "prior_claims"]:
        reference_profile[term] = 0
        comparison_profile[term] = 1
    else:
        comparison_profile[term] += change

    reference_row = pd.DataFrame([reference_profile])
    comparison_row = pd.DataFrame([comparison_profile])

    X_count_reference = sm.add_constant(
        reference_row[zip_covariates_py],
        has_constant="add",
    )
    X_zero_reference = X_count_reference.copy()

    X_count_comparison = sm.add_constant(
        comparison_row[zip_covariates_py],
        has_constant="add",
    )
    X_zero_comparison = X_count_comparison.copy()

    reference_fit = predict_zip_quantities_py(
        zip_test_result_py,
        X_count_reference,
        X_zero_reference,
    )

    comparison_fit = predict_zip_quantities_py(
        zip_test_result_py,
        X_count_comparison,
        X_zero_comparison,
    )

    scenario_rows_py.append({
        "term": term,
        "comparison": comparison,
        "reference_pi": reference_fit["fitted_pi"][0],
        "comparison_pi": comparison_fit["fitted_pi"][0],
        "change_in_pi":
            comparison_fit["fitted_pi"][0]
            - reference_fit["fitted_pi"][0],
        "lambda_ratio":
            comparison_fit["fitted_lambda"][0]
            / reference_fit["fitted_lambda"][0],
        "reference_mu": reference_fit["fitted_mu"][0],
        "comparison_mu": comparison_fit["fitted_mu"][0],
        "change_in_mu":
            comparison_fit["fitted_mu"][0]
            - reference_fit["fitted_mu"][0],
        "reference_p_zero": reference_fit["fitted_p_zero"][0],
        "comparison_p_zero": comparison_fit["fitted_p_zero"][0],
        "change_in_p_zero":
            comparison_fit["fitted_p_zero"][0]
            - reference_fit["fitted_p_zero"][0],
    })

zip_scenario_interpretation_py = pd.DataFrame(
    scenario_rows_py
)
Table 12.48: Scenario-based changes in ZIP component and marginal fitted quantities using R.
Table 12.49: Scenario-based changes in ZIP component and marginal fitted quantities using Python.

The scenario results in Table 12.48 and Table 12.49 show how the two ZIP components combine on interpretable fitted scales. The strongest changes occur for prior claims and annual mileage. For the prior-claims comparison, the fitted structural-zero probability falls from 56.1% to 25.9%, while the count-state mean is multiplied by 1.75. Combining those mechanisms increases the marginal expected number of claims from 1.087 to 3.215, an increase of about 2.128 claims, while the fitted probability of observing zero claims falls by about 33.0 percentage points.

A 10,000-km annual-mileage increase produces the same qualitative combination. The structural-zero probability falls from 56.1% to 28.0%, the count-state mean is multiplied by 1.592, and the marginal expected count rises by about 1.754 claims. The fitted observed-zero probability decreases by about 30.4 percentage points.

The remaining scenario point estimates move in the same reinforcing direction, but the preceding inferential results show that they are less precisely estimated. A 10-year increase in driver age lowers the fitted structural-zero probability by about 7.0 percentage points, increases the count-state mean by a factor of 1.077, and raises the fitted marginal mean by about 0.2721 claims. For urban versus rural driving, the structural-zero change is small, while the count-state mean ratio is 1.352, so most of the fitted marginal increase comes from the count mechanism. Vehicle age and the male indicator also have positive marginal point changes, but their component intervals include the neutral values and should therefore not be given the same inferential weight as annual mileage or prior claims.

Importantly, none of the six scenario point estimates in this fitted example has the two ZIP mechanisms moving in opposite directions. For every comparison shown, the structural-zero probability decreases while the count-state mean increases. The mechanisms therefore reinforce one another in the point estimates, making the direction of the resulting marginal mean and observed-zero probability easier to read. In another ZIP application, competing component directions could produce a much less obvious marginal result.

A useful reading order for a ZIP regressor is:

  1. Zero component: Does the regressor make structural-zero membership more or less likely?
  2. Count component: Does it increase or decrease the expected count among observations remaining in the count-generating state?
  3. Marginal mean: After combining both mechanisms, does the overall expected number of observed claims increase or decrease?
  4. Observed-zero probability: After allowing for both structural zeros and ordinary Poisson zeros, does the probability of observing claims = 0 increase or decrease?

The third and fourth questions are often the most directly communicable to an applied audience, but the first two explain why those marginal changes occur.

12.12.6 Interpreting uncertainty in the scenarios

The scenario comparisons above translate the two ZIP components into fitted quantities that are easier to communicate. In particular, the marginal expected number of claims for a policyholder profile is

\[ \mu_i = \mathbb{E}(Y_i\mid\mathbf{x}_i) = (1-\pi_i)\lambda_i. \tag{12.72}\]

The values reported in Table 12.48 and Table 12.49 are point estimates. They tell us what the fitted testing-set ZIP model implies for each reference and comparison profile, but they do not yet show how precisely the corresponding marginal means have been estimated.

The inferential target here is therefore the conditional mean response, \(\mu_i=\mathbb{E}(Y_i\mid\mathbf{x}_i)\). The confidence interval we construct answers:

How uncertain are we about the expected number of claims for a policyholder with this fixed covariate profile?

This is not a new kind of target that appears only in ZIP regression. Chapter 3 introduces the familiar fitted response in Results: Predictive Analysis, where OLS uses \(\widehat{\mu}_i=\mathbf{x}_i^\top\widehat{\boldsymbol{\beta}}\). That chapter does not develop the profile-level mean-response confidence interval explicitly, but the underlying quantity is the same conditional mean. A closer cookbook precedent for carrying uncertainty through a response-scale transformation appears in Chapter 8, Results and Statistical Interpretation: Probability-Scale Comparisons (Section 8.13.4), where uncertainty in a fitted Logistic Regression linear predictor is transformed into uncertainty for a fitted probability. Chapter 10, Prediction with Poisson Regression (Section 10.10), similarly emphasizes that the Poisson model predicts a positive expected count, rather than an exact future count.

ZIP regression keeps that same response-scale goal but adds one complication: its marginal mean combines two fitted mechanisms. The fitted mean can change because the fitted structural-zero probability \(\widehat{\pi}_i\) changes, because the fitted count-state mean \(\widehat{\lambda}_i\) changes, or because both change together. Consequently, uncertainty in \(\widehat{\mu}_i\) depends on the joint uncertainty of the zero-inflation and count coefficients, including their estimated covariance.

For this subsection, the reference and comparison policyholder profiles are treated as fixed scenarios. We do not repeatedly change which profile is being described. Instead, we ask how much the estimated marginal mean for those same profiles would vary because the ZIP coefficients themselves were estimated from a finite sample.

This is an inferential calculation. The coefficient estimates and covariance matrix therefore come from the testing-set refit, matching the inferential workflow used in the preceding sections. The later prediction section continues to use the training-fitted model for held-out prediction.

Heads-up on the covariates in the two ZIP components

For consistency with the running example and with Data Modelling: Modelling the parameters with covariates earlier in this chapter, we continue to use the same covariate vector \(\mathbf{x}_i\) in both ZIP components:

\[ \log(\lambda_i) = \mathbf{x}_i^\top\boldsymbol{\beta} \]

and

\[ \operatorname{logit}(\pi_i) = \mathbf{x}_i^\top\boldsymbol{\alpha}. \]

This does not mean that a ZIP model must use the same regressors in both components. The count and zero-inflation components may use different covariate sets when that choice is substantively justified. The present notation simply reflects the specification used in the insurance-claims running example. If different design vectors were used, the uncertainty calculation below would proceed in the same way with the corresponding component-specific vectors.

Propagating uncertainty to the marginal mean

For the current specification, the count-state mean and structural-zero probability are

\[ \lambda_i = \exp\left( \mathbf{x}_i^\top\boldsymbol{\beta} \right) \]

and

\[ \pi_i = \operatorname{logit}^{-1} \left( \mathbf{x}_i^\top\boldsymbol{\alpha} \right). \]

Combining them gives

\[ \mu_i = \frac{ \exp\left( \mathbf{x}_i^\top\boldsymbol{\beta} \right) }{ 1+ \exp\left( \mathbf{x}_i^\top\boldsymbol{\alpha} \right) }. \tag{12.73}\]

Because \(\mu_i>0\), it is convenient to work with its logarithm:

\[ \log(\mu_i) = \mathbf{x}_i^\top\boldsymbol{\beta} - \log\left[ 1+ \exp\left( \mathbf{x}_i^\top\boldsymbol{\alpha} \right) \right]. \tag{12.74}\]

Why introduce this transformation and then take a derivative?

The fitted mean depends on estimated coefficients, and those coefficients have sampling uncertainty. To approximate how that uncertainty changes \(\log(\widehat{\mu}_i)\), we need to know how sensitive the fitted log mean is to small changes in each coefficient. The gradient collects those local sensitivities into one vector.

Let the joint parameter vector be ordered as

\[ \boldsymbol{\theta} = \begin{pmatrix} \boldsymbol{\alpha}\\ \boldsymbol{\beta} \end{pmatrix}, \]

and define

\[ h_i(\boldsymbol{\theta}) = \log(\mu_i). \]

The delta method will use the gradient

\[ \nabla_{\boldsymbol{\theta}} h_i(\boldsymbol{\theta}) \]

to translate uncertainty in \(\widehat{\boldsymbol{\theta}}\) into uncertainty in the fitted log mean.

Tip on where the ZIP gradient comes from

Start from

\[ h_i(\boldsymbol{\theta}) = \mathbf{x}_i^\top\boldsymbol{\beta} - \log\left[ 1+ \exp\left( \mathbf{x}_i^\top\boldsymbol{\alpha} \right) \right]. \]

First consider the count coefficients. The only term involving \(\boldsymbol{\beta}\) is the count linear predictor, so

\[ \frac{ \partial h_i }{ \partial\boldsymbol{\beta} } = \mathbf{x}_i. \]

For the zero-inflation coefficients, let

\[ \eta_{\alpha,i} = \mathbf{x}_i^\top\boldsymbol{\alpha}. \]

Using the chain rule,

\[ \begin{aligned} \frac{ \partial }{ \partial\boldsymbol{\alpha} } \left\{ -\log\left[ 1+\exp(\eta_{\alpha,i}) \right] \right\} &= - \frac{ \exp(\eta_{\alpha,i}) }{ 1+\exp(\eta_{\alpha,i}) } \frac{ \partial\eta_{\alpha,i} }{ \partial\boldsymbol{\alpha} } \\[6pt] &= -\pi_i\mathbf{x}_i. \end{aligned} \]

The fraction

\[ \frac{ \exp(\eta_{\alpha,i}) }{ 1+\exp(\eta_{\alpha,i}) } \]

is exactly the structural-zero probability \(\pi_i\).

Because we ordered the joint parameter vector as \(\boldsymbol{\theta}=(\boldsymbol{\alpha}^\top,\boldsymbol{\beta}^\top)^\top\), stacking the two derivatives gives

\[ \nabla_{\boldsymbol{\theta}} \log(\mu_i) = \begin{pmatrix} -\pi_i\mathbf{x}_i\\[4pt] \mathbf{x}_i \end{pmatrix}. \tag{12.75}\]

The signs also have a direct ZIP interpretation. Increasing a count coefficient in the direction of \(\mathbf{x}_i\) raises the count-state mean. Increasing a zero-inflation coefficient raises structural-zero probability and therefore pushes the marginal mean downward. The factor \(\pi_i\) means that the local zero-component contribution also depends on the profile’s current structural-zero probability.

Let

\[ \widehat{\mathbf V} = \widehat{\operatorname{Var}} \left( \widehat{\boldsymbol{\theta}} \right) \]

be the full testing-set covariance matrix, and let

\[ \widehat{\mathbf g}_i = \nabla_{\boldsymbol{\theta}} \log(\widehat{\mu}_i) \]

be the fitted gradient from Equation 12.75.

Tip on where the delta-method variance comes from

The delta method uses a first-order Taylor approximation. If \(h(\boldsymbol{\theta})\) is a smooth function of the coefficient vector, then near the true parameter value,

\[ h(\widehat{\boldsymbol{\theta}}) \approx h(\boldsymbol{\theta}) + \nabla h(\boldsymbol{\theta})^\top \left( \widehat{\boldsymbol{\theta}} - \boldsymbol{\theta} \right). \]

The first term is constant with respect to the sampling variation in \(\widehat{\boldsymbol{\theta}}\). The approximate variance therefore comes from the linear term:

\[ \operatorname{Var} \left[ h(\widehat{\boldsymbol{\theta}}) \right] \approx \nabla h(\boldsymbol{\theta})^\top \operatorname{Var} \left( \widehat{\boldsymbol{\theta}} \right) \nabla h(\boldsymbol{\theta}). \]

Replacing the unknown quantities with their fitted estimates gives the familiar delta-method form

\[ \widehat{\operatorname{Var}} \left[ h(\widehat{\boldsymbol{\theta}}) \right] \approx \widehat{\mathbf g}^\top \widehat{\mathbf V} \widehat{\mathbf g}. \]

The connection to OLS is especially useful. In Chapter 3, Results: Predictive Analysis in Chapter 3, the fitted response is based on the linear mean function

\[ h(\boldsymbol{\beta}) = \mu_i = \mathbf{x}_i^\top\boldsymbol{\beta}. \]

For that linear function,

\[ \nabla_{\boldsymbol{\beta}} h(\boldsymbol{\beta}) = \mathbf{x}_i, \]

so the covariance propagation becomes

\[ \operatorname{Var} ( \widehat{\mu}_i ) = \mathbf{x}_i^\top \widehat{\operatorname{Var}} ( \widehat{\boldsymbol{\beta}} ) \mathbf{x}_i. \]

For OLS, this variance result is exact because the conditional mean is already linear in the coefficients. ZIP has the same inferential target, but \(\mu_i\) is nonlinear in two coefficient blocks, so the delta method uses a local linear approximation.

The same broad logic also underlies the transformed response-scale intervals in Chapter 8, Results and Statistical Interpretation: Probability-Scale Comparisons (Section 8.13.4): uncertainty is first characterized on a fitted model scale and then carried to the response quantity of interest.

Applying this result to \(h_i(\boldsymbol{\theta})=\log(\mu_i)\) gives

\[ \widehat{\operatorname{Var}} \left[ \log(\widehat{\mu}_i) \right] \approx \widehat{\mathbf g}_i^\top \widehat{\mathbf V} \widehat{\mathbf g}_i. \tag{12.76}\]

The corresponding standard error is

\[ \operatorname{SE} \left[ \log(\widehat{\mu}_i) \right] = \sqrt{ \widehat{\mathbf g}_i^\top \widehat{\mathbf V} \widehat{\mathbf g}_i }. \tag{12.77}\]

We can now return to the inferential target: a confidence interval for the conditional mean response \(\mu_i=\mathbb{E}(Y_i\mid\mathbf{x}_i)\).

An approximate 95% Wald confidence interval is first constructed on the log-mean scale,

\[ \log(\widehat{\mu}_i) \pm 1.96\, \operatorname{SE} \left[ \log(\widehat{\mu}_i) \right], \]

and then transformed back to the expected-count scale:

\[ \left[ \exp\left( \log(\widehat{\mu}_i) - 1.96\, \operatorname{SE} \left[ \log(\widehat{\mu}_i) \right] \right), \; \exp\left( \log(\widehat{\mu}_i) + 1.96\, \operatorname{SE} \left[ \log(\widehat{\mu}_i) \right] \right) \right]. \tag{12.78}\]

Working on the log-mean scale is convenient because transforming the endpoints back through the exponential function keeps the confidence interval for \(\mu_i\) positive.

The matrix multiplication in Equation 12.76 uses the full joint covariance matrix. We do not calculate one uncertainty contribution from the count component and another from the zero-inflation component and then treat those contributions as independent. Their estimated covariance is retained automatically.

Confidence intervals for means are not predictive intervals

The interval in Equation 12.78 quantifies uncertainty about the expected number of claims for a fixed profile.

It does not quantify the range of claim counts that a future policyholder might actually experience. A future response remains random and integer-valued even if \(\mu_i\) were known exactly. This is the same distinction emphasized for expected counts in Chapter 10, Prediction with Poisson Regression (Section 10.10). The later ZIP prediction section therefore treats future-outcome uncertainty separately through the full ZIP predictive distribution.

Uncertainty in the reference-to-comparison change

Tip on the reference and comparison marginal means

The quantities \(\mu_{\operatorname{ref}}\) and \(\mu_{\operatorname{comp}}\) are not new ZIP parameters. They are the same marginal mean function,

\[ \mu(\mathbf{x}) = \mathbb{E}(Y\mid\mathbf{x}) = (1-\pi(\mathbf{x}))\lambda(\mathbf{x}), \]

evaluated at two different covariate profiles.

Let

\[ \mathbf{x}_{\operatorname{ref}} \]

denote a reference profile, and let

\[ \mathbf{x}_{\operatorname{comp}} \]

denote a comparison profile in which one covariate has been changed while the remaining covariates are held fixed.

Using the same fitted ZIP coefficient vector, the two marginal means are

\[ \mu_{\operatorname{ref}} = \mu\left( \mathbf{x}_{\operatorname{ref}}; \boldsymbol{\theta} \right) \]

and

\[ \mu_{\operatorname{comp}} = \mu\left( \mathbf{x}_{\operatorname{comp}}; \boldsymbol{\theta} \right). \]

Thus, the distinction is between the covariate values being supplied to the model, not between two different fitted models.

For the insurance-claims example, the scenario analysis begins from a representative policyholder profile constructed from the testing data. The continuous covariates are held at their testing-set median values and the binary covariates at typical testing-set values, except for the covariate being varied in the scenario.

For example, in the annual-mileage scenario,

\[ \mathbf{x}_{\operatorname{ref}} \]

contains the reference policyholder characteristics, while

\[ \mathbf{x}_{\operatorname{comp}} \]

keeps those same characteristics but increases annual mileage by 10,000 km. The two fitted means are therefore

\[ \mu_{\operatorname{ref}} = \text{expected claims for the reference mileage profile} \]

and

\[ \mu_{\operatorname{comp}} = \text{expected claims for the otherwise identical profile with 10,000 additional km}. \]

For a binary comparison, such as prior claims, the same idea applies. The reference profile sets prior_claims = 0, while the comparison profile sets prior_claims = 1, with the remaining characteristics held fixed.

The scenario contrast

\[ \Delta\mu = \mu_{\operatorname{comp}} - \mu_{\operatorname{ref}} \]

therefore measures the fitted change in the marginal expected number of claims associated with moving from the reference profile to the comparison profile.

A useful way to keep the notation straight is:

\[ \boxed{ \text{same fitted model} + \text{different fixed profiles} \longrightarrow \mu_{\operatorname{ref}} \text{ and } \mu_{\operatorname{comp}} } \]

The later uncertainty calculation asks how precisely this model-implied difference has been estimated.

For each scenario, the main response-scale contrast is

\[ \Delta\mu = \mu_{\operatorname{comp}} - \mu_{\operatorname{ref}}. \tag{12.79}\]

This quantity asks how much the expected response changes between the fixed comparison and reference profiles. In a simple additive OLS model, a one-variable profile contrast often reduces directly to a scaled regression coefficient. In ZIP, the same response-scale contrast must combine the changes occurring through both \(\pi_i\) and \(\lambda_i\).

Both fitted means come from the same testing-set model, so their estimation errors are correlated. We therefore need a confidence interval for the difference itself rather than comparing the overlap of two separate mean-response confidence intervals.

Tip on moving from the log-mean gradient back to the mean scale

Recalling Equation 12.74, we previously worked with

\[ \log(\mu_i) = \mathbf{x}_i^\top\boldsymbol{\beta} - \log\left[ 1+ \exp\left( \mathbf{x}_i^\top\boldsymbol{\alpha} \right) \right]. \]

Working on the log scale was convenient because it gave us a relatively simple gradient for the marginal mean. However, the reference-to-comparison contrast that we ultimately want to study is

\[ \Delta\mu = \mu_{\operatorname{comp}} - \mu_{\operatorname{ref}}, \]

which is defined on the original expected-count scale, not on the log scale.

Therefore, before constructing the gradient for \(\Delta\mu\), we need to move from

\[ \nabla_{\boldsymbol{\theta}} \log(\mu_i) \]

back to

\[ \nabla_{\boldsymbol{\theta}} \mu_i. \]

Because \(\mu_i>0\), \(\log(\mu_i)\) is well defined, and we can write

\[ \mu_i = \exp\left[ \log(\mu_i) \right]. \]

Now differentiate both sides with respect to the parameter vector \(\boldsymbol{\theta}\):

\[ \nabla_{\boldsymbol{\theta}} \mu_i = \nabla_{\boldsymbol{\theta}} \exp\left[ \log(\mu_i) \right]. \]

Using the chain rule,

\[ \nabla_{\boldsymbol{\theta}} \exp\left[ \log(\mu_i) \right] = \exp\left[ \log(\mu_i) \right] \nabla_{\boldsymbol{\theta}} \log(\mu_i). \]

Since

\[ \exp\left[ \log(\mu_i) \right] = \mu_i, \]

we obtain

\[ \boxed{ \nabla_{\boldsymbol{\theta}} \mu_i = \mu_i \nabla_{\boldsymbol{\theta}} \log(\mu_i) }. \]

Thus, the gradient on the original mean scale is obtained by multiplying the log-mean gradient by the marginal mean itself. Using Equation 12.75,

\[ \nabla_{\boldsymbol{\theta}} \mu_i = \mu_i \begin{pmatrix} -\pi_i\mathbf{x}_i\\[4pt] \mathbf{x}_i \end{pmatrix} = \begin{pmatrix} -\mu_i\pi_i\mathbf{x}_i\\[4pt] \mu_i\mathbf{x}_i \end{pmatrix}. \]

This conversion is needed because the confidence interval for the scenario contrast is constructed for the difference in marginal expected counts, \(\Delta\mu\), rather than for a difference in log marginal means.

For one profile,

\[ \nabla_{\boldsymbol{\theta}} \mu_i = \mu_i \nabla_{\boldsymbol{\theta}} \log(\mu_i). \]

To mirror the comparison-minus-reference definition of \(\Delta\mu\), first define the change in the response-gradient:

\[ \Delta \left( \nabla_{\boldsymbol{\theta}}\mu \right) = \nabla_{\boldsymbol{\theta}} \mu_{\operatorname{comp}} - \nabla_{\boldsymbol{\theta}} \mu_{\operatorname{ref}}. \tag{12.80}\]

Because differentiation is a linear operator,

\[ \begin{aligned} \Delta \left( \nabla_{\boldsymbol{\theta}}\mu \right) &= \nabla_{\boldsymbol{\theta}} \mu_{\operatorname{comp}} - \nabla_{\boldsymbol{\theta}} \mu_{\operatorname{ref}} \\[4pt] &= \nabla_{\boldsymbol{\theta}} \left( \mu_{\operatorname{comp}} - \mu_{\operatorname{ref}} \right) \\[4pt] &= \nabla_{\boldsymbol{\theta}} \Delta\mu. \end{aligned} \tag{12.81}\]

For the variance calculation, denote this common gradient by

\[ \mathbf g_{\Delta} = \nabla_{\boldsymbol{\theta}} \Delta\mu. \]

The delta-method variance for the fitted difference is then

\[ \widehat{\operatorname{Var}} ( \widehat{\Delta\mu} ) \approx \widehat{\mathbf g}_{\Delta}^\top \widehat{\mathbf V} \widehat{\mathbf g}_{\Delta}. \tag{12.82}\]

Unlike \(\mu_i\), the difference \(\Delta\mu\) can legitimately be positive, zero, or negative. Its approximate 95% Wald confidence interval is therefore constructed directly on the response-difference scale:

\[ \boxed{ \widehat{\Delta\mu} \pm 1.96\, \operatorname{SE} ( \widehat{\Delta\mu} ).} \tag{12.83}\]

This is the interval that tells us how precisely the model has estimated the change in the expected number of claims between the two fixed scenarios.

Heads-up on the connection to earlier regression chapters

The target of this calculation can be linked to several earlier parts of the cookbook.

  • OLS — Chapter 3, Results: Predictive Analysis in Chapter 3: the fitted response is based on the conditional mean \(\mathbb{E}(Y_i\mid\mathbf{x}_i)=\mathbf{x}_i^\top\boldsymbol{\beta}\). ZIP targets the same kind of conditional mean, but that mean is nonlinear and contains two coefficient blocks.
  • Binary Logistic Regression — Chapter 8, Results and Statistical Interpretation: Probability-Scale Comparisons (Section 8.13.4): uncertainty is carried from the fitted model scale to a nonlinear response-scale probability for fixed profiles.
  • Classical Poisson Regression — Chapter 10, Prediction with Poisson Regression (Section 10.10): the fitted response is interpreted as an expected count rather than an exact future count. Chapter 10, Results and Statistical Interpretation: Wald Tests in Classical Poisson Regression (Section 10.11.2), also provides the coefficient-level Wald framework that the present delta-method calculation extends.

ZIP combines these ideas. The inferential target remains a fitted conditional mean, but

\[ \mathbb{E}(Y_i\mid\mathbf{x}_i) = (1-\pi_i)\lambda_i \]

depends jointly on the zero-inflation and count components.

The following code applies the calculation to the same reference and comparison profiles used in the preceding scenario table. Because the running example uses the same regressors in both ZIP components, the implementation also uses one x_profile design vector. The derivatives are assigned to the model parameters by name, so differences in the internal parameter ordering used by R and Python do not change the calculation.

zip_wald_critical_value_r <- qnorm(0.975)

zip_delta_profile_design_r <- function(profile, term_names) {
  available_terms <- c(
    `(Intercept)` = 1,
    driver_age_10 = as.numeric(profile$driver_age_10),
    annual_mileage_10k = as.numeric(profile$annual_mileage_10k),
    vehicle_age_5 = as.numeric(profile$vehicle_age_5),
    male = as.numeric(profile$male),
    urban_area = as.numeric(profile$urban_area),
    prior_claims = as.numeric(profile$prior_claims)
  )

  available_terms[term_names]
}

zip_delta_profile_r <- function(model, profile) {
  theta_hat <- coef(model)

  covariance_matrix <- vcov(model)[
    names(theta_hat),
    names(theta_hat),
    drop = FALSE
  ]

  count_terms <- names(
    coef(model, model = "count")
  )

  zero_terms <- names(
    coef(model, model = "zero")
  )

  if (!identical(count_terms, zero_terms)) {
    stop(
      paste(
        "This chapter implementation expects the same regressors",
        "in the count and zero-inflation components."
      )
    )
  }

  x_profile <- zip_delta_profile_design_r(
    profile,
    count_terms
  )

  beta_hat <- coef(
    model,
    model = "count"
  )[count_terms]

  alpha_hat <- coef(
    model,
    model = "zero"
  )[zero_terms]

  eta_count <- sum(
    x_profile * beta_hat
  )

  eta_zero <- sum(
    x_profile * alpha_hat
  )

  fitted_pi <- plogis(
    eta_zero
  )

  fitted_lambda <- exp(
    eta_count
  )

  fitted_mu <-
    (1 - fitted_pi) *
    fitted_lambda

  gradient_log_mu <- setNames(
    numeric(length(theta_hat)),
    names(theta_hat)
  )

  gradient_log_mu[
    paste0("zero_", zero_terms)
  ] <- -fitted_pi * x_profile

  gradient_log_mu[
    paste0("count_", count_terms)
  ] <- x_profile

  variance_log_mu <- as.numeric(
    t(gradient_log_mu) %*%
      covariance_matrix %*%
      gradient_log_mu
  )

  se_log_mu <- sqrt(
    max(variance_log_mu, 0)
  )

  log_mu <- log(
    fitted_mu
  )

  mu_ci_low <- exp(
    log_mu -
      zip_wald_critical_value_r *
        se_log_mu
  )

  mu_ci_high <- exp(
    log_mu +
      zip_wald_critical_value_r *
        se_log_mu
  )

  gradient_mu <-
    fitted_mu *
    gradient_log_mu

  list(
    fitted_pi = fitted_pi,
    fitted_lambda = fitted_lambda,
    fitted_mu = fitted_mu,
    mu_ci_low = mu_ci_low,
    mu_ci_high = mu_ci_high,
    gradient_mu = gradient_mu
  )
}

zip_test_theta_names_delta_r <- names(
  coef(zip_test_model_r)
)

zip_test_vcov_delta_r <- vcov(
  zip_test_model_r
)[
  zip_test_theta_names_delta_r,
  zip_test_theta_names_delta_r,
  drop = FALSE
]

zip_scenario_uncertainty_r <- purrr::map_dfr(
  seq_len(
    nrow(zip_scenario_definitions_r)
  ),
  function(row_index) {
    definition <-
      zip_scenario_definitions_r[
        row_index,
      ]

    term_name <- definition$term

    reference_profile <-
      zip_reference_profile_r

    comparison_profile <-
      zip_reference_profile_r

    if (definition$binary) {
      reference_profile[[term_name]] <- 0
      comparison_profile[[term_name]] <- 1
    } else {
      comparison_profile[[term_name]] <-
        comparison_profile[[term_name]] + 1
    }

    reference_summary <- zip_delta_profile_r(
      zip_test_model_r,
      reference_profile
    )

    comparison_summary <- zip_delta_profile_r(
      zip_test_model_r,
      comparison_profile
    )

    gradient_change <-
      comparison_summary$gradient_mu -
      reference_summary$gradient_mu

    gradient_change <- gradient_change[
      zip_test_theta_names_delta_r
    ]

    variance_change <- as.numeric(
      t(gradient_change) %*%
        zip_test_vcov_delta_r %*%
        gradient_change
    )

    se_change <- sqrt(
      max(variance_change, 0)
    )

    change_in_mu <-
      comparison_summary$fitted_mu -
      reference_summary$fitted_mu

    tibble(
      comparison = definition$comparison,
      reference_mu =
        reference_summary$fitted_mu,
      reference_mu_ci_low =
        reference_summary$mu_ci_low,
      reference_mu_ci_high =
        reference_summary$mu_ci_high,
      comparison_mu =
        comparison_summary$fitted_mu,
      comparison_mu_ci_low =
        comparison_summary$mu_ci_low,
      comparison_mu_ci_high =
        comparison_summary$mu_ci_high,
      change_in_mu = change_in_mu,
      change_in_mu_ci_low =
        change_in_mu -
        zip_wald_critical_value_r *
          se_change,
      change_in_mu_ci_high =
        change_in_mu +
        zip_wald_critical_value_r *
          se_change
    )
  }
)
from scipy.special import expit

zip_wald_critical_value_py = 1.96

zip_test_theta_delta_py = (
    zip_test_result_py.params
    .astype(float)
    .copy()
)

zip_test_vcov_delta_py = (
    zip_test_result_py
    .cov_params()
    .astype(float)
    .loc[
        zip_test_theta_delta_py.index,
        zip_test_theta_delta_py.index,
    ]
)

zip_count_parameter_names_delta_py = [
    "const",
    *zip_covariates_py,
]

zip_zero_parameter_names_delta_py = [
    f"inflate_{name}"
    for name
    in zip_count_parameter_names_delta_py
]

def zip_delta_profile_design_py(profile):
    return pd.Series(
        {
            "const": 1.0,
            **{
                name: float(
                    profile.iloc[0][name]
                )
                for name
                in zip_covariates_py
            },
        },
        dtype=float,
    )

def zip_delta_profile_py(result, profile):
    theta_hat = (
        result.params
        .astype(float)
        .copy()
    )

    covariance_matrix = (
        result.cov_params()
        .astype(float)
        .loc[
            theta_hat.index,
            theta_hat.index,
        ]
    )

    missing_count = [
        name
        for name in zip_count_parameter_names_delta_py
        if name not in theta_hat.index
    ]

    missing_zero = [
        name
        for name in zip_zero_parameter_names_delta_py
        if name not in theta_hat.index
    ]

    if missing_count or missing_zero:
        raise ValueError(
            "The fitted ZIP parameter names do not match "
            "the chapter's same-regressor specification."
        )

    x_profile = (
        zip_delta_profile_design_py(
            profile
        )
        .loc[
            zip_count_parameter_names_delta_py
        ]
    )

    beta_hat = (
        theta_hat
        .loc[
            zip_count_parameter_names_delta_py
        ]
        .to_numpy()
    )

    alpha_hat = (
        theta_hat
        .loc[
            zip_zero_parameter_names_delta_py
        ]
        .to_numpy()
    )

    eta_count = float(
        x_profile.to_numpy()
        @ beta_hat
    )

    eta_zero = float(
        x_profile.to_numpy()
        @ alpha_hat
    )

    fitted_pi = float(
        expit(eta_zero)
    )

    fitted_lambda = float(
        np.exp(eta_count)
    )

    fitted_mu = (
        (1 - fitted_pi)
        * fitted_lambda
    )

    gradient_log_mu = pd.Series(
        0.0,
        index=theta_hat.index,
        dtype=float,
    )

    gradient_log_mu.loc[
        zip_zero_parameter_names_delta_py
    ] = (
        -fitted_pi
        * x_profile.to_numpy()
    )

    gradient_log_mu.loc[
        zip_count_parameter_names_delta_py
    ] = x_profile.to_numpy()

    gradient_array = (
        gradient_log_mu
        .to_numpy()
    )

    covariance_array = (
        covariance_matrix
        .to_numpy()
    )

    variance_log_mu = float(
        gradient_array
        @ covariance_array
        @ gradient_array
    )

    se_log_mu = np.sqrt(
        max(
            variance_log_mu,
            0.0,
        )
    )

    log_mu = np.log(
        fitted_mu
    )

    mu_ci_low = np.exp(
        log_mu
        - zip_wald_critical_value_py
        * se_log_mu
    )

    mu_ci_high = np.exp(
        log_mu
        + zip_wald_critical_value_py
        * se_log_mu
    )

    gradient_mu = (
        fitted_mu
        * gradient_log_mu
    )

    return {
        "fitted_pi": fitted_pi,
        "fitted_lambda": fitted_lambda,
        "fitted_mu": fitted_mu,
        "mu_ci_low": mu_ci_low,
        "mu_ci_high": mu_ci_high,
        "gradient_mu": gradient_mu,
    }

scenario_uncertainty_rows_py = []

for (
    term_name,
    comparison_label,
    is_binary,
) in zip_scenario_definitions_py:

    reference_profile = (
        zip_reference_profile_py.copy()
    )

    comparison_profile = (
        zip_reference_profile_py.copy()
    )

    if is_binary:
        reference_profile[term_name] = 0
        comparison_profile[term_name] = 1
    else:
        comparison_profile[term_name] = (
            comparison_profile[term_name]
            + 1
        )

    reference_summary = zip_delta_profile_py(
        zip_test_result_py,
        reference_profile,
    )

    comparison_summary = zip_delta_profile_py(
        zip_test_result_py,
        comparison_profile,
    )

    gradient_change = (
        comparison_summary["gradient_mu"]
        - reference_summary["gradient_mu"]
    )

    gradient_change_array = (
        gradient_change
        .loc[
            zip_test_theta_delta_py.index
        ]
        .to_numpy()
    )

    covariance_array = (
        zip_test_vcov_delta_py
        .to_numpy()
    )

    variance_change = float(
        gradient_change_array
        @ covariance_array
        @ gradient_change_array
    )

    se_change = np.sqrt(
        max(
            variance_change,
            0.0,
        )
    )

    change_in_mu = (
        comparison_summary["fitted_mu"]
        - reference_summary["fitted_mu"]
    )

    scenario_uncertainty_rows_py.append(
        {
            "comparison": comparison_label,
            "reference_mu":
                reference_summary["fitted_mu"],
            "reference_mu_ci_low":
                reference_summary["mu_ci_low"],
            "reference_mu_ci_high":
                reference_summary["mu_ci_high"],
            "comparison_mu":
                comparison_summary["fitted_mu"],
            "comparison_mu_ci_low":
                comparison_summary["mu_ci_low"],
            "comparison_mu_ci_high":
                comparison_summary["mu_ci_high"],
            "change_in_mu":
                change_in_mu,
            "change_in_mu_ci_low":
                change_in_mu
                - zip_wald_critical_value_py
                * se_change,
            "change_in_mu_ci_high":
                change_in_mu
                + zip_wald_critical_value_py
                * se_change,
        }
    )

zip_scenario_uncertainty_py = pd.DataFrame(
    scenario_uncertainty_rows_py
)
Table 12.50: Delta-method 95% confidence intervals for scenario-based marginal expected claims using R.
Table 12.51: Delta-method 95% confidence intervals for scenario-based marginal expected claims using Python.

The intervals in Table 12.50 and Table 12.51 add uncertainty statements to the scenario point estimates; they do not redefine the scenarios themselves.

For each row, the reference interval describes uncertainty in the marginal expected count for the fixed reference profile. The comparison interval describes uncertainty in the marginal expected count after the stated covariate change. The final three columns are usually the most directly useful for the scenario question because they summarize the estimated change in expected claims and its uncertainty.

A confidence interval for Change in Marginal Mean that remains entirely above zero supports a positive marginal expected-count difference for that stated comparison under the large-sample approximation. An interval that remains entirely below zero supports a negative difference. If the interval includes zero, the point estimate may still be positive or negative, but the testing-set refit is not precise enough to distinguish that marginal difference clearly from zero at the 95% Wald level.

The reference and comparison intervals should not be assessed by asking whether they overlap. Those two fitted means come from the same fitted coefficient vector and are correlated. The interval for Change in Marginal Mean propagates that dependence directly and is therefore the appropriate interval for the scenario contrast.

The delta-method intervals in Table 12.50 and Table 12.51 separate the six fitted scenario changes into two groups. The estimated marginal changes for driver age, annual mileage, and prior claims remain entirely above zero at the 95% level. For a 10-year increase in driver age, the fitted marginal mean increases by 0.2721 claims, with a 95% interval from 0.04607 to 0.4981. By contrast, the intervals for vehicle age, sex, and urban area include zero. None of the six scenario-change intervals is entirely below zero. Thus, the scenario table suggests positive fitted marginal changes for all six point estimates, but only three of those changes are estimated precisely enough for their 95% intervals to remain on the positive side of zero.

The two largest and most precisely estimated marginal changes are the same covariates that showed the clearest two-component evidence earlier: annual mileage and prior claims. For the +10,000-km mileage scenario, the reference marginal mean is 1.087 claims and the comparison mean is 2.841, giving an estimated increase of 1.754 claims with a 95% interval from 0.9569 to 2.551. For prior claims versus none, the fitted marginal mean rises from 1.087 to 3.215 claims, an estimated increase of 2.128 with a 95% interval from 1.292 to 2.963. These positive marginal contrasts are consistent with the earlier component-level findings: both covariates reduce the fitted structural-zero probability while increasing the count-state mean, so the two mechanisms reinforce one another rather than offsetting each other.

The remaining contrasts are less uniform in precision. A 10-year increase in driver age has a smaller estimated marginal increase whose interval nevertheless remains above zero, even though the separate count-component rate-ratio interval and structural-zero odds-ratio interval both include their neutral values. This is not a contradiction: Change in Marginal Mean is a different nonlinear contrast that combines both ZIP components and their joint covariance. For a 5-year increase in vehicle age, the fitted change is 0.3012 claims with a 95% interval from -0.3401 to 0.9426. The male-versus-female contrast is 0.3111 with an interval from -0.1066 to 0.7288, and the urban-versus-rural contrast is 0.3156 with an interval from -0.08769 to 0.719. All three intervals include zero. In particular, the urban result complements the earlier component-level table: its testing-set count-state rate ratio is above 1 with an interval narrowly excluding 1, but the zero component is imprecise and the combined marginal scenario contrast is not estimated precisely enough for its own interval to exclude zero.

Tip on coefficient simulation and bootstrap alternatives

The delta method is one way to construct uncertainty intervals for the fitted conditional mean

\[ \mu_i = \mathbb{E}(Y_i\mid\mathbf{x}_i). \]

Two useful alternatives are coefficient simulation and nonparametric bootstrap refitting. These methods target the same underlying inferential quantity but propagate coefficient uncertainty in different ways.

With coefficient simulation, generate plausible joint coefficient vectors from

\[ \boldsymbol{\theta}^{(b)} \sim N\left( \widehat{\boldsymbol{\theta}}, \widehat{\mathbf V} \right), \]

keep the scenario profiles fixed, and recompute \(\mu_{\operatorname{ref}}^{(b)}\), \(\mu_{\operatorname{comp}}^{(b)}\), and \(\Delta\mu^{(b)}\) for each draw. Percentiles of those simulated fitted quantities can then be used as approximate confidence limits. This approach avoids writing the gradient explicitly, but it still relies on the same large-sample Normal approximation for the joint coefficient vector and introduces Monte Carlo variation through the finite number of simulation draws.

With a nonparametric bootstrap, repeatedly resample observations with replacement, refit the same frozen ZIP specification, and recompute the fitted quantities for the same fixed profiles. In this inferential subsection, the bootstrap would resample the testing observations because the model being summarized is the testing-set refit. In the later held-out predictive workflow, a bootstrap would instead resample the training observations while keeping the selected testing profiles fixed.

Bootstrap refitting reproduces more of the estimation process, but it is computationally more expensive because the ZIP model must be optimized many times. Some bootstrap samples may also produce convergence or numerical-stability problems; those failures should be monitored and reported rather than silently discarded.

For a general discussion of the delta method and bootstrap reasoning, see Wasserman (2004). For the count-model context, see Cameron and Trivedi (2013).

The delta-method intervals are used as the main calculation here because they extend the same covariance-based Wald logic used elsewhere in the cookbook to the ZIP marginal mean. Coefficient simulation and bootstrap refitting remain useful alternatives when a different balance between analytical approximation, simulation, and computational cost is preferred.

12.12.7 Returning to the inferential inquiry

The written conclusion should follow this sequence:

  1. state the zero-component association;
  2. state the count-component association;
  3. explain whether the mechanisms reinforce or compete;
  4. report the resulting fitted marginal change;
  5. acknowledge the associated uncertainty;
  6. avoid causal language.

Because the dataset is synthetic, these interpretations demonstrate the ZIP workflow rather than describing a real insurance population.

The fitted ZIP story is therefore driven most clearly by annual mileage and prior-claims history. In the testing-set fit, higher mileage and prior claims are associated with a lower fitted probability of structural-zero membership and a higher mean within the count-generating state. The scenario calculations show that these two mechanisms combine to produce higher marginal expected claim counts and lower probabilities of observing zero claims, while Table 12.50 and Table 12.51 show that both corresponding marginal-mean changes remain clearly positive after accounting for estimation uncertainty. Urban driving is associated mainly with the count-state mean, whereas the fitted results for driver age, vehicle age, and the male indicator are less precise. The scenario table remains essential for this conclusion: the component-specific odds ratios and rate ratios describe different latent mechanisms and should not individually be read as the total change in the observed claim response.

12.13 Prediction with the ZIP Model

We now return to the predictive inquiry introduced in Section 12.2.1:

How well can the available policyholder and vehicle characteristics predict claim-related quantities for policyholders not used to fit the model?

The predictions in this section come from the ZIP model fitted on the training data. The separate testing-set fit from Section 12.11 is not used to generate them. The testing responses are used only to score the predictions produced by the training-fitted parameter vector.

ZIP regression provides several predictive quantities:

  1. the marginal expected count \(\widehat{\mu}_i=(1-\widehat{\pi}_i)\widehat{\lambda}_i\);
  2. the probability of an observed zero \(\widehat{p}_{0,i}\);
  3. the probability of a particular count \(\widehat{P}(Y_i=k\mid\mathbf{x}_i)\);
  4. a simulated count from the fitted predictive distribution.

The latent structural-zero probability \(\widehat{\pi}_i\) can be reported as a model component, but it cannot be scored directly against an observed structural-state label.

12.13.1 Generating testing-set predictions from the training fit

zip_testing_r <- test_data |>
  mutate(
    driver_age_10 = driver_age / 10,
    annual_mileage_10k = annual_mileage / 10000,
    vehicle_age_5 = vehicle_age / 5
  )

zip_test_predictions_r <- zip_testing_r |>
  mutate(
    predicted_mu = as.numeric(
      predict(
        zip_model_r,
        newdata = zip_testing_r,
        type = "response"
      )
    ),
    predicted_lambda = as.numeric(
      predict(
        zip_model_r,
        newdata = zip_testing_r,
        type = "count"
      )
    ),
    predicted_pi = as.numeric(
      predict(
        zip_model_r,
        newdata = zip_testing_r,
        type = "zero"
      )
    ),
    predicted_p_zero =
      predicted_pi +
      (1 - predicted_pi) * exp(-predicted_lambda)
  )
zip_testing_py = testing_data.copy()

zip_testing_py["driver_age_10"] = (
    pd.to_numeric(zip_testing_py["driver_age"], errors="coerce") / 10
)
zip_testing_py["annual_mileage_10k"] = (
    pd.to_numeric(zip_testing_py["annual_mileage"], errors="coerce") / 10000
)
zip_testing_py["vehicle_age_5"] = (
    pd.to_numeric(zip_testing_py["vehicle_age"], errors="coerce") / 5
)

for column in zip_covariates_py + ["claims"]:
    zip_testing_py[column] = pd.to_numeric(
        zip_testing_py[column],
        errors="coerce",
    )

zip_testing_py = zip_testing_py.dropna(
    subset=zip_covariates_py + ["claims"]
).copy()

X_count_test_py = sm.add_constant(
    zip_testing_py[zip_covariates_py].astype(float),
    has_constant="add",
)
X_zero_test_py = X_count_test_py.copy()

zip_test_predictions_py = zip_testing_py.copy()
zip_test_predictions_py["predicted_mu"] = zip_result_py.predict(
    exog=X_count_test_py,
    exog_infl=X_zero_test_py,
    which="mean",
)
zip_test_predictions_py["predicted_lambda"] = zip_result_py.predict(
    exog=X_count_test_py,
    exog_infl=X_zero_test_py,
    which="mean-main",
)
zip_test_predictions_py["predicted_pi"] = (
    1 - zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="prob-main",
    )
)
zip_test_predictions_py["predicted_p_zero"] = zip_result_py.predict(
    exog=X_count_test_py,
    exog_infl=X_zero_test_py,
    which="prob-zero",
)

These predictions use the testing regressors but retain the coefficients estimated from the training observations.

12.13.2 ZIP prediction metric guide

A ZIP model produces more than one kind of prediction, so no single metric can evaluate every aspect of predictive performance.

The held-out testing assessment therefore asks three different questions:

  1. How accurate is the predicted marginal expected count?
    Use point-prediction metrics on \(\widehat{\mu}_i\).

  2. How accurate is the predicted probability that the observed count equals zero?
    Use probability scores for the binary event \(Y_i=0\).

  3. How much probability does the model assign to the exact count that actually occurs?
    Use a scoring rule for the complete ZIP predictive distribution.

These metrics are complementary. A model can predict the marginal mean reasonably well while assigning poor probabilities to zeros or to the individual count values. Conversely, a model can improve probability forecasts without producing a dramatic reduction in point-prediction error.

The comparisons below use only simple training-derived baselines:

  • the training mean for marginal expected-count prediction;
  • the training zero probability for predicting the event \(Y=0\);
  • the training count probabilities for scoring the complete count distribution.

The goal is to ask whether the fitted ZIP model improves on what could be predicted without using the testing observation’s covariates.

12.13.3 Point-prediction metrics for the marginal mean

Let \(\widehat{\mu}_i\) denote the ZIP prediction of the marginal expected number of claims for testing observation \(i\).

The Mean Error is

\[ \operatorname{MeanError} = \frac{1}{n_{\operatorname{test}}} \sum_i \left( Y_i-\widehat{\mu}_i \right). \tag{12.84}\]

This is a signed measure. A positive value means that observed counts tend to exceed the predictions; a negative value means predictions tend to exceed observed counts. Because positive and negative errors can cancel, Mean Error is mainly a check for systematic overprediction or underprediction rather than total predictive accuracy.

The Mean Absolute Error (MAE) is

\[ \operatorname{MAE} = \frac{1}{n_{\operatorname{test}}} \sum_i \left| Y_i-\widehat{\mu}_i \right|. \tag{12.85}\]

MAE is the average absolute prediction error in the same units as the response: number of claims. It answers a direct practical question: How far, on average, is the predicted expected count from the observed count? Every absolute error contributes linearly (Kuhn and Johnson 2013).

The Root Mean Squared Error (RMSE) is

\[ \operatorname{RMSE} = \sqrt{ \frac{1}{n_{\operatorname{test}}} \sum_i \left( Y_i-\widehat{\mu}_i \right)^2 }. \tag{12.86}\]

RMSE is also measured in claims, but squaring the errors before averaging gives larger misses more influence. Comparing MAE and RMSE can therefore help reveal whether a small number of larger errors are materially affecting point-prediction performance (Kuhn and Johnson 2013).

For both MAE and RMSE, smaller is better. Their most useful interpretation here is relative to the training-mean baseline.

12.13.4 Metrics for predicting observed zeros

Define the observed-zero indicator

\[ Z_i = \mathbb{I}(Y_i=0). \tag{12.87}\]

The ZIP forecast for this event is the fitted probability

\[ \widehat{p}_{0,i} = \widehat{P}(Y_i=0\mid\mathbf{x}_i). \tag{12.88}\]

The Brier score is

\[ \operatorname{Brier} = \frac{1}{n_{\operatorname{test}}} \sum_i \left( Z_i-\widehat{p}_{0,i} \right)^2. \tag{12.89}\]

It is the mean squared error of a probability forecast for the binary event “zero claims”. A probability close to \(1\) is rewarded when a zero occurs and penalized when a positive count occurs; the reverse holds for probabilities close to \(0\). A smaller Brier score indicates better probability predictions (Brier 1950; Gneiting and Raftery 2007).

The zero-event log loss is

\[ \operatorname{LogLoss}_0 = - \frac{1}{n_{\operatorname{test}}} \sum_i \left[ Z_i\log(\widehat{p}_{0,i}) + (1-Z_i)\log(1-\widehat{p}_{0,i}) \right]. \tag{12.90}\]

Log loss places a particularly large penalty on confidently wrong probability forecasts. For example, assigning a probability very close to zero to an event that actually occurs is penalized much more heavily than assigning a moderate probability. Smaller values are better (Gneiting and Raftery 2007).

These two metrics evaluate the observable event \(Y_i=0\). They do not evaluate whether a zero was structural, because structural-zero membership is latent.

12.13.5 Scoring the complete ZIP predictive distribution

Point metrics use only \(\widehat{\mu}_i\), and the zero-event metrics use only \(\widehat{p}_{0,i}\). A ZIP model, however, supplies a complete predictive probability mass function

\[ \widehat{P}(Y_i=k\mid\mathbf{x}_i), \qquad k=0,1,2,\ldots \tag{12.91}\]

for each testing observation.

A simple way to evaluate this complete distribution is to record the probability assigned to the count that actually occurred. The negative log predictive mass is

\[ -\log \widehat{P} \left( Y_i=y_i \mid \mathbf{x}_i \right). \tag{12.92}\]

Averaging this quantity across the testing observations gives a distributional score. Smaller values are better because they mean that, on average, the model assigned more probability to the counts that were actually observed.

This score matters because two models can have similar predicted means while distributing probability very differently across \(0,1,2,\ldots\). The log score evaluates the whole predictive distribution, not only its centre (Gneiting and Raftery 2007).

The complete-distribution log score uses the probability assigned to the observed testing count:

\[ -\frac{1}{n_{\operatorname{test}}} \sum_i \log \left[ \widehat{P}(Y_i=y_i\mid\mathbf{x}_i) \right]. \tag{12.93}\]

This score is more faithful to ZIP than copying the Classical Poisson deviance unchanged. Two ZIP predictions can have the same marginal mean but assign different probabilities to zero and to the positive counts.

12.13.6 Held-out marginal-mean performance

We first compare the ZIP marginal-mean predictions with a simple baseline that assigns every testing observation the mean claim count observed in the training data.

The code below calculates the three metrics defined above for both approaches. The same testing outcomes are used in both rows; what changes is the prediction being scored.

zip_training_mean_r <- mean(zip_training_r$claims)

zip_point_metrics_r <- bind_rows(
  tibble(
    model = "Training mean",
    mean_error = mean(
      zip_test_predictions_r$claims -
        zip_training_mean_r
    ),
    MAE = mean(
      abs(
        zip_test_predictions_r$claims -
          zip_training_mean_r
      )
    ),
    RMSE = sqrt(
      mean(
        (
          zip_test_predictions_r$claims -
            zip_training_mean_r
        )^2
      )
    )
  ),
  tibble(
    model = "ZIP",
    mean_error = mean(
      zip_test_predictions_r$claims -
        zip_test_predictions_r$predicted_mu
    ),
    MAE = mean(
      abs(
        zip_test_predictions_r$claims -
          zip_test_predictions_r$predicted_mu
      )
    ),
    RMSE = sqrt(
      mean(
        (
          zip_test_predictions_r$claims -
            zip_test_predictions_r$predicted_mu
        )^2
      )
    )
  )
)
training_mean_py = zip_training_py["claims"].mean()

observed_test_py = (
    zip_test_predictions_py["claims"]
    .to_numpy(dtype=float)
)

zip_point_metrics_py = pd.DataFrame([
    {
        "model": "Training mean",
        "mean_error": np.mean(
            observed_test_py - training_mean_py
        ),
        "MAE": np.mean(
            np.abs(
                observed_test_py - training_mean_py
            )
        ),
        "RMSE": np.sqrt(
            np.mean(
                (
                    observed_test_py -
                    training_mean_py
                ) ** 2
            )
        ),
    },
    {
        "model": "ZIP",
        "mean_error": np.mean(
            observed_test_py -
            zip_test_predictions_py[
                "predicted_mu"
            ].to_numpy(dtype=float)
        ),
        "MAE": np.mean(
            np.abs(
                observed_test_py -
                zip_test_predictions_py[
                    "predicted_mu"
                ].to_numpy(dtype=float)
            )
        ),
        "RMSE": np.sqrt(
            np.mean(
                (
                    observed_test_py -
                    zip_test_predictions_py[
                        "predicted_mu"
                    ].to_numpy(dtype=float)
                ) ** 2
            )
        ),
    },
])
Table 12.52: Held-out marginal-mean prediction metrics for the training-mean baseline and ZIP model using R.
Table 12.53: Held-out marginal-mean prediction metrics for the training-mean baseline and ZIP model using Python.

The held-out point-prediction results in Table 12.52 and Table 12.53 favour the covariate-dependent ZIP predictions over the constant training-mean baseline. Because Mean Error is defined as observed minus predicted, the baseline value of 0.03125 indicates slight average underprediction, while the ZIP value of -0.006266 indicates only a very small average overprediction. In both cases the signed average error is close to zero, so Mean Error alone provides little separation. The absolute-error metrics are more informative: MAE decreases from 1.681 to 1.268 claims, a reduction of about 24.6%. Thus, the typical absolute discrepancy between an observed testing count and its predicted marginal mean is about 1.27 claims under ZIP rather than 1.68 under the constant baseline. RMSE similarly falls from 2.052 to 1.667, so ZIP also performs better when larger count errors receive extra weight.

12.13.7 Held-out observed-zero performance

The next comparison evaluates the event \(Y_i=0\).

The baseline assigns every testing policyholder the same zero probability, equal to the proportion of zero claims observed in the training data. ZIP instead assigns a covariate-dependent probability \(\widehat{p}_{0,i}\) to each testing policyholder.

The code calculates the Brier score and zero-event log loss for both sets of probability forecasts.


zip_training_zero_probability_r <-
  mean(zip_training_r$claims == 0)

zip_zero_indicator_r <-
  as.integer(zip_test_predictions_r$claims == 0)

binary_probability_scores_r <- function(
  model_name,
  probabilities
) {
  clipped_probabilities <- pmin(
    pmax(probabilities, 1e-12),
    1 - 1e-12
  )

  tibble(
    model = model_name,
    zero_brier_score = mean(
      (
        zip_zero_indicator_r -
          probabilities
      )^2
    ),
    zero_log_loss = -mean(
      zip_zero_indicator_r *
        log(clipped_probabilities)
      +
      (1 - zip_zero_indicator_r) *
        log(1 - clipped_probabilities)
    )
  )
}

zip_probability_metrics_r <- bind_rows(
  binary_probability_scores_r(
    "Training zero probability",
    rep(
      zip_training_zero_probability_r,
      nrow(zip_test_predictions_r)
    )
  ),
  binary_probability_scores_r(
    "ZIP",
    zip_test_predictions_r$predicted_p_zero
  )
)

training_zero_probability_py = (
    zip_training_py["claims"] == 0
).mean()

zero_indicator_py = (
    zip_test_predictions_py["claims"] == 0
).astype(float).to_numpy()

def binary_probability_scores_py(
    model_name,
    probabilities,
):
    probabilities = np.asarray(
        probabilities,
        dtype=float,
    )

    clipped_probabilities = np.clip(
        probabilities,
        1e-12,
        1 - 1e-12,
    )

    return {
        "model": model_name,
        "zero_brier_score": np.mean(
            (
                zero_indicator_py -
                probabilities
            ) ** 2
        ),
        "zero_log_loss": -np.mean(
            zero_indicator_py *
            np.log(clipped_probabilities)
            +
            (1 - zero_indicator_py) *
            np.log(1 - clipped_probabilities)
        ),
    }

zip_probability_metrics_py = pd.DataFrame([
    binary_probability_scores_py(
        "Training zero probability",
        np.full(
            len(zip_test_predictions_py),
            training_zero_probability_py,
        ),
    ),
    binary_probability_scores_py(
        "ZIP",
        zip_test_predictions_py[
            "predicted_p_zero"
        ].to_numpy(dtype=float),
    ),
])
Table 12.54: Held-out observed-zero prediction scores for the training zero-probability baseline and ZIP model using R.
Table 12.55: Held-out observed-zero prediction scores for the training zero-probability baseline and ZIP model using Python.

The zero-event probability scores in Table 12.54 and Table 12.55 also favour ZIP. The Brier score decreases from 0.2493 for the constant training zero-probability baseline to 0.2078 for the ZIP probabilities. The zero-event log loss similarly decreases from 0.6917 to 0.6046. Because lower values are better for both metrics, the testing outcomes support using the covariate-dependent ZIP probabilities rather than assigning every policyholder the same zero probability estimated from the training set. The improvement is not a statement that every individual zero probability is correct; it is an aggregate held-out comparison of probability forecasts.

12.13.8 Held-out complete-distribution performance

Finally, we evaluate the complete count distribution.

For the baseline, we estimate a probability distribution over the observed count values using the training response frequencies. Add-one smoothing is used so that a count value absent from the training sample does not receive an exact probability of zero.

For ZIP, the fitted training model produces a separate probability mass function for each testing observation. We then extract the probability assigned to the count that actually occurred and average the negative log predictive mass.


zip_test_count_grid_r <- 0:max(
  c(
    zip_training_r$claims,
    zip_test_predictions_r$claims
  )
)

# Baseline distribution estimated from training counts.
zip_training_count_probabilities_r <- tibble(
  claims = zip_test_count_grid_r,
  count = vapply(
    zip_test_count_grid_r,
    function(count_value) {
      sum(zip_training_r$claims == count_value)
    },
    numeric(1)
  )
) |>
  mutate(
    probability =
      (count + 1) /
      (
        sum(count) +
        length(zip_test_count_grid_r)
      )
  )

zip_training_probability_lookup_r <- setNames(
  zip_training_count_probabilities_r$probability,
  zip_training_count_probabilities_r$claims
)

training_observed_mass_r <- unname(
  zip_training_probability_lookup_r[
    as.character(
      zip_test_predictions_r$claims
    )
  ]
)

# ZIP probability mass for every testing row and count value.
zip_test_probability_matrix_r <- predict(
  zip_model_r,
  newdata = zip_testing_r,
  type = "prob",
  at = zip_test_count_grid_r
)

zip_observed_mass_r <- zip_test_probability_matrix_r[
  cbind(
    seq_len(nrow(zip_test_predictions_r)),
    match(
      zip_test_predictions_r$claims,
      zip_test_count_grid_r
    )
  )
]

zip_distribution_score_r <- tibble(
  model = c(
    "Training count probabilities",
    "ZIP"
  ),
  mean_negative_log_predictive_mass = c(
    mean(
      -log(
        pmax(
          training_observed_mass_r,
          1e-12
        )
      )
    ),
    mean(
      -log(
        pmax(
          zip_observed_mass_r,
          1e-12
        )
      )
    )
  )
)

zip_test_count_grid_py = np.arange(
    0,
    int(
        max(
            zip_training_py["claims"].max(),
            zip_test_predictions_py["claims"].max(),
        )
    ) + 1,
)

# Baseline distribution estimated from training counts.
training_counts_py = np.array([
    (zip_training_py["claims"] == value).sum()
    for value in zip_test_count_grid_py
], dtype=float)

training_count_probabilities_py = (
    training_counts_py + 1
) / (
    training_counts_py.sum()
    + len(zip_test_count_grid_py)
)

training_probability_lookup_py = dict(
    zip(
        zip_test_count_grid_py,
        training_count_probabilities_py,
    )
)

training_observed_mass_py = np.array([
    training_probability_lookup_py[int(value)]
    for value in zip_test_predictions_py["claims"]
])

# ZIP probability mass for every testing row and count value.
zip_test_probability_matrix_py = np.asarray(
    zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="prob",
        y_values=zip_test_count_grid_py,
    ),
    dtype=float,
)

observed_columns_py = np.array([
    np.where(
        zip_test_count_grid_py == int(value)
    )[0][0]
    for value in zip_test_predictions_py["claims"]
])

zip_observed_mass_py = (
    zip_test_probability_matrix_py[
        np.arange(
            len(zip_test_predictions_py)
        ),
        observed_columns_py,
    ]
)

zip_distribution_score_py = pd.DataFrame({
    "model": [
        "Training count probabilities",
        "ZIP",
    ],
    "mean_negative_log_predictive_mass": [
        np.mean(
            -np.log(
                np.clip(
                    training_observed_mass_py,
                    1e-12,
                    None,
                )
            )
        ),
        np.mean(
            -np.log(
                np.clip(
                    zip_observed_mass_py,
                    1e-12,
                    None,
                )
            )
        ),
    ],
})
Table 12.56: Held-out complete-distribution prediction score for the training count-probability baseline and ZIP model using R.
Table 12.57: Held-out complete-distribution prediction score for the training count-probability baseline and ZIP model using Python.

The complete-distribution comparison in Table 12.56 and Table 12.57 leads to the same qualitative conclusion. The smoothed training count-frequency baseline has a mean negative log predictive mass of 1.584, whereas the ZIP predictive distributions achieve 1.409. The decrease of about 0.1748 means that the covariate-dependent ZIP distributions assigned more probability, on average, to the exact testing counts that were observed. Thus, the predictive advantage is not limited to the expected count or to the zero-versus-nonzero event; it is also visible when the complete discrete outcome distribution is scored.

12.13.9 Summary of prediction metrics

The preceding subsections evaluate several different aspects of held-out ZIP prediction. Table 12.58 collects the ZIP result for each metric in one place so that the predictive assessment can be read as a compact summary rather than as a glossary alone.

Table 12.58: Prediction metrics and held-out ZIP results for the testing data.

12.13.10 Prediction distributions for selected policyholders

An expected count alone does not describe the full ZIP prediction. The following table selects testing observations with low, middle, and high fitted marginal means and reports the corresponding component quantities and count probabilities.

The selected-policyholder table is intended to show what a ZIP prediction contains for an individual observation rather than to summarize model accuracy.

For each selected policyholder, report:

  • the observed claim count;
  • the fitted structural-zero probability;
  • the fitted count-state mean;
  • the fitted marginal expected number of claims;
  • the fitted probability of observing zero claims;
  • optionally, selected positive-count probabilities such as \(P(Y=1)\) and \(P(Y\ge 2)\).

These quantities describe different aspects of the same predictive distribution and should not be interpreted interchangeably.

To make the full predictive distribution concrete, we select three testing observations representing the lowest, middle, and highest fitted marginal means. We then extract the ZIP probabilities of zero claims, exactly one claim, and two or more claims for those same observations.


zip_selected_index_r <- unique(
  c(
    which.min(
      zip_test_predictions_r$predicted_mu
    ),
    order(
      zip_test_predictions_r$predicted_mu
    )[
      ceiling(
        nrow(zip_test_predictions_r) / 2
      )
    ],
    which.max(
      zip_test_predictions_r$predicted_mu
    )
  )
)

selection_labels_r <- c(
  "Low fitted mean",
  "Middle fitted mean",
  "High fitted mean"
)[seq_along(zip_selected_index_r)]

# Probability of exactly one claim for the selected rows.
probability_y_1_r <-
  zip_test_probability_matrix_r[
    cbind(
      zip_selected_index_r,
      match(
        1,
        zip_test_count_grid_r
      )
    )
  ]

zip_selected_predictions_r <-
  zip_test_predictions_r[
    zip_selected_index_r,
  ] |>
  mutate(
    selection = selection_labels_r,
    probability_y_1 = probability_y_1_r,
    probability_y_ge_2 = pmax(
      0,
      1 -
        predicted_p_zero -
        probability_y_1
    )
  ) |>
  select(
    selection,
    row_id,
    claims,
    predicted_pi,
    predicted_lambda,
    predicted_mu,
    predicted_p_zero,
    probability_y_1,
    probability_y_ge_2
  )
  
py$zip_selected_row_ids <- as.integer(
  zip_selected_predictions_r$row_id
)

zip_selected_row_ids_py = np.asarray(
    zip_selected_row_ids,
    dtype=int,
)

testing_row_ids_py = (
    zip_test_predictions_py["row_id"]
    .astype(int)
    .to_numpy()
)

zip_selected_index_py = np.array(
    [
        np.flatnonzero(
            testing_row_ids_py == row_id
        )[0]
        for row_id
        in zip_selected_row_ids_py
    ],
    dtype=int,
)

selection_labels_py = [
    "Low fitted mean",
    "Middle fitted mean",
    "High fitted mean",
]

probability_y_1_column_py = np.flatnonzero(
    zip_test_count_grid_py == 1
)

if len(probability_y_1_column_py) != 1:
    raise ValueError(
        "The testing count grid must contain "
        "exactly one column for Y = 1."
    )

probability_y_1_py = (
    zip_test_probability_matrix_py[
        zip_selected_index_py,
        probability_y_1_column_py[0],
    ]
)

zip_selected_predictions_py = (
    zip_test_predictions_py
    .iloc[zip_selected_index_py]
    .copy()
)

zip_selected_predictions_py.insert(
    0,
    "selection",
    selection_labels_py,
)

zip_selected_predictions_py[
    "probability_y_1"
] = probability_y_1_py

zip_selected_predictions_py[
    "probability_y_ge_2"
] = np.maximum(
    0,
    1
    - zip_selected_predictions_py[
        "predicted_p_zero"
    ]
    - zip_selected_predictions_py[
        "probability_y_1"
    ],
)

zip_selected_predictions_py = (
    zip_selected_predictions_py[[
        "selection",
        "row_id",
        "claims",
        "predicted_pi",
        "predicted_lambda",
        "predicted_mu",
        "predicted_p_zero",
        "probability_y_1",
        "probability_y_ge_2",
    ]]
)
Table 12.59: Selected held-out ZIP prediction distributions using R.
Table 12.60: Selected held-out ZIP prediction distributions using Python.

The selected distributions in Table 12.59 and Table 12.60 show how differently shaped ZIP predictions can arise across policyholder profiles. For the low fitted-mean profile, the marginal expected count is only 0.1512, and the fitted probability of observing zero claims is 90.9%; only about 4.2% of the predictive mass lies at two or more claims. The middle profile has a fitted mean of about 1.255 but still retains a 57.0% probability of an observed zero, while about 34.8% of its probability lies at two or more claims. This combination of substantial mass at zero and a positive right tail is a characteristic feature of the ZIP distribution.

At the high fitted-mean profile, the balance changes sharply: the fitted marginal mean is 6.825, the probability of an observed zero falls to 3.9%, and 95.6% of the predictive mass lies at two or more claims. The observed testing counts shown in the table are retained only for held-out assessment. A single realised count does not prove that an individual probability distribution was correct or incorrect.

12.13.11 Uncertainty in expected counts versus future outcomes

The prediction distributions above describe what the fitted ZIP model assigns to different count values for selected testing observations. Those probabilities are plug-in predictions: they condition on the coefficient estimates obtained from the training fit and treat those estimates as fixed.

There is a second source of uncertainty to consider. The fitted coefficients themselves were estimated from a finite training sample. Consequently, uncertainty about the coefficient vector induces uncertainty about fitted quantities such as the marginal expected count

\[ \mu_i = (1-\pi_i)\lambda_i. \tag{12.94}\]

A confidence interval for \(\mu_i\) and a predictive interval for a future count answer different questions.

A confidence interval for the marginal expected count asks:

How uncertain are we about the expected number of claims for a policyholder with these covariates?

A predictive interval for a future observed count asks:

After accounting for both coefficient uncertainty and the inherent randomness of the ZIP response, what observed claim counts are plausible for a policyholder with these covariates?

The distinction matters because an expected count is not itself a future observed count. Even if the ZIP parameters were known exactly, a future response would remain random and integer-valued.

To make this distinction concrete, we return to the same low-, middle-, and high-fitted-mean testing observations used in the preceding subsection. The covariate profiles come from the testing set, but the coefficient estimates and joint covariance matrix come only from the training-fitted ZIP model. Thus, the calculation preserves the held-out predictive workflow introduced earlier in the chapter.

We use coefficient simulation to propagate estimation uncertainty. Let

\[ \widehat{\boldsymbol{\theta}}_{\operatorname{train}} = \begin{pmatrix} \widehat{\boldsymbol{\beta}}_{\operatorname{train}} \\ \widehat{\boldsymbol{\alpha}}_{\operatorname{train}} \end{pmatrix} \tag{12.95}\]

denote the joint coefficient vector from the training fit, with estimated covariance matrix \(\widehat{\mathbf V}_{\operatorname{train}}\). We generate simulated coefficient vectors according to the asymptotic approximation

\[ \boldsymbol{\theta}^{(b)} \sim N\left( \widehat{\boldsymbol{\theta}}_{\operatorname{train}}, \widehat{\mathbf V}_{\operatorname{train}} \right), \qquad b=1,\ldots,B. \tag{12.96}\]

For testing profile \(i\), each coefficient draw produces

\[ \pi_i^{(b)} = \operatorname{logit}^{-1} \left( \mathbf{x}_i^\top \boldsymbol{\alpha}^{(b)} \right), \tag{12.97}\]

\[ \lambda_i^{(b)} = \exp \left( \mathbf{x}_i^\top \boldsymbol{\beta}^{(b)} \right), \tag{12.98}\]

and therefore

\[ \mu_i^{(b)} = \left( 1-\pi_i^{(b)} \right) \lambda_i^{(b)}. \tag{12.99}\]

The empirical 2.5th and 97.5th percentiles of the simulated \(\mu_i^{(b)}\) values give an approximate 95% confidence interval for the marginal expected count.

To obtain a predictive distribution that additionally includes response randomness, we generate

\[ Y_i^{(b)} \sim \operatorname{ZIP} \left( \pi_i^{(b)}, \lambda_i^{(b)} \right). \tag{12.100}\]

The corresponding empirical quantiles give an approximate 95% predictive interval for a future observed claim count. Because the response is discrete, the predictive-interval endpoints are integer counts and the interval need not be symmetric around the fitted mean (Gelman, Hill, and Vehtari 2021; Jackman 2024; Seabold and Perktold 2010).

# Number of coefficient draws used for the simulation.
zip_uncertainty_draws_r <- 10000L

# Training-fitted coefficient vector and full joint covariance matrix.
zip_theta_hat_r <- coef(
  zip_model_r,
  model = "full"
)
zip_vcov_train_r <- vcov(
  zip_model_r,
  model = "full"
)

# Generate multivariate Normal draws without adding a new package dependency.
zip_mvn_draws_r <- function(
  mean_vector,
  covariance_matrix,
  n_draws,
  seed = 123
) {
  covariance_matrix <-
    (
      covariance_matrix +
        t(covariance_matrix)
    ) / 2

  covariance_eigen <-
    eigen(
      covariance_matrix,
      symmetric = TRUE
    )

  if (min(covariance_eigen$values) < -1e-8) {
    stop(
      "The training covariance matrix is not positive semidefinite."
    )
  }

  covariance_eigen$values <-
    pmax(
      covariance_eigen$values,
      0
    )

  covariance_root <-
    covariance_eigen$vectors %*%
    diag(
      sqrt(covariance_eigen$values),
      nrow = length(covariance_eigen$values)
    ) %*%
    t(covariance_eigen$vectors)

  set.seed(seed)

  standard_normal_draws <-
    matrix(
      rnorm(
        n_draws *
          length(mean_vector)
      ),
      nrow = n_draws
    )

  parameter_draws <-
    sweep(
      standard_normal_draws %*%
        covariance_root,
      2,
      mean_vector,
      FUN = "+"
    )

  colnames(parameter_draws) <-
    names(mean_vector)

  parameter_draws
}

zip_parameter_draws_r <-
  zip_mvn_draws_r(
    mean_vector = zip_theta_hat_r,
    covariance_matrix = zip_vcov_train_r,
    n_draws = zip_uncertainty_draws_r,
    seed = 123
  )

zip_count_terms_r <-
  names(
    coef(
      zip_model_r,
      model = "count"
    )
  )

zip_zero_terms_r <-
  names(
    coef(
      zip_model_r,
      model = "zero"
    )
  )

zip_count_parameter_names_r <-
  paste0(
    "count_",
    zip_count_terms_r
  )

zip_zero_parameter_names_r <-
  paste0(
    "zero_",
    zip_zero_terms_r
  )

# Empirical quantiles for integer-valued predictive draws.
zip_discrete_quantile_r <- function(
  x,
  probability
) {
  sorted_x <- sort(x)
  position <- max(
    1L,
    ceiling(
      probability *
        length(sorted_x)
    )
  )
  sorted_x[position]
}

zip_prediction_uncertainty_r <-
  purrr::map_dfr(
    seq_along(zip_selected_index_r),
    function(j) {

      profile_index <-
        zip_selected_index_r[j]

      profile <-
        zip_testing_r[
          profile_index,
          ,
          drop = FALSE
        ]

      x_count <-
        c(
          `(Intercept)` = 1,
          driver_age_10 =
            profile$driver_age_10,
          annual_mileage_10k =
            profile$annual_mileage_10k,
          vehicle_age_5 =
            profile$vehicle_age_5,
          male =
            profile$male,
          urban_area =
            profile$urban_area,
          prior_claims =
            profile$prior_claims
        )

      x_zero <- x_count

      x_count <-
        x_count[
          zip_count_terms_r
        ]

      x_zero <-
        x_zero[
          zip_zero_terms_r
        ]

      eta_count_draws <-
        as.numeric(
          zip_parameter_draws_r[
            ,
            zip_count_parameter_names_r,
            drop = FALSE
          ] %*%
            x_count
        )

      eta_zero_draws <-
        as.numeric(
          zip_parameter_draws_r[
            ,
            zip_zero_parameter_names_r,
            drop = FALSE
          ] %*%
            x_zero
        )

      lambda_draws <-
        exp(eta_count_draws)

      pi_draws <-
        plogis(eta_zero_draws)

      mu_draws <-
        (
          1 - pi_draws
        ) *
        lambda_draws

      mean_interval <-
        quantile(
          mu_draws,
          probs = c(
            0.025,
            0.975
          ),
          names = FALSE
        )

      # Add response randomness to each simulated parameter vector.
      structural_zero_draw <-
        runif(
          length(pi_draws)
        ) <
        pi_draws

      poisson_draw <-
        rpois(
          length(lambda_draws),
          lambda = lambda_draws
        )

      predictive_draw <-
        ifelse(
          structural_zero_draw,
          0L,
          poisson_draw
        )

      tibble(
        selection =
          selection_labels_r[j],
        row_id =
          profile$row_id,
        claims =
          profile$claims,
        fitted_mu =
          zip_test_predictions_r$
            predicted_mu[
              profile_index
            ],
        expected_count_ci_low =
          mean_interval[1],
        expected_count_ci_high =
          mean_interval[2],
        predictive_interval_low =
          zip_discrete_quantile_r(
            predictive_draw,
            0.025
          ),
        predictive_interval_high =
          zip_discrete_quantile_r(
            predictive_draw,
            0.975
          )
      )
    }
  )
# Number of coefficient draws used for the simulation.
zip_uncertainty_draws_py = 10000

# Training-fitted coefficient vector and full joint covariance matrix.
zip_theta_hat_py = (
    zip_result_py.params
    .astype(float)
    .copy()
)

zip_vcov_train_py = np.asarray(
    zip_result_py.cov_params(),
    dtype=float,
)

# Numerical symmetry protects against very small floating-point discrepancies.
zip_vcov_train_py = (
    zip_vcov_train_py
    + zip_vcov_train_py.T
) / 2

rng_uncertainty_py = np.random.default_rng(123)

zip_parameter_draws_py = rng_uncertainty_py.multivariate_normal(
    mean=zip_theta_hat_py.to_numpy(),
    cov=zip_vcov_train_py,
    size=zip_uncertainty_draws_py,
    check_valid="raise",
)

zip_parameter_draws_py = pd.DataFrame(
    zip_parameter_draws_py,
    columns=zip_theta_hat_py.index,
)

zip_count_parameter_names_py = list(
    X_count_test_py.columns
)

zip_zero_parameter_names_py = [
    f"inflate_{name}"
    for name in X_zero_test_py.columns
]

missing_parameter_names_py = (
    set(
        zip_count_parameter_names_py
        + zip_zero_parameter_names_py
    )
    - set(
        zip_parameter_draws_py.columns
    )
)

if missing_parameter_names_py:
    raise ValueError(
        "The simulated parameter vector does not contain "
        f"the expected ZIP terms: {sorted(missing_parameter_names_py)}"
    )

def discrete_quantile_py(values, probability):
    sorted_values = np.sort(
        np.asarray(
            values,
            dtype=int,
        )
    )
    position = max(
        0,
        int(
            np.ceil(
                probability
                * len(sorted_values)
            )
        ) - 1,
    )
    return int(
        sorted_values[position]
    )

uncertainty_rows_py = []

for j, profile_index in enumerate(
    zip_selected_index_py
):
    x_count = (
        X_count_test_py
        .iloc[profile_index]
        .to_numpy(dtype=float)
    )

    x_zero = (
        X_zero_test_py
        .iloc[profile_index]
        .to_numpy(dtype=float)
    )

    beta_draws = (
        zip_parameter_draws_py[
            zip_count_parameter_names_py
        ]
        .to_numpy(dtype=float)
    )

    alpha_draws = (
        zip_parameter_draws_py[
            zip_zero_parameter_names_py
        ]
        .to_numpy(dtype=float)
    )

    eta_count_draws = (
        beta_draws @ x_count
    )

    eta_zero_draws = (
        alpha_draws @ x_zero
    )

    lambda_draws = np.exp(
        eta_count_draws
    )

    # Stable inverse-logit calculation.
    eta_zero_draws_clipped = np.clip(
        eta_zero_draws,
        -700,
        700,
    )
    pi_draws = (
        1
        / (
            1
            + np.exp(
                -eta_zero_draws_clipped
            )
        )
    )

    mu_draws = (
        1 - pi_draws
    ) * lambda_draws

    mean_interval = np.quantile(
        mu_draws,
        [
            0.025,
            0.975,
        ],
    )

    # Add response randomness to each simulated parameter vector.
    structural_zero_draw = (
        rng_uncertainty_py.random(
            len(pi_draws)
        )
        < pi_draws
    )

    poisson_draw = rng_uncertainty_py.poisson(
        lambda_draws
    )

    predictive_draw = np.where(
        structural_zero_draw,
        0,
        poisson_draw,
    )

    profile = (
        zip_testing_py
        .iloc[profile_index]
    )

    uncertainty_rows_py.append({
        "selection":
            selection_labels_py[j],
        "row_id":
            profile["row_id"],
        "claims":
            profile["claims"],
        "fitted_mu":
            zip_test_predictions_py
            .iloc[profile_index][
                "predicted_mu"
            ],
        "expected_count_ci_low":
            mean_interval[0],
        "expected_count_ci_high":
            mean_interval[1],
        "predictive_interval_low":
            discrete_quantile_py(
                predictive_draw,
                0.025,
            ),
        "predictive_interval_high":
            discrete_quantile_py(
                predictive_draw,
                0.975,
            ),
    })

zip_prediction_uncertainty_py = pd.DataFrame(
    uncertainty_rows_py
)
Table 12.61: Uncertainty in expected counts and future observed counts for selected held-out policyholders using R.
Table 12.62: Uncertainty in expected counts and future observed counts for selected held-out policyholders using Python.

The confidence interval and predictive interval should not be compared as though they were two estimates of the same quantity. The confidence interval describes uncertainty about \(\mu_i\), which is a fitted expectation and can therefore take non-integer values. The predictive interval describes future realizations of \(Y_i\), which remain integer-valued and variable even when \(\mu_i\) is estimated precisely.

The testing response shown in the table is also not used to construct either interval. It is retained only to connect the prediction back to the held-out observation after the predictive quantities have been calculated.

The intervals in Table 12.61 show that uncertainty about the fitted expected count increases in absolute width as the selected fitted mean increases. For the low fitted-mean profile, \(\widehat{\mu}_i=\) 0.1512, with an approximate 95% confidence interval from 0.09097 to 0.2429. For the middle profile, the fitted mean is 1.255, with an interval from 0.8485 to 1.724. For the high profile, the fitted mean is 6.825, and its expected-count interval extends from 5.465 to 8.519.

The corresponding predictive intervals are much wider because they incorporate both coefficient uncertainty and the randomness of a future ZIP count. They extend from 0 to 2 claims for the low profile, from 0 to 6 for the middle profile, and from 0 to 13 for the high profile. Zero therefore remains inside all three 95% predictive intervals, even for the high-mean policyholder. This is consistent with the preceding probability table: a ZIP distribution can retain nonzero probability mass at zero while simultaneously placing substantial mass in a positive-count tail, whose upper extent becomes larger as the fitted mean increases.

For these held-out profiles, the interval describing uncertainty about the expected count is much narrower than the corresponding predictive interval for an observed claim count. This illustrates that uncertainty about the conditional mean is only one part of prediction: even after estimating the mean, a future ZIP response remains discrete and stochastic. After the selected-profile synchronisation described earlier, small remaining differences between Table 12.61 and Table 12.62 can be attributed to model-based covariance and Monte Carlo implementation details rather than to different policyholder profiles.

Heads-up on plug-in and parameter-inclusive prediction

The count probabilities reported in the preceding subsection use the fitted training coefficients as fixed values. They therefore describe the plug-in ZIP predictive distribution

\[ P\left( Y_i=y \mid \mathbf{x}_i, \widehat{\boldsymbol{\theta}}_{\operatorname{train}} \right). \]

The predictive interval constructed here goes one step further by allowing the coefficient vector to vary according to its estimated joint covariance before generating the future response. Thus, it incorporates both the estimated coefficient uncertainty and the inherent randomness of the ZIP count.

This distinction is useful when discussing uncertainty, but it does not replace the held-out scoring metrics reported earlier. The Brier score, log loss, and negative log predictive mass evaluate the plug-in probabilities assigned by the fitted training model to the held-out testing outcomes.

12.13.12 Returning to the predictive inquiry

The predictive conclusion should combine several metrics. A model may improve zero prediction without materially improving RMSE, or improve the complete probability score while producing similar point predictions.

Table 12.63: Guide to held-out ZIP prediction assessment.
Predictive target Primary metric or output Reference baseline Question
Marginal expected claims Mean Error, MAE, RMSE Training mean Does ZIP improve count-point prediction beyond a constant training-set mean?
Probability of zero claims Brier score, zero-event log loss Training zero probability Do covariate-dependent ZIP zero probabilities improve on a constant training zero rate?
Complete count distribution Mean negative log predictive mass Training count probabilities Does ZIP assign more probability to the exact held-out counts than a training-frequency probability baseline?

Because the data are synthetic, the results demonstrate predictive assessment rather than establishing performance for a real insurance portfolio.

The held-out predictive results give a consistent, but target-specific, conclusion. For the marginal expected count, both the training-mean baseline and ZIP have Mean Error close to zero, so the improvement in average signed bias is small; however, ZIP clearly reduces both MAE and RMSE, indicating better policyholder-specific expected-count predictions than the constant training mean. For the probability of an observed zero, ZIP achieves lower Brier score and lower zero-event log loss than the constant training zero probability, showing that the covariates improve the probability forecasts for claims == 0. For the complete count distribution, ZIP also has lower mean negative log predictive mass than the smoothed training count-frequency baseline, meaning that it assigns more probability on average to the exact testing counts that occur. Thus, the predictive evidence does not depend on only one target: ZIP improves the held-out expected-count errors, the observed-zero probability scores, and the complete-distribution score, although the signed Mean Error was already small for the simple baseline.

12.14 How does ZIP compare to Simpler Alternatives?

The earlier comparison in this chapter introduced Binary Logistic Regression (LR) and Classical Poisson Regression (CPR) as simpler ways to represent different parts of the insurance-claims problem. We can now return to those models after fitting, diagnosing, interpreting, and evaluating the Zero-Inflated Poisson (ZIP) model.

The purpose of this section is not to declare one model universally superior. Instead, we ask a narrower set of questions:

  1. What inferential question can each model answer, and how much modelling flexibility does it require?
  2. When the models can be evaluated on the same observed target, which one fits that target more closely?
  3. How do their residual patterns compare on the training data?
  4. Which model produces the strongest held-out predictions for the quantities it is capable of predicting?

These distinctions matter because the three models do not all model the same response distribution. LR replaces claims with the binary response has_claim, whereas CPR and ZIP retain the full count response. As a result, some comparisons are valid across all three models, while others are meaningful only for CPR and ZIP.

AIC and BIC cannot rank all three models together

AIC and BIC compare penalized likelihoods. Their values are directly comparable only when the candidate models are fitted to the same response on the same observations using likelihoods for that same observed outcome.

CPR and ZIP both model the full count response claims, so their AIC and BIC values can be compared directly. LR instead models the derived binary response has_claim. Its likelihood therefore refers to a different observed outcome, so placing its AIC or BIC beside the CPR and ZIP values and choosing the smallest number would not be a fair three-model comparison.

To compare all three models on a common observable target, we instead use each model’s fitted probability that the observed count equals zero:

  • LR: \(P(Y_i=0)=1-P(H_i=1)\);
  • CPR: \(P(Y_i=0)=\exp(-\lambda_i)\);
  • ZIP: \(P(Y_i=0)=\pi_i+(1-\pi_i)\exp(-\lambda_i)\).

The resulting Brier score, log loss, and calibration summaries answer a common question for all three approaches: how well does the model represent the observed zero-versus-positive distinction? They do not, however, measure every aspect of the full count distribution.

12.14.1 Comparing inferential reach and fitted quality

The three models support different inferential statements. The Binary Logistic Regression chapter (Chapter 8) focuses on the odds of an observed event. The Classical Poisson Regression chapter (Chapter 10) focuses on the expected count under a single Poisson process. ZIP separates the zero-heavy count problem into two latent mechanisms.

Table 12.64: Inferential scope of the three regression approaches used in the insurance-claims example.
Model Response modelled Primary coefficient interpretation What the model can distinguish Main inferential limitation in this comparison
Binary Logistic Regression has_claim \(=\mathbb{I}(Y>0)\) Odds ratio for at least one observed claim Zero versus positive claims Discards the distinction among one, two, or more claims
Classical Poisson Regression claims Rate ratio for the expected count Gradients in the complete count response Uses one Poisson mechanism and ties the zero probability to the count mean
Zero-Inflated Poisson Regression claims Structural-zero odds ratio and count-state rate ratio A latent extra-zero mechanism and a separate count-generating mechanism Requires more parameters and therefore more information to estimate both components precisely

This table also explains why the number of statistically significant coefficients should not be used as a model-selection score. A coefficient in LR, a coefficient in CPR, and a coefficient in either ZIP component refer to different parameters. Moreover, formal statistical power is a repeated-sampling property that depends on a specified data-generating process, effect sizes, sample size, and testing procedure. The fitted dataset alone does not provide a direct estimate of which model has greater statistical power in that formal sense.

For the observed training sample, we can instead compare inferential quality through model adequacy, penalized fit where valid, the stability and uncertainty of the fitted coefficients, and whether the model’s assumptions appear compatible with the data. The ZIP-specific coefficient stability results in Section 12.11 should therefore be read alongside the simpler-model comparisons below rather than reduced to a count of rejected null hypotheses.

Count-response likelihood comparison: CPR versus ZIP

Because CPR and ZIP model the same claims observations, AIC and BIC provide a direct penalized-likelihood comparison between these two count models. Both criteria reward stronger likelihood fit but penalize additional parameters; BIC applies the stronger sample-size-dependent penalty.

count_fit_row <- function(model, model_name, n_obs) {
  model_log_likelihood <- logLik(model)
  k <- attr(model_log_likelihood, "df")
  ll <- as.numeric(model_log_likelihood)

  tibble(
    model = model_name,
    log_likelihood = ll,
    number_of_parameters = k,
    AIC = -2 * ll + 2 * k,
    BIC = -2 * ll + log(n_obs) * k
  )
}

zip_alt_count_fit_r <- bind_rows(
  count_fit_row(cpr_model_r, "Classical Poisson Regression", nrow(train_data)),
  count_fit_row(zip_model_r, "Zero-Inflated Poisson Regression", nrow(train_data))
) |>
  mutate(
    delta_AIC = AIC - min(AIC),
    delta_BIC = BIC - min(BIC)
  )
def count_fit_row(result, model_name, n_obs):
    ll = float(result.llf)
    k = len(result.params)
    return {
        "model": model_name,
        "log_likelihood": ll,
        "number_of_parameters": k,
        "AIC": -2 * ll + 2 * k,
        "BIC": -2 * ll + np.log(n_obs) * k,
    }

zip_alt_count_fit_py = pd.DataFrame([
    count_fit_row(
        cpr_model_py,
        "Classical Poisson Regression",
        len(training_data),
    ),
    count_fit_row(
        zip_result_py,
        "Zero-Inflated Poisson Regression",
        len(training_data),
    ),
])

zip_alt_count_fit_py["delta_AIC"] = (
    zip_alt_count_fit_py["AIC"] - zip_alt_count_fit_py["AIC"].min()
)
zip_alt_count_fit_py["delta_BIC"] = (
    zip_alt_count_fit_py["BIC"] - zip_alt_count_fit_py["BIC"].min()
)
Table 12.65: Training-data AIC and BIC comparison of Classical Poisson Regression and Zero-Inflated Poisson Regression using R.
Table 12.66: Training-data AIC and BIC comparison of Classical Poisson Regression and Zero-Inflated Poisson Regression using Python.

The count-response likelihood comparison in Table 12.65 and Table 12.66 strongly favours the ZIP specification over Classical Poisson Regression. ZIP has the smaller AIC, 2300, compared with 2629 for CPR. Equivalently, CPR is 329 AIC points above ZIP. BIC gives the same ordering: ZIP has BIC 2365, compared with 2661 for CPR, a difference of 296.2 points. These gaps remain very large even though ZIP estimates 7 additional parameters. For this training sample, the improvement in the full count-response likelihood therefore more than compensates for ZIP’s added complexity under both penalized-likelihood criteria. Binary Logistic Regression is not part of this ranking because it is fitted to has_claim rather than to the complete claims response.

The interpretation should focus on the trade-off between likelihood fit and complexity. If ZIP has meaningfully smaller AIC and BIC, the added zero-inflation component improves the count-response likelihood enough to offset the larger parameter count. If the criteria are nearly tied, CPR may remain attractive for parsimony. If CPR is favoured, the extra ZIP component is not supported strongly enough by these penalized-likelihood criteria alone.

A common fitted target for all three models: observed zeros

A direct three-model likelihood comparison is unavailable, but all three approaches imply a probability that the observed response is zero. This gives us a common fitted target without changing what each model was originally estimated to do.

For training observation \(i\), let \(Z_i=\mathbb{I}(Y_i=0)\) and let \(\widehat{p}_{0,i}\) be the model-implied probability of zero claims. We summarize the fitted probabilities with the same Brier score and zero-event log loss used later for held-out prediction in Section 12.13. Here, however, the scores are calculated on the training data, so they describe fitted quality rather than out-of-sample predictive performance.

zero_log_loss <- function(observed_zero, predicted_zero) {
  p <- pmin(pmax(predicted_zero, 1e-12), 1 - 1e-12)
  -mean(
    observed_zero * log(p) +
      (1 - observed_zero) * log(1 - p)
  )
}

zip_alt_zero_fit_predictions_r <- bind_rows(
  tibble(
    model = "Binary Logistic Regression",
    observed_zero = as.integer(train_data$claims == 0),
    predicted_p_zero = 1 - predict(lr_model_r, type = "response")
  ),
  tibble(
    model = "Classical Poisson Regression",
    observed_zero = as.integer(train_data$claims == 0),
    predicted_p_zero = exp(-predict(cpr_model_r, type = "response"))
  ),
  tibble(
    model = "Zero-Inflated Poisson Regression",
    observed_zero = as.integer(zip_training_diagnostics_r$claims == 0),
    predicted_p_zero = zip_training_diagnostics_r$fitted_p_zero
  )
)

zip_alt_zero_fit_scores_r <- zip_alt_zero_fit_predictions_r |>
  group_by(model) |>
  summarise(
    zero_brier_score = mean((observed_zero - predicted_p_zero)^2),
    zero_log_loss = zero_log_loss(observed_zero, predicted_p_zero),
    .groups = "drop"
  )
def zero_log_loss(observed_zero, predicted_zero):
    p = np.clip(np.asarray(predicted_zero, dtype=float), 1e-12, 1 - 1e-12)
    y = np.asarray(observed_zero, dtype=float)
    return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))

X_alt_train_py = sm.add_constant(
    training_data[zip_model_covariates_py].astype(float),
    has_constant="add",
)

lr_train_p_zero_py = 1 - np.asarray(lr_model_py.predict(X_alt_train_py))
cpr_train_mu_py = np.asarray(cpr_model_py.predict(X_alt_train_py))
cpr_train_p_zero_py = np.exp(-cpr_train_mu_py)
zip_train_p_zero_py = np.asarray(
    zip_result_py.predict(which="prob-zero")
)

observed_zero_train_py = (
    training_data["claims"].astype(int).to_numpy() == 0
).astype(int)

zip_alt_zero_fit_predictions_py = pd.concat([
    pd.DataFrame({
        "model": "Binary Logistic Regression",
        "observed_zero": observed_zero_train_py,
        "predicted_p_zero": lr_train_p_zero_py,
    }),
    pd.DataFrame({
        "model": "Classical Poisson Regression",
        "observed_zero": observed_zero_train_py,
        "predicted_p_zero": cpr_train_p_zero_py,
    }),
    pd.DataFrame({
        "model": "Zero-Inflated Poisson Regression",
        "observed_zero": observed_zero_train_py,
        "predicted_p_zero": zip_train_p_zero_py,
    }),
], ignore_index=True)

zip_alt_zero_fit_scores_py = (
    zip_alt_zero_fit_predictions_py
    .groupby("model", as_index=False)
    .apply(
        lambda frame: pd.Series({
            "zero_brier_score": np.mean(
                (frame["observed_zero"] - frame["predicted_p_zero"]) ** 2
            ),
            "zero_log_loss": zero_log_loss(
                frame["observed_zero"], frame["predicted_p_zero"]
            ),
        }),
        include_groups=False,
    )
    .reset_index(drop=True)
)
Table 12.67: Training-data Brier score and log loss for the observed zero-claim event across all three regression models using R.
Table 12.68: Training-data Brier score and log loss for the observed zero-claim event across all three regression models using Python.

The Brier score and log loss are both smaller-is-better measures. The Brier score emphasizes squared probability error, while log loss penalizes confident incorrect probability assignments more strongly. Because these are training-data scores, they should be interpreted as summaries of how closely each fitted model represents the observed zero/nonzero pattern, not as evidence of generalization.

On the common training-data zero-versus-positive target, Binary Logistic Regression and ZIP are extremely close, while Classical Poisson Regression is clearly worse. In Table 12.67 and Table 12.68, LR has the smallest fitted Brier score, 0.2004, followed almost immediately by ZIP at 0.2007. The fitted zero-event log losses show the same near-tie: 0.5896 for LR and 0.5903 for ZIP. CPR is noticeably higher on both metrics, with a Brier score of 0.2368 and log loss of 0.6931. Thus, the one-process Poisson model has more difficulty representing the observed zero pattern, whereas LR and ZIP fit that binary feature similarly well. Because these scores use the same training observations used for estimation, they describe fitted quality rather than held-out predictive performance.

A calibration plot adds information that an aggregate score can hide. In a well-calibrated model, groups assigned a similar fitted zero probability should have an observed zero rate close to that probability. Points near the 45-degree line therefore indicate good calibration for the observed event \(Y_i=0\).

ggplot(
  zip_alt_zero_calibration_r,
  aes(
    x = fitted_zero_probability,
    y = observed_zero_rate
  )
) +
  geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
  geom_point(size = 2) +
  geom_line() +
  facet_wrap(~ model, nrow = 1) +
  coord_equal(xlim = c(0, 1), ylim = c(0, 1)) +
  labs(
    x = "Mean fitted probability of zero claims",
    y = "Observed zero-claim rate"
  ) +
  zip_theme
model_order = [
    "Binary Logistic Regression",
    "Classical Poisson Regression",
    "Zero-Inflated Poisson Regression",
]

fig, axes = plt.subplots(1, 3, figsize=(14, 5), sharex=True, sharey=True)

for ax, model_name in zip(axes, model_order):
    frame = zip_alt_zero_calibration_py[
        zip_alt_zero_calibration_py["model"] == model_name
    ].sort_values("fitted_zero_probability")

    ax.plot([0, 1], [0, 1], linestyle="--")
    ax.plot(
        frame["fitted_zero_probability"],
        frame["observed_zero_rate"],
        marker="o",
    )
    ax.set_title(model_name)
    ax.set_xlabel("Mean fitted probability of zero claims")
    ax.set_ylabel("Observed zero-claim rate")
    ax.set_xlim(0, 1)
    ax.set_ylim(0, 1)
    zip_clean_axis(ax)

plt.tight_layout()
plt.show()
Figure 12.20: Training-data calibration of the observed zero-claim probability across Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using R.
Figure 12.21: Training-data calibration of the observed zero-claim probability across Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using Python.

The calibration panels in Figure 12.20 and Figure 12.21 make the difference especially clear. Binary Logistic Regression and ZIP both remain reasonably close to the 45-degree line across most fitted-probability groups, with local deviations on both sides rather than a persistent one-direction error. LR is slightly closer overall on this training zero-event target, which is consistent with its marginally smaller Brier score and log loss above. CPR behaves differently: its observed zero rate lies above its fitted zero probability across the calibration groups, so the one-process Poisson fit systematically assigns too little probability to zero claims. The discrepancy is visually largest through the middle and upper-middle fitted-probability range rather than being confined to one extreme group. Thus, the ZIP zero-inflation component produces a large calibration improvement over CPR by allowing extra zero probability separately from the count mean. It does not, however, create a meaningful calibration advantage over the dedicated binary LR model when the only target being judged is whether the observed count equals zero.

12.14.2 Residual behaviour across the three fitted models

Residuals provide another view of model adequacy. For each model, we use a Pearson-style residual standardized by that model’s fitted variance:

  • LR uses the Bernoulli variance \(\widehat{p}_i(1-\widehat{p}_i)\) for has_claim;
  • CPR uses the Poisson variance \(\widehat{\mu}_i\) for claims;
  • ZIP uses the fitted marginal variance from Equation 12.16.

Because LR is fitted to a binary response while CPR and ZIP are fitted to counts, the residuals are not interchangeable observations from a single common residual distribution. We use them comparatively only to ask whether each model leaves systematic structure, unusually large residuals, or changing residual spread after accounting for its own fitted variance.

lr_fitted_claim_r <- predict(lr_model_r, type = "response")
cpr_fitted_mu_r <- predict(cpr_model_r, type = "response")

zip_alt_residuals_r <- bind_rows(
  tibble(
    model = "Binary Logistic Regression",
    fitted_value = lr_fitted_claim_r,
    pearson_residual =
      (train_data$has_claim - lr_fitted_claim_r) /
      sqrt(lr_fitted_claim_r * (1 - lr_fitted_claim_r))
  ),
  tibble(
    model = "Classical Poisson Regression",
    fitted_value = cpr_fitted_mu_r,
    pearson_residual = residuals(cpr_model_r, type = "pearson")
  ),
  tibble(
    model = "Zero-Inflated Poisson Regression",
    fitted_value = zip_training_diagnostics_r$fitted_mu,
    pearson_residual = zip_training_diagnostics_r$pearson_residual
  )
)
lr_fitted_claim_py = np.asarray(lr_model_py.predict(X_alt_train_py))
cpr_fitted_mu_py = np.asarray(cpr_model_py.predict(X_alt_train_py))
zip_fitted_mu_py = np.asarray(zip_result_py.predict(which="mean"))

has_claim_train_py = (
    training_data["claims"].astype(int).to_numpy() > 0
).astype(int)
claims_train_py = training_data["claims"].astype(float).to_numpy()

lr_residual_py = (
    has_claim_train_py - lr_fitted_claim_py
) / np.sqrt(
    lr_fitted_claim_py * (1 - lr_fitted_claim_py)
)

cpr_residual_py = (
    claims_train_py - cpr_fitted_mu_py
) / np.sqrt(cpr_fitted_mu_py)

zip_variance_py = np.asarray(zip_result_py.predict(which="var"))
zip_residual_py = (
    claims_train_py - zip_fitted_mu_py
) / np.sqrt(zip_variance_py)
Table 12.69: Training-data Pearson residual summaries for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using R.
Table 12.70: Training-data Pearson residual summaries for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using Python.
ggplot(
  zip_alt_residuals_r,
  aes(x = fitted_value, y = pearson_residual)
) +
  geom_hline(yintercept = 0, linetype = "dashed") +
  geom_point(alpha = 0.35) +
  geom_smooth(method = "loess", se = FALSE) +
  facet_wrap(~ model, scales = "free_x", nrow = 1) +
  labs(
    x = "Model-specific fitted value",
    y = "Pearson residual"
  ) +
  zip_theme
model_order = [
    "Binary Logistic Regression",
    "Classical Poisson Regression",
    "Zero-Inflated Poisson Regression",
]

fig, axes = plt.subplots(1, 3, figsize=(14, 5))

for ax, model_name in zip(axes, model_order):
    frame = zip_alt_residuals_py[
        zip_alt_residuals_py["model"] == model_name
    ]
    sns.regplot(
        data=frame,
        x="fitted_value",
        y="pearson_residual",
        lowess=True,
        scatter_kws={"alpha": 0.35},
        line_kws={"linewidth": 1.5},
        ax=ax,
    )
    ax.axhline(0, linestyle="--")
    ax.set_title(model_name)
    ax.set_xlabel("Model-specific fitted value")
    ax.set_ylabel("Pearson residual")
    zip_clean_axis(ax)

plt.tight_layout()
plt.show()
Figure 12.22: Pearson residuals against each model’s fitted value in the training data for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using R.
Figure 12.23: Pearson residuals against each model’s fitted value in the training data for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using Python.

The fitted-value axis should not be compared numerically across all three panels. In the LR panel it is a fitted probability of at least one claim, while in the CPR and ZIP panels it is an expected claim count. The useful comparison is instead whether the residual clouds remain centred near zero, whether a smooth trend remains, whether the spread changes strongly with fitted risk, and how frequently large standardized residuals occur.

The residual summaries and plots in Table 12.69, Figure 12.22, and their Python counterparts point to the clearest remaining lack of fit in Classical Poisson Regression. All three residual means are close to zero, so average centring alone does not distinguish the models. The CPR residuals are much more dispersed, however: their standard deviation is 1.352, compared with 0.9833 for ZIP. About 10.0% of CPR residuals exceed 2 in absolute value, compared with 4.2% under ZIP, and CPR also has the larger maximum absolute residual. Visually, the CPR smooth shows a much stronger systematic drift as fitted counts increase, while the ZIP smooth stays near zero through most of its fitted range and shows only a milder downward movement at the highest fitted means. This indicates that separating the zero mechanism removes much of the count-scale residual structure left by the Classical Poisson model, although the ZIP residuals are not perfectly pattern-free.

The LR residuals are also centred near zero, with 3.6% exceeding 2 in absolute value. Their two-band appearance reflects the binary response and should not be compared directly with the count-model residual magnitudes. The useful conclusion is instead that the LR smooth remains broadly centred for its own zero-versus-positive target, whereas CPR leaves conspicuous structure for the full count response and ZIP substantially reduces that structure.

12.14.3 Comparing held-out predictive quality

The predictive comparison uses only the testing observations and retains the coefficients estimated from the training data, following the predictive workflow in Section 12.13. We use the same aggregated metrics already introduced for ZIP, but only when the model actually defines the required predictive quantity.

This creates three levels of comparison:

  1. Marginal expected-count prediction: CPR and ZIP can be compared with Mean Error, MAE, and RMSE. LR is not included because a Bernoulli probability of has_claim is not an expected claim count when observations can have two or more claims.
  2. Observed-zero probability: all three models can be compared with the zero Brier score and zero-event log loss.
  3. Complete count distribution: CPR and ZIP can be compared by mean negative log predictive mass. LR is not included because it does not assign probabilities separately to \(Y=1,2,3,\ldots\).

This distinction prevents a binary occurrence model from being rewarded or penalized for a count prediction that it was never designed to make.

lr_test_p_claim_r <- predict(
  lr_model_r,
  newdata = test_data,
  type = "response"
)

cpr_test_mu_r <- predict(
  cpr_model_r,
  newdata = test_data,
  type = "response"
)

zip_test_mu_r <- predict(
  zip_model_r,
  newdata = zip_testing_r,
  type = "response"
)
zip_test_lambda_r <- predict(
  zip_model_r,
  newdata = zip_testing_r,
  type = "count"
)
zip_test_pi_r <- predict(
  zip_model_r,
  newdata = zip_testing_r,
  type = "zero"
)
zip_test_p_zero_r <-
  zip_test_pi_r +
  (1 - zip_test_pi_r) * exp(-zip_test_lambda_r)
X_alt_test_py = sm.add_constant(
    testing_data[zip_alt_covariates_py].astype(float),
    has_constant="add",
)

lr_test_p_claim_py = np.asarray(
    lr_model_py.predict(X_alt_test_py),
    dtype=float,
)
cpr_test_mu_py = np.asarray(
    cpr_model_py.predict(X_alt_test_py),
    dtype=float,
)

zip_test_mu_py = np.asarray(
    zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="mean",
    ),
    dtype=float,
)
zip_test_lambda_py = np.asarray(
    zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="mean-main",
    ),
    dtype=float,
)
zip_test_pi_py = 1 - np.asarray(
    zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="prob-main",
    ),
    dtype=float,
)
zip_test_p_zero_py = np.asarray(
    zip_result_py.predict(
        exog=X_count_test_py,
        exog_infl=X_zero_test_py,
        which="prob-zero",
    ),
    dtype=float,
)
Table 12.71: Held-out predictive metrics for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using R. Blank cells indicate that the model does not define that predictive target.
Table 12.72: Held-out predictive metrics for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression using Python. Blank cells indicate that the model does not define that predictive target.

The blank LR cells are intentional. They are not missing results that need to be imputed. LR predicts the probability of crossing the zero-versus-positive boundary, but it does not specify how probability should be divided among one, two, three, or more claims. Consequently, it cannot be assigned a count-scale MAE/RMSE or an exact-count predictive-mass score without adding another model or an additional assumption.

For Mean Error, values closer to zero indicate less average signed bias. For MAE, RMSE, zero Brier score, zero log loss, and mean negative log predictive mass, smaller values indicate better held-out performance.

For held-out expected-count prediction, CPR and ZIP are both almost unbiased on average. CPR’s Mean Error, -0.001166, is slightly closer to zero than ZIP’s -0.006266, but both values are tiny relative to the claim-count scale. ZIP performs better on the unsigned error measures: its MAE is 1.268 claims compared with 1.316 for CPR, and its RMSE is 1.667 compared with 1.697. These are improvements of only about 3.6% in MAE and 1.8% in RMSE, so the policyholder-specific point-prediction advantage is real but modest.

For the shared observed-zero probability target, ZIP is narrowly best on the held-out data, but LR remains essentially tied. The ZIP Brier score is 0.2078, compared with 0.2084 for LR; the corresponding zero-event log losses are 0.6046 and 0.606. Those differences are extremely small. CPR is substantially worse on both zero-event scores. Thus, ZIP preserves the strong occurrence prediction of the dedicated binary model while also modelling the positive-count distribution, but LR remains highly competitive if zero versus positive is the only predictive question.

For the complete held-out count distribution, the separation between the two count models is much larger. ZIP has mean negative log predictive mass 1.409, compared with 1.671 for CPR. This is a reduction of about 15.7%. The ZIP distribution therefore assigns appreciably more probability, on average, to the exact held-out claim counts that are observed. LR has no corresponding complete-count score because it does not specify probabilities for one, two, three, or more claims.

Visual summary of held-out metrics

The next figure displays the same aggregate testing metrics as Table 12.71. Each metric receives its own panel because the numerical scales differ. The figure is therefore intended for within-metric model comparisons only.

ggplot(
  zip_alt_prediction_plot_r,
  aes(x = model, y = value)
) +
  geom_col() +
  facet_wrap(~ metric, scales = "free_y", ncol = 2) +
  labs(x = NULL, y = "Metric value") +
  zip_theme +
  theme(
    axis.text.x = element_text(angle = 30, hjust = 1)
  )
metric_order = [
    "Mean Error",
    "MAE",
    "RMSE",
    "Zero Brier Score",
    "Zero Log Loss",
    "Mean Negative Log Predictive Mass",
]

fig, axes = plt.subplots(3, 2, figsize=(14, 10))
axes = axes.flatten()

for ax, metric_name in zip(axes, metric_order):
    frame = zip_alt_prediction_plot_py[
        zip_alt_prediction_plot_py["metric"] == metric_name
    ]
    sns.barplot(data=frame, x="model", y="value", ax=ax)
    if metric_name == "Mean Error":
        ax.axhline(0, linestyle="--")
    ax.set_title(metric_name)
    ax.set_xlabel("")
    ax.set_ylabel("Metric value")
    ax.tick_params(axis="x", rotation=30)
    zip_clean_axis(ax)

plt.tight_layout()
plt.show()
Figure 12.24: Held-out predictive metrics across the regression alternatives using R. Mean Error is interpreted by distance from zero; smaller values are better for the remaining metrics.
Figure 12.25: Held-out predictive metrics across the regression alternatives using Python. Mean Error is interpreted by distance from zero; smaller values are better for the remaining metrics.

The panel-wise rankings in Figure 12.24 and Figure 12.25 match the numerical conclusions above. CPR’s Mean Error bar lies slightly closer to zero, whereas ZIP has the lower MAE and RMSE. On the two zero-event panels, LR and ZIP are visually almost indistinguishable and both outperform CPR, with ZIP narrowly lower on the held-out scores. The largest visual separation between the two count models appears in mean negative log predictive mass, where ZIP is clearly lower than CPR. The missing LR bars for Mean Error, MAE, RMSE, and mean negative log predictive mass are intentional rather than missing data: Binary Logistic Regression does not define a marginal claim-count prediction or a complete predictive distribution over the count values.

12.14.4 What do the comparisons tell us jointly?

No single statistic answers every question in this section. A model can be attractive inferentially because its parameters answer a useful scientific question, yet still have weak residual behaviour or little held-out predictive advantage. Conversely, a simpler model may predict one observable target well while deliberately ignoring other features of the response.

The final comparison should therefore combine model scope, fitted adequacy, residual diagnostics, predictive performance, and complexity.

Table 12.73: Joint comparison framework for Binary Logistic, Classical Poisson, and Zero-Inflated Poisson Regression.
Comparison dimension Binary Logistic Regression Classical Poisson Regression Zero-Inflated Poisson Regression Joint conclusion
Inferential target Odds of at least one observed claim Expected claim count under one Poisson process Structural-zero odds and count-state expected claims Different estimands; do not rank by number of significant coefficients
Count-response AIC/BIC Not comparable because the response is has_claim See Table 12.65 See Table 12.65 ZIP is strongly favoured over CPR: CPR is 329 AIC points and 296.2 BIC points above ZIP despite ZIP’s additional parameters.
Common zero-event fitted quality See Table 12.67 See Table 12.67 See Table 12.67 LR is marginally best in sample; ZIP is essentially tied with LR, while CPR is clearly worse at representing observed zeros.
Residual adequacy See Figure 12.22 See Figure 12.22 See Figure 12.22 CPR leaves the strongest count-scale residual spread and drift. ZIP substantially reduces that structure; LR is broadly adequate for its separate binary target.
Held-out expected-count accuracy Not defined by LR See Table 12.71 See Table 12.71 CPR has Mean Error slightly closer to zero, but ZIP has modestly lower MAE and RMSE.
Held-out zero-event probability See Table 12.71 See Table 12.71 See Table 12.71 ZIP is narrowly best on Brier score and log loss; LR is effectively tied, while CPR is clearly worse.
Held-out complete count distribution Not defined by LR See Table 12.71 See Table 12.71 ZIP assigns substantially more probability to the exact held-out counts than CPR, as shown by its lower mean negative log predictive mass.
Complexity and interpretability Simplest; one binary mechanism Simple count model; one mean mechanism Most flexible; two linked mechanisms and more parameters ZIP’s extra flexibility is worthwhile for the full count problem in this dataset, but LR remains the more parsimonious choice when the only target is claim occurrence.

Taken together, the comparisons support the added ZIP mechanism when the objective is to model the full claim-count response. Relative to Classical Poisson Regression, ZIP improves the training likelihood enough to remain strongly favoured after both AIC and BIC penalize its seven additional parameters. The calibration and residual diagnostics explain why: CPR systematically assigns too little probability to observed zeros and leaves substantially greater Pearson-residual spread and fitted-value drift, whereas ZIP captures the zero mass separately and produces a more stable count-scale residual pattern. The improvement is therefore not merely an information-criterion artifact; it corresponds to the empirical feature that motivated the model in the first place.

The predictive comparison is more nuanced. For held-out expected counts, ZIP has lower MAE and RMSE than CPR, but the improvement is modest and CPR’s Mean Error is actually slightly closer to zero. The largest count-model predictive gain appears when the complete distribution is evaluated: ZIP has a clearly lower mean negative log predictive mass, so it assigns more probability on average to the exact held-out counts. On the common zero-versus-positive target, the dedicated Binary Logistic Regression model remains highly competitive. LR is marginally better than ZIP on the training zero-event scores, while ZIP is only narrowly better on the held-out Brier score and log loss. Consequently, the extra ZIP structure is not needed simply to obtain a strong binary prediction of whether any claim occurs.

For this synthetic dataset, ZIP is therefore the most informative choice when the analysis requires the complete count distribution and a substantively meaningful separation between structural-zero membership and count-state claim frequency. CPR is more parsimonious but does not represent the zero-heavy count distribution nearly as well. LR remains preferable when the scientific or operational question is genuinely limited to claim versus no claim, because it achieves essentially the same zero-event predictive quality with a simpler estimand and fewer modelling assumptions. The model comparison therefore supports ZIP for the chapter’s full count-data inquiry without implying that greater flexibility should always be preferred regardless of the target.

The comparison should not be read as a rule that ZIP must win because the data contain many zeros. LR may remain the most direct model when the practical question is only whether any claim occurs. CPR may remain preferable when a one-process count model is adequate and interpretability or parsimony is a priority. ZIP becomes most compelling when the data and the substantive problem both support a distinct zero-generating mechanism and the additional flexibility leads to better fitted adequacy, more useful inference, or stronger held-out prediction.

Because this running example uses synthetic insurance data, the final ranking demonstrates how to compare regression approaches rather than establishing a general result about insurance claims. In an applied analysis, model choice should also consider the scientific plausibility of the latent structural-zero state, the stability of the estimated ZIP components, and whether the additional complexity changes decisions that matter to the analysis.

12.15 Storytelling

The last stage of a regression analysis is not another coefficient table or diagnostic plot. It is the task of explaining what the evidence says about the original inquiry, why the chosen model is useful, and which conclusions would go beyond what the data can support. In our synthetic insurance-claims example, we have compared three approaches that answer related but different questions: Binary Logistic Regression (LR) describes whether any claim was observed, Classical Poisson Regression (CPR) describes claim counts through one Poisson process, and Zero-Inflated Poisson Regression (ZIP) allows two latent routes to an observed zero while retaining a complete probability distribution for nonnegative counts.

The study design in Section 12.2.1 established two inquiries. The inferential inquiry concerns how policyholder and vehicle characteristics are associated with the ZIP structural-zero probability, count-state mean, and marginal expected count. The predictive inquiry concerns the accuracy of the training-fitted model when predicting the claims of policyholders held out from estimation. A responsible final story must address both, without treating coefficient significance as predictive success or predictive accuracy as proof of a structural mechanism.

12.15.1 A briefing for an insurance analytics team

Imagine that an insurance analytics team asks: What have we learned about the drivers of claim frequency, and does the additional ZIP structure actually help us describe and predict claims? The evidence can be organised into the short briefing in Table 12.74.

Table 12.74: Stakeholder-facing synthesis of the inferential and predictive ZIP inquiries in the synthetic insurance-claims example.
Stakeholder question Evidence used in this chapter Practical interpretation
Which characteristics show the clearest adjusted associations? The frozen-specification testing-set refit and the component and joint Wald results in Section 12.11. Annual mileage and the prior-claims indicator provide the clearest and comparatively stable model-based associations. In this example, both are associated with lower structural-zero odds and higher expected claims within the count-generating state. Other effects require more caution, especially where intervals are wide or conclusions change near a conventional threshold.
Does ZIP explain why the observed zeros are difficult for CPR? The training zero-probability calibration in Figure 12.20 and the count-model diagnostics in Section 12.10. Across the fitted-probability groups, CPR tends to assign too little probability to no-claim outcomes. ZIP substantially improves the description of this observed feature; the two-component formulation is therefore responding to an actual diagnostic problem rather than merely adding parameters.
Does the more flexible model also improve residual behaviour? The training Pearson-residual comparison in Figure 12.22. CPR leaves more pronounced count-scale residual spread and fitted-value drift. ZIP reduces these patterns, although its residuals are not perfectly pattern-free. LR residuals concern a binary response and cannot be ranked on exactly the same numerical scale as count-model residuals.
Does ZIP improve held-out prediction? The training-fitted models scored on the testing data in Table 12.71. ZIP yields modestly smaller MAE and RMSE for expected counts, markedly better complete-count predictive mass than CPR, and substantially better zero-event probability scores than CPR. LR remains essentially competitive with ZIP when the only question is whether any claim occurs.
Should we treat ZIP’s latent classifications as known insurance facts? The modelling assumptions in Section 12.2.1 and Section 12.10. No. The structural-zero state is latent. An observed zero could also come from the Poisson count state. The synthetic dataset does not establish which state generated any one policyholder’s zero or validate a real-world explanation of structural ineligibility.

The key finding is not simply that the most elaborate model wins. Rather, the model choice depends on the quantity we need to learn or predict. If the team only needs a probability that a policyholder files at least one claim, the simpler LR model already addresses that question directly and performs similarly to ZIP on the zero-versus-positive target. If the team needs the expected number of claims and the probabilities of particular claim counts, LR leaves important aspects of the response undefined. ZIP is more informative for that fuller task because it models both the zero mass and the distribution of positive count outcomes.

12.15.2 Why the graphical comparison matters

The zero-calibration panels in Figure 12.20 make the motivation for ZIP visible to readers without requiring them to interpret its likelihood equations. The fitted CPR model repeatedly assigns less probability to zero claims than the observed group frequencies suggest. By contrast, ZIP and LR are closer to the observed zero frequencies, with no comparable persistent one-direction discrepancy. This is exactly the feature the additional ZIP mechanism was introduced to accommodate. Nevertheless, LR’s success on this graph should not be surprising: it was fitted specifically to a binary claim-versus-no-claim outcome. Good zero calibration is necessary for a zero-heavy count model, but it does not on its own demonstrate that the entire count distribution is adequate.

The residual panels in Figure 12.22 provide a complementary perspective. CPR’s larger standardized residual spread and stronger fitted-value trend suggest that the one-process Poisson formulation is missing structure in the claim counts. ZIP reduces that structure by separating the zero probability from the count-state mean. This does not mean that ZIP solves every lack-of-fit problem, nor that a Pearson-residual plot can identify which individual zeros are structural. Also, the LR panel is calculated for has_claim, while the CPR and ZIP panels are calculated for claims; it is therefore the within-panel patterns, rather than direct comparison of the LR and count residual magnitudes, that are informative.

Finally, the held-out results in Table 12.71 explain why a visually much better model of zero claims does not necessarily produce a dramatically smaller RMSE. RMSE evaluates the differences between observed counts \(Y_i\) and the predicted marginal expected counts \(\widehat{\mu}_i\); it does not evaluate the probability assigned to \(Y_i=0\) or to each exact count. CPR and ZIP can generate fairly similar \(\widehat{\mu}_i\) even while assigning very different probability masses to the possible outcomes. Moreover, occasional larger counts contribute disproportionately to squared error, and no count model can remove the chance variability in realised claims. ZIP’s advantage here is therefore more pronounced in describing and forecasting the count distribution than in reducing the squared error of its point predictions. A similar RMSE is not evidence that the two likelihood models are equivalent.

12.15.3 A concise stakeholder message

In this synthetic insurance-claims example, policyholder mileage and prior-claims history show the most consistent adjusted associations with the fitted claim processes. A standard Poisson model struggles to reproduce the observed frequency of no-claim policyholders and leaves more systematic residual structure. The ZIP model handles those features better and assigns more probability to the observed held-out claim counts, although its improvement in expected-count RMSE is modest. If our only task were predicting claim versus no claim, a simpler Logistic model would remain a strong alternative. The two-state explanation should be treated as a useful modelling assumption—not proof that individual policyholders belong to an identifiable structural-zero group.

This message answers the two inquiries without overstating either. The inferential conclusion concerns adjusted associations in a fitted synthetic-data model, including uncertainty and stability; it is not a causal account of insurance risk. The predictive conclusion concerns held-out performance of the model estimated on the training data, not the refitted testing-set model. The same testing outcomes also appear in the split-sample inferential comparison, so the two assessments should not be advertised as independent external validations. The next section considers when this type of model, and these conclusions, may be unreliable in practice.

12.16 Practical Considerations

ZIP regression is a useful extension of the count-regression toolkit, but it is not a one-size-fits-all response to a high proportion of zeros. A fitted ZIP model can reproduce the observed count distribution while providing weak information about its latent components, or it can fit one dataset well without generalising to another. Practical model choice must therefore account for the substantive meaning of zero, the distribution of positive counts, the available information, the dependence structure, and the eventual use of the predictions (Lambert 1992; Cameron and Trivedi 2013).

12.16.1 Excess observed zeros do not establish a separate zero-generating state

ZIP assumes that an observation may come from a structural-zero state with probability \(\pi_i\), or from a Poisson count state with probability \(1-\pi_i\). The second state can itself produce zero. Consequently, the probability of an observed zero is

\[ \Pr(Y_i=0\mid\mathbf{x}_i) = \pi_i+(1-\pi_i)\exp(-\lambda_i). \]

This expression is useful for prediction, but its two terms are not separately observed labels. In the insurance setting, a policyholder with no recorded claim is not automatically in a group that could not have filed a claim. They may simply have experienced no claim during the observation period. A plausible structural mechanism would require information about the policy, coverage, exposure, and reporting process that is not available in this synthetic example.

An unusually large number of zeros can arise without a distinct zero state: unmeasured differences in exposure, omitted regressors, heterogeneous claim rates, a misspecified relationship with the regressors, or a different count distribution can all change the expected zero frequency. Thus, a favourable ZIP AIC or calibration plot supports the usefulness of a fitted distribution, but does not by itself establish a physical or behavioural zero-generating mechanism. When the existence of two states is the main scientific claim, substantive evidence outside the regression fit is essential.

12.16.2 Overdispersion and choosing another count model

ZIP also changes the variance structure relative to Classical Poisson Regression. Writing the marginal mean as \(\mu_i=(1-\pi_i)\lambda_i\), the ZIP conditional variance is

\[ \operatorname{Var}(Y_i\mid\mathbf{x}_i) = \mu_i+\pi_i(1-\pi_i)\lambda_i^2. \]

The extra nonnegative term shows how the mixture can generate overdispersion even though the count-generating state remains Poisson. However, this does not mean that a ZIP model accommodates every source of excess variance. If the positive counts are more variable than a Poisson distribution permits, even after accounting for zeros and regressors, a different count distribution or model structure may be necessary. Likewise, a Negative Binomial model can sometimes accommodate both the larger variance and many of the zeros without invoking a separate structural-zero group.

Table 12.75 places the main alternatives in the context of the problem they address.

Table 12.75: Choosing among count models according to the substantive mechanism and remaining distributional misfit.
Model Main modelling feature When it deserves consideration
Classical Poisson Regression (Chapter 10) One count-generating process; conditional variance equals conditional mean. The observed counts and fitted zero probabilities are reasonably compatible with the Poisson formulation.
Negative Binomial Regression (Chapter 11) A more flexible count variance than Classical Poisson Regression. Overdispersion persists, potentially explaining numerous zeros without a separate zero-generating state.
Zero-Inflated Poisson Regression A latent zero-only state plus a Poisson count state. A separate zero-producing mechanism is substantively defensible, and the model improves the relevant diagnostics or prediction targets.
Zero-Inflated Negative Binomial Regression A latent zero-only state plus an overdispersed Negative Binomial count state. Both a distinct zero mechanism and additional count-state variation appear relevant; the increased parameter burden is supportable.
Hurdle model A separate process for zero versus positive, followed by a zero-truncated count distribution for positive outcomes. The main distinction is whether any event occurs versus how many occur after the hurdle has been crossed; unlike ZIP, the positive-count component cannot generate zeros.
Generalized Poisson Regression (Chapter 13) An alternative count distribution with a more flexible mean–variance relationship. The principal concern is count dispersion rather than evidence for a latent zero-only state.

A hurdle model is a particularly useful next concept. ZIP combines structural zeros with ordinary Poisson sampling zeros, whereas a hurdle formulation puts all observed zeros on one side of the hurdle and uses a zero-truncated distribution on the positive side. This distinction changes the interpretation of each component: a hurdle model describes the probability of crossing the observed zero-versus-positive boundary; ZIP introduces an unobserved structural-zero state. Neither parameterisation should be chosen simply because its name seems to match a high zero rate (Hu, Pavlicova, and Nunes 2011; Cameron and Trivedi 2013).

12.16.3 Limited data and the cost of modelling two components

Every ZIP fit estimates two linked regression components. When the same six regressors and an intercept are included in each component, the model has fourteen regression coefficients rather than the seven of a comparable Classical Poisson model. This additional flexibility may improve the fit, but it also requires the data to distinguish a change in \(\pi_i\) from a change in \(\lambda_i\). A large overall sample is not enough if most of the observations provide little information about one of those components.

In particular, very few positive counts, sparse binary-regressor categories, near-deterministic zero/nonzero patterns, or limited overlap between regressor groups can make the zero-state coefficients weakly identified. The numerical optimiser may converge despite large estimates, unstable curvature, inflated standard errors, or wide confidence intervals. The inverse-Hessian covariance matrix is only as trustworthy as the local identification and large-sample approximation that justify it. Strong conclusions should not be drawn from a coefficient merely because software prints a finite estimate or a small \(p\)-value.

This matters for the current study design because the testing-set refit contains substantially fewer observations than the training fit. It is intended to illustrate coefficient stability under a frozen specification, not to make uncertainty disappear. With limited data, analysts should consider a more parsimonious zero component, prespecified covariate selection, sensitivity analyses, bootstrap uncertainty where computationally feasible, or scientifically justified regularisation. There is no universal minimum number of observations or zero counts that guarantees reliable ZIP inference.

12.16.4 Multicollinearity and competing explanations

ZIP is especially vulnerable to interpretive overreach when regressors overlap in the information they contain. For example, annual mileage, an urban-driving indicator, and past claims could all be associated with exposure or driving behaviour. When regressors are strongly correlated, the model has less information to separate their adjusted associations. Coefficients may become sensitive to adding or removing other variables, confidence intervals may widen, and it may become difficult to say which characteristic contributes independently.

This is a problem of precision, stability, and attribution, not proof that the coefficients are inherently biased or that all correlated regressors must be removed. Exact linear dependence prevents unique estimation; high but imperfect correlation does not automatically invalidate a fitted model. In ZIP, there are also two sources of potential difficulty: collinearity within each component’s design matrix and competition between the zero and count components for explaining the observed frequency of zeros. They are related modelling concerns but are not the same phenomenon.

Useful checks include examining covariate correlations and category frequencies, inspecting the rank and condition of both component design matrices, considering variance inflation factors where appropriate, examining the stability of the joint covariance matrix, and checking whether substantive conclusions persist under defensible alternative specifications. Any simplification should preserve the study’s inferential question rather than dropping variables solely to obtain smaller \(p\)-values. Fitted marginal quantities and policyholder-profile contrasts can be easier to communicate than a long list of unstable component coefficients.

12.16.5 Exposure, dependence, and specification

The observation window and exposure definition matter for count outcomes. Two policyholders observed for different lengths of time or under different coverage conditions should not automatically be treated as having equal claim opportunities. When it is scientifically appropriate to model rates, a known exposure measure can enter the count-component log link as an offset. Whether exposure also helps describe structural-zero membership is a separate substantive question. A missing or incorrect exposure definition can produce apparent zero inflation and misleading regression coefficients.

The simple ZIP model developed in this chapter also assumes that policyholder responses are conditionally independent and that the logit and log-link systematic components provide adequate descriptions of their respective relationships. Repeated observations for the same policyholder, clustering by location or insurer, unmodelled nonlinearities, interactions, influential counts, or omitted heterogeneity can violate these simplifications. Depending on the data, useful extensions include mixed-effects or hierarchical count models, richer functional forms, and alternative count distributions. In all cases, the more elaborate model should answer a documented deficiency rather than merely provide a lower in-sample information criterion.

12.16.6 Distinguishing different kinds of model evidence

The chapter has used several forms of evidence, each with a different role:

  • Inferential quantities—component coefficients, Wald tests, confidence intervals, joint coefficient tests, and marginal scenario contrasts—describe model-based associations and their uncertainty under the assumed specification.
  • Training-stage diagnostics—observed-versus-fitted zero frequencies, calibration, residual patterns, and comparisons of observed and fitted counts—show whether the fitted model captures important empirical features used during development.
  • Information criteria—AIC and BIC for models fitted to the same count response—balance in-sample likelihood with a penalty for complexity. They are not proofs that a latent mechanism exists.
  • Held-out predictive metrics—RMSE, MAE, zero-event Brier score and log loss, and mean negative log predictive mass—measure different targets and may therefore rank models differently. Model choice should follow the target rather than an arbitrary winning metric.

Heads-up on tests of the zero-inflation mechanism!

A joint test of the zero-inflation slopes within a fitted ZIP model asks whether the observed regressors contribute to its latent zero-state probability beyond a constant zero-state probability. This is distinct from testing whether a zero-inflation component is needed at all. Under the null hypothesis of no zero inflation, \(\pi_i=0\) for every policyholder; with a logit zero component, that null is approached as its intercept tends toward \(-\infty\), and its slopes are not identified in the usual way. Therefore, the familiar interior-parameter Chi-squared reference distribution for an ordinary likelihood-ratio test is generally not justified for the full CPR-versus-ZIP comparison.

Specialised score tests for extra zeros, including the approach of van den Broek (1995) and its covariate-dependent extensions, or a carefully designed parametric-bootstrap likelihood-ratio comparison, are possible approaches. Their assumptions and null distributions must be checked for the actual fitted specification. In particular, an ordinary non-nested Vuong test should not be used uncritically as an omnibus test of zero inflation. For this teaching example, AIC/BIC, calibration, residual evidence, and held-out predictions are the main reported comparisons; we do not claim that these are a formal boundary-corrected hypothesis test of \(\pi_i=0\).

12.16.7 Responsibility when reporting results

Even when ZIP gives a good fitted description of claims, the results remain model-based associations. Observational regressors are not treatments assigned at random; a coefficient does not identify the effect of changing a policyholder’s mileage, moving a driver between urban and rural settings, or altering prior-claims history. In an actual insurance application, questions of measurement quality, differences across portfolios and time, privacy, fairness, and the consequences of deploying model-based decisions would also require attention. The synthetic dataset in this chapter is valuable for demonstrating methodology, but it cannot establish reliable risk estimates or policy recommendations for real customers.

Finally, no diagnostic certifies that a model will remain adequate indefinitely. A model intended for operational use would require data collected under a clearly documented design, external or temporal validation, monitoring of zero frequencies and count distributions, and review when conditions change. The best model is the simplest defensible model that answers the inferential or predictive question adequately, not necessarily the model with the most terms.

12.17 Chapter Summary

This chapter introduced Zero-Inflated Poisson (ZIP) Regression as a model for nonnegative integer counts in which more than one mechanism may produce observed zeros. We began with a synthetic insurance-claims dataset, compared Binary Logistic and Classical Poisson Regression, and developed ZIP as a model combining a latent zero-only state with an ordinary Poisson count state. The central idea was not that every zero is structural; it was that a zero can arise from either part of the mixture.

For policyholder \(i\), the fitted ZIP model distinguishes the structural-zero probability \(\pi_i\), the count-state Poisson mean \(\lambda_i\), and the marginal expected count \(\mu_i\). Their relationship is

\[ \begin{aligned} \Pr(Y_i=0\mid\mathbf{x}_i) &=\pi_i+(1-\pi_i)e^{-\lambda_i},\\[4pt] \mathbb{E}(Y_i\mid\mathbf{x}_i) &=\mu_i=(1-\pi_i)\lambda_i. \end{aligned} \]

Two regression components connect the observed regressors with \(\pi_i\) through a logit link and with \(\lambda_i\) through a log link. Their coefficients consequently have different interpretations: exponentiated zero-component coefficients represent odds ratios for latent structural-zero membership, while exponentiated count-component coefficients represent rate ratios for the Poisson count-state mean. Neither coefficient block alone generally determines the regressor’s association with the marginal expected claim count. Scenario-based quantities and their uncertainty are useful for communicating their combined implications.

We organised the empirical work around the two inquiries in Table 12.76.

Table 12.76: Summary of the inferential and predictive inquiries in the synthetic insurance-claims study.
Inquiry Question answered Main lesson from the synthetic example
Inferential How are policyholder and vehicle regressors associated with structural-zero membership, count-state claim frequency, and marginal expected claims? Annual mileage and prior-claims history show the clearest and most stable adjusted associations across the two components. Other patterns are less precise, and component-specific associations should not be mistaken for marginal or causal effects.
Predictive How well does a training-fitted model predict observed zero probabilities, expected counts, and the full count distribution for held-out policyholders? ZIP improves substantially on CPR for the observed-zero probability and exact-count predictive mass, but produces only a modest improvement in count-scale MAE and RMSE. A simpler LR model is highly competitive for zero-versus-positive prediction alone.

The workflow also illustrated that estimation, inference, model assessment, and prediction are separate activities. We first examined the response and regressors in the training data, fitted ZIP by maximising its joint likelihood, and evaluated numerical completion and model adequacy. The frozen specification was then refitted on the testing observations for a split-sample inferential comparison, while the original training fit was used unchanged to generate held-out predictions. The resulting testing-set coefficient intervals and tests do not have the same purpose as the held-out predictive scores, and the shared testing outcomes do not create two independent external validations.

Most importantly, the comparison with simpler models taught us to match the model to the question. The training zero-calibration and Pearson-residual plots show why Classical Poisson Regression can struggle with a zero-heavy count distribution. ZIP’s additional mechanism reduces this lack of fit and supports a better model of complete claim-count probabilities. Nevertheless, a model can improve distributional fit without greatly improving RMSE, because the fitted mean and the full predictive distribution answer different questions. Similarly, a simple Binary Logistic model can predict the occurrence of any claim well without modelling the number of claims.

ZIP is therefore a valuable model, not a universal prescription. Before using it, analysts should examine whether a separate zero-only mechanism is scientifically credible, whether the count state is still overdispersed, whether the observations and regressors contain enough information to estimate both components reliably, and whether multicollinearity, exposure differences, dependence, or misspecification weaken the conclusions. Negative Binomial, zero-inflated Negative Binomial, hurdle, and generalized count models each address somewhat different shortcomings, and may be more appropriate for a given response (Hu, Pavlicova, and Nunes 2011; Cameron and Trivedi 2013).

The main takeaway of this chapter is methodological: a useful regression analysis is not defined by the number of significant coefficients or by one model-selection statistic. It begins with a clear inferential or predictive inquiry, follows the evidence from the fitted data and diagnostics, makes comparisons on compatible targets, and ends with an explanation of what the model can and cannot establish. The synthetic insurance example provides a complete introduction to that workflow for counts with excess zeros, while leaving more flexible discrete-response and hurdle models as natural extensions.

12.18 Practice exercises

Coming soon…