Skip to main content

25  Multinomial Logistic Regression, Ordinal Regression, and Poisson Regression

“It’s easy to lie with statistics; it is easier to lie without them.” - Frederick Mosteller

The previous two chapters were about a response with two categories. This chapter covers three models for responses that are neither binary nor continuous: multinomial logistic regression for unordered categories, ordinal logistic regression for ordered categories, and Poisson regression for counts.

All three are close relatives of binary logistic regression. Each one has a linear predictor \(\mathbf{x}_i^\prime\boldsymbol{\beta}\), a link function that connects the linear predictor to the mean of the response, and coefficients estimated by maximum likelihood. What changes from model to model is the kind of response and, as a result, what the coefficients mean. Most of the mistakes people make with these models come from reading a coefficient as though it came from one of the other models.

25.1 Nominal Response

Logistic regression is most often used when the response has two categories. Sometimes, however, the response has more than two.

If the categories have no natural order, the response is nominal. A consumer’s choice among product A, product B, and product C is nominal: the categories are names, and there is no sense in which B lies between A and C. Mode of transport to work (car, bus, bicycle, walking), blood type, and political party are other examples.

If the categories do have an order, the response is ordinal. Pain rated as none, mild, moderate, or severe is ordinal, and so is a survey answer on a five-point agree/disagree scale. A count, such as the number of store visits, is ordered too, but it is numeric and has no upper limit, so it gets a model of its own.

NoteNominal, ordinal, and count responses
Response type Example Model in this chapter
Nominal Product A, product B, product C Multinomial logistic regression
Ordinal Mild, moderate, severe Ordinal (proportional odds) logistic regression
Count Number of store visits Poisson regression

A nominal model ignores any ordering, an ordinal model uses it, and a Poisson model is for nonnegative integer counts.

Whether a response is nominal or ordinal is sometimes a judgment call. Pregnancy duration grouped into preterm, intermediate, and full term, which is the first example below, is clearly ordered. Hospital discharge status (home, rehabilitation facility, nursing home, died) has a rough order by severity, but whether “rehabilitation facility” is between “home” and “nursing home” for every patient is debatable. When the order is in doubt, fitting both kinds of model and comparing them is reasonable; this chapter does that for the pregnancy data.

25.2 Multinomial Logistic Regression

For a response with \(J\) categories, multinomial logistic regression picks one category as the baseline and compares each of the other categories with it. If category 1 is the baseline, then for a response with three categories the model is

\[ \log\left(\frac{P(Y=2)}{P(Y=1)}\right) = \beta_{20}+\beta_{21}x_1+\cdots+\beta_{2,p-1}x_{p-1} \]

and

\[ \log\left(\frac{P(Y=3)}{P(Y=1)}\right) = \beta_{30}+\beta_{31}x_1+\cdots+\beta_{3,p-1}x_{p-1}. \]

Each non-baseline category gets its own intercept and its own slope for every predictor. With \(J\) categories and \(p-1\) predictors, the model has \((J-1)p\) coefficients. A binary logistic regression is the special case \(J=2\).

These equations are called baseline-category logits. Solving them for the probabilities gives

\[ P(Y=j)=\frac{\exp(\eta_j)}{\sum_{k=1}^{J}\exp(\eta_k)}, \qquad \eta_j=\beta_{j0}+\beta_{j1}x_1+\cdots+\beta_{j,p-1}x_{p-1}, \]

with \(\eta_1=0\) for the baseline. The denominator makes the \(J\) probabilities add to 1, and every probability is between 0 and 1 no matter what values the predictors take.

The comparison between two non-baseline categories is not fitted separately; it follows from the others. Subtracting the two equations above gives

\[ \log\left(\frac{P(Y=3)}{P(Y=2)}\right) = (\beta_{30}-\beta_{20})+(\beta_{31}-\beta_{21})x_1+\cdots. \]

So the choice of baseline changes which comparisons are printed, but it does not change the model or its fitted probabilities.

Example 25.1  

ExamplePregnancy duration data

A study was undertaken to examine the association between several risk factors and pregnancy duration.

The response variable has three categories:

Code Pregnancy duration category
1 Preterm: less than 36 weeks
2 Intermediate: 36 to 37 weeks
3 Full term: 38 weeks or greater

The predictors are:

Variable Meaning
\(X_1\) Nutritional status; higher scores indicate better nutritional status
\(X_2\) Indicator for age less than or equal to 20
\(X_3\) Indicator for age greater than 30
\(X_4\) Indicator for alcohol history
\(X_5\) Indicator for smoking history

The age categories are represented by two indicator variables:

Age category \(X_2\) \(X_3\)
Less than or equal to 20 1 0
21 to 30 0 0
Greater than 30 0 1

Thus, age 21 to 30 is the reference group.

Example 25.2  

ExampleLoading and preparing the pregnancy data

We read the data, name the variables, and convert the response to a factor. The data file also contains three indicator columns for the response categories, which we drop because the factor Y carries the same information.

library(tidyverse)
library(tidymodels)
library(poissonreg)

tidymodels_prefer()

pregnancy_data <- read.table("CH14TA13.txt")

names(pregnancy_data) <- c(
  "id", "Y", "Y1", "Y2", "Y3",
  "X1", "X2", "X3", "X4", "X5"
)

pregnancy_data <- pregnancy_data |>
  mutate(
    Y = factor(
      Y,
      levels = c(1, 2, 3),
      labels = c("Preterm", "Intermediate", "FullTerm")
    )
  ) |>
  select(-id, -Y1, -Y2, -Y3)

pregnancy_data |>
  count(Y) |>
  mutate(proportion = n / sum(n))
             Y  n proportion
1      Preterm 26  0.2549020
2 Intermediate 35  0.3431373
3     FullTerm 41  0.4019608

There are 102 pregnancies. The smallest category, Preterm, has 26. That number limits how many coefficients the data can support: the multinomial model below has 12 coefficients, and half of them are estimated from the contrast between FullTerm and only 26 preterm cases.

A few targeted plots are easier to read than a large scatterplot matrix. We start with the distribution of the response categories.

duration_colors <- c(
  Preterm = "#D55E00",
  Intermediate = "#E69F00",
  FullTerm = "#0072B2"
)

pregnancy_data |>
  count(Y) |>
  ggplot(aes(x = Y, y = n, fill = Y)) +
  geom_col(show.legend = FALSE) +
  scale_fill_manual(values = duration_colors) +
  labs(
    x = "Pregnancy duration category",
    y = "Number of observations",
    title = "Pregnancy duration category counts"
  ) +
  theme_minimal()

Bar chart showing the number of observations in each pregnancy duration category: 26 preterm, 35 intermediate, and 41 full term.

Next, we look at nutritional status by pregnancy duration category.

pregnancy_data |>
  ggplot(aes(x = Y, y = X1, color = Y)) +
  geom_boxplot(outlier.shape = NA, alpha = 0.15) +
  geom_jitter(width = 0.12, height = 0, alpha = 0.7) +
  scale_color_manual(values = duration_colors) +
  labs(
    x = "Pregnancy duration category",
    y = "Nutritional status",
    color = "Category",
    title = "Nutritional status by pregnancy duration"
  ) +
  theme_minimal()

Boxplots and jittered points showing nutritional status by pregnancy duration category. Median nutritional status is higher in the full-term group than in the other two groups.

The full-term group has higher nutritional scores on the whole, while the preterm and intermediate groups look similar. A plot like this already suggests that the effect of nutrition may not be the same for every comparison between categories, which is something a multinomial model allows and an ordinal model does not.

Finally, we look at the observed category proportions for each indicator predictor.

pregnancy_indicator_proportions <- pregnancy_data |>
  select(Y, X2, X3, X4, X5) |>
  pivot_longer(
    cols = X2:X5,
    names_to = "predictor",
    values_to = "indicator_value"
  ) |>
  mutate(
    predictor = recode(
      predictor,
      X2 = "Age <= 20",
      X3 = "Age > 30",
      X4 = "Alcohol history",
      X5 = "Smoking history"
    ),
    indicator_value = factor(indicator_value, levels = c(0, 1))
  ) |>
  count(predictor, indicator_value, Y) |>
  group_by(predictor, indicator_value) |>
  mutate(proportion = n / sum(n)) |>
  ungroup()

pregnancy_indicator_proportions |>
  ggplot(aes(x = indicator_value, y = proportion, fill = Y)) +
  geom_col() +
  facet_wrap(~ predictor) +
  scale_fill_manual(values = duration_colors) +
  scale_y_continuous(labels = scales::label_percent()) +
  labs(
    x = "Indicator value",
    y = "Observed category proportion",
    fill = "Category",
    title = "Pregnancy duration proportions by indicator value"
  ) +
  theme_minimal()

Faceted stacked bar charts showing observed pregnancy duration proportions for indicator values 0 and 1 of four binary predictors. The full-term share is smaller when the indicator is 1 for every predictor.

For each of the four indicators, the full-term share is smaller in the group coded 1. These are unadjusted comparisons. The age indicators and the behavior indicators may be related to each other and to nutrition, so the model is needed to separate them.

Example 25.3  

ExampleFitting a multinomial logistic regression model

We fit the model with a tidymodels workflow. The nnet engine fits the model by maximum likelihood.

pregnancy_recipe <- recipe(Y ~ X1 + X2 + X3 + X4 + X5, data = pregnancy_data)

pregnancy_model <- multinom_reg() |>
  set_engine("nnet")

pregnancy_workflow <- workflow() |>
  add_recipe(pregnancy_recipe) |>
  add_model(pregnancy_model)

pregnancy_fit <- pregnancy_workflow |>
  fit(data = pregnancy_data)

The first level of the factor, Preterm, is the baseline. The model fits one equation for Intermediate versus Preterm and another for FullTerm versus Preterm. The coefficients are on the log-odds scale, one row per non-baseline category.

pregnancy_fit |>
  extract_fit_engine() |>
  coef()
             (Intercept)         X1          X2         X3         X4
Intermediate   -1.517009 0.01897219 -0.04355881 -0.1721573 -0.9758857
FullTerm       -5.475353 0.06542052 -2.95693397 -2.0596355 -2.0428964
                     X5
Intermediate -0.2218629
FullTerm     -2.4522828

tidy() gives the same coefficients in long form with standard errors, Wald \(z\) statistics, and confidence intervals. With exponentiate = TRUE, the estimates and intervals are odds ratios.

There is a catch. To get standard errors, the tidy() method for multinom fits calls summary(), which refits the model using the data named in the original call. Inside a workflow, that data is not available under its original name, and tidy(pregnancy_fit) stops with the error “‘data’ must be a data.frame, environment, or list”. The fix is to fit the same model with nnet::multinom() directly. We will need this fit for the likelihood ratio tests below as well.

library(nnet)

full_multinom <- multinom(
  Y ~ X1 + X2 + X3 + X4 + X5,
  data = pregnancy_data,
  trace = FALSE
)

all.equal(coef(full_multinom), coef(extract_fit_engine(pregnancy_fit)), tolerance = 1e-4)
[1] TRUE
pregnancy_or <- full_multinom |>
  tidy(exponentiate = TRUE, conf.int = TRUE)

pregnancy_or |>
  select(y.level, term, estimate, conf.low, conf.high, p.value) |>
  print(n = Inf)
# A tibble: 12 × 6
   y.level      term        estimate  conf.low conf.high  p.value
   <chr>        <chr>          <dbl>     <dbl>     <dbl>    <dbl>
 1 Intermediate (Intercept)  0.219   0.00396      12.1   0.459   
 2 Intermediate X1           1.02    0.987         1.05  0.245   
 3 Intermediate X2           0.957   0.226         4.06  0.953   
 4 Intermediate X3           0.842   0.216         3.28  0.804   
 5 Intermediate X4           0.377   0.119         1.19  0.0964  
 6 Intermediate X5           0.801   0.254         2.52  0.705   
 7 FullTerm     (Intercept)  0.00419 0.0000488     0.360 0.0159  
 8 FullTerm     X1           1.07    1.03          1.11  0.000335
 9 FullTerm     X2           0.0520  0.00785       0.344 0.00217 
10 FullTerm     X3           0.128   0.0221        0.736 0.0213  
11 FullTerm     X4           0.130   0.0323        0.521 0.00400 
12 FullTerm     X5           0.0861  0.0205        0.361 0.000801

Here is how to read a few of these, holding the other predictors fixed.

The X1 coefficient in the FullTerm row is about 0.065, so each one-point increase in nutritional status multiplies the odds of a full-term birth rather than a preterm birth by about \(\exp(0.065)=1.07\). Over a 10-point difference, which is less than the spread between the quartiles of \(X_1\) (about 121 to 149), the factor is \(\exp(0.65)\approx 1.9\).

The X5 (smoking) odds ratio in the FullTerm row is about 0.09: smokers have roughly one-twelfth the odds of a full-term birth rather than a preterm birth.

In the Intermediate row, every interval contains 1; the smallest \(p\)-value, about 0.10, is for alcohol history. The data say little about what separates intermediate from preterm pregnancies. Most of the signal is in the comparison of full-term with preterm.

The odds ratios are for pairs of categories. “Smoking multiplies the odds of a full-term birth by 0.09” is not correct as it stands, because the comparison category, preterm, is part of the statement. The odds of full term versus not full term would require a different model.

Example 25.4  

ExampleChanging the baseline category

Comparing FullTerm with Intermediate is not printed above, but it is part of the model. One way to see it is to subtract rows. For smoking, the log odds ratio for full term versus intermediate is \(-2.452-(-0.222)=-2.230\).

The other way is to refit the model with a different baseline. fct_relevel() moves FullTerm to the first level. The recipe records the factor levels of the data it was created with, so reusing pregnancy_workflow on the releveled data stops with an error about mismatched factor levels. We build a new recipe from the releveled data instead.

pregnancy_data_fullterm <- pregnancy_data |>
  mutate(Y = fct_relevel(Y, "FullTerm"))

pregnancy_fit_fullterm <- workflow() |>
  add_recipe(recipe(Y ~ X1 + X2 + X3 + X4 + X5, data = pregnancy_data_fullterm)) |>
  add_model(pregnancy_model) |>
  fit(data = pregnancy_data_fullterm)

pregnancy_fit_fullterm |>
  extract_fit_engine() |>
  coef()
             (Intercept)          X1       X2       X3       X4       X5
Preterm         5.475147 -0.06541919 2.957028 2.059662 2.042900 2.452362
Intermediate    3.958370 -0.04644903 2.913475 1.887550 1.067001 2.230492

The Intermediate row is now intermediate versus full term. Its X5 coefficient, about 2.23, is the negative of the difference we computed, as it should be. The Preterm row is the old FullTerm row with every sign reversed.

The fitted probabilities are the same in both fits, up to the convergence tolerance of the optimizer.

probs_preterm_base <- predict(pregnancy_fit, pregnancy_data, type = "prob")
probs_fullterm_base <- predict(pregnancy_fit_fullterm, pregnancy_data, type = "prob")

max(abs(
  as.matrix(probs_preterm_base) -
    as.matrix(probs_fullterm_base[, names(probs_preterm_base)])
))
[1] 1.777432e-05

The choice of baseline is a choice of which comparisons to report. A good baseline is a category that readers naturally compare against (a control group, the most common outcome, or the “normal” outcome) and one that has a reasonable number of observations. A rare baseline category makes every coefficient’s standard error large, because every comparison involves it.

25.2.1 Testing a Predictor in a Multinomial Model

Each predictor in a multinomial model has \(J-1\) coefficients, one per non-baseline category. The question “does smoking history matter?” is a question about all of them at once, so the test has \(J-1\) degrees of freedom. The likelihood ratio test from the previous chapter works the same way: fit the model with and without the predictor and compare the deviances.

Example 25.5  

ExampleLikelihood ratio tests for the multinomial model

We fit the models with nnet::multinom() directly. As in Example 24.5, anova() should be given ordinary model fits rather than the engine fit extracted from a workflow.

no_smoking_multinom <- multinom(
  Y ~ X1 + X2 + X3 + X4,
  data = pregnancy_data,
  trace = FALSE
)

anova(no_smoking_multinom, full_multinom)
Likelihood ratio tests of Multinomial Models

Response: Y
                   Model Resid. df Resid. Dev   Test    Df LR stat.
1      X1 + X2 + X3 + X4       194   186.1517                      
2 X1 + X2 + X3 + X4 + X5       192   168.6754 1 vs 2     2 17.47627
       Pr(Chi)
1             
2 0.0001603528

The deviance drops by about 17.5 on 2 degrees of freedom when smoking history is added, which is strong evidence that smoking is associated with pregnancy duration.

To test each predictor in turn, we loop over the predictors and drop one at a time.

predictors <- c("X1", "X2", "X3", "X4", "X5")

map(predictors, \(v) {
  reduced <- multinom(
    reformulate(setdiff(predictors, v), response = "Y"),
    data = pregnancy_data,
    trace = FALSE
  )
  tibble(
    dropped = v,
    lr_statistic = deviance(reduced) - deviance(full_multinom),
    df = 2,
    p_value = pchisq(lr_statistic, df = 2, lower.tail = FALSE)
  )
}) |>
  list_rbind()
# A tibble: 5 × 4
  dropped lr_statistic    df   p_value
  <chr>          <dbl> <dbl>     <dbl>
1 X1             21.0      2 0.0000276
2 X2             16.7      2 0.000236 
3 X3              7.61     2 0.0222   
4 X4              9.36     2 0.00926  
5 X5             17.5      2 0.000160 

Every predictor is significant at the 5% level, with age over 30 (\(X_3\)) the weakest. These tests are each conditional on the other four predictors being in the model.

The two age indicators together describe one variable, age group. A test of whether age group matters drops \(X_2\) and \(X_3\) together, for \(2 \times 2 = 4\) degrees of freedom.

no_age_multinom <- multinom(
  Y ~ X1 + X4 + X5,
  data = pregnancy_data,
  trace = FALSE
)

anova(no_age_multinom, full_multinom)
Likelihood ratio tests of Multinomial Models

Response: Y
                   Model Resid. df Resid. Dev   Test    Df LR stat.
1           X1 + X4 + X5       196   187.8249                      
2 X1 + X2 + X3 + X4 + X5       192   168.6754 1 vs 2     4 19.14948
       Pr(Chi)
1             
2 0.0007345354

25.2.2 Seeing the Model on the Probability Scale

A table of 12 odds ratios is hard to take in. Plotting fitted probabilities against a predictor, with the other predictors held at chosen values, usually communicates the model better.

Example 25.6  

ExampleFitted category probabilities against nutritional status

We predict on a grid of nutritional scores for a 21- to 30-year-old with no alcohol history, once for a nonsmoker and once for a smoker.

nutrition_grid <- crossing(
  X1 = seq(95, 195, by = 1),
  X5 = c(0, 1)
) |>
  mutate(X2 = 0, X3 = 0, X4 = 0)

nutrition_probs <- nutrition_grid |>
  bind_cols(predict(pregnancy_fit, new_data = nutrition_grid, type = "prob")) |>
  pivot_longer(
    starts_with(".pred_"),
    names_to = "category",
    names_prefix = ".pred_",
    values_to = "probability"
  ) |>
  mutate(
    category = factor(category, levels = c("Preterm", "Intermediate", "FullTerm")),
    smoking = if_else(X5 == 1, "Smoker", "Nonsmoker")
  )

nutrition_probs |>
  ggplot(aes(x = X1, y = probability, color = category)) +
  geom_line(linewidth = 1) +
  facet_wrap(~ smoking) +
  scale_color_manual(values = duration_colors) +
  labs(
    x = "Nutritional status",
    y = "Fitted probability",
    color = "Category",
    title = "Fitted category probabilities, age 21 to 30, no alcohol history"
  ) +
  theme_minimal()

Two panels of fitted probabilities against nutritional status for a nonsmoker and a smoker. The full-term probability rises with nutritional status in both panels and is lower for the smoker. The intermediate probability falls for the nonsmoker and rises and then falls for the smoker.

For a nonsmoker, the full-term probability rises from about 0.47 at a nutritional score of 95 to 0.99 at 195, and the intermediate probability falls from about 0.30 to almost 0. For a smoker, the intermediate curve is not monotone: it rises to about 0.49 near a score of 107, as preterm births become less likely, and then falls as full-term births take over.

This is a general feature of multinomial models. Every coefficient for Intermediate in Example 25.3 is a comparison with Preterm, and the X1 coefficient for Intermediate is positive, yet the probability of an intermediate birth goes down as \(X_1\) increases (for a nonsmoker, over the whole range plotted). The sign of a baseline-category coefficient tells you the direction of one odds ratio, not the direction in which that category’s probability moves. That direction depends on all of the categories at once.

25.2.3 Predictions and Evaluation

Example 25.7  

ExamplePredicted probabilities and classes from a multinomial model

A multinomial model gives one predicted probability for each response category. A common classification rule is to predict the category with the largest fitted probability.

pregnancy_predictions <- pregnancy_data |>
  select(Y) |>
  bind_cols(
    predict(pregnancy_fit, new_data = pregnancy_data, type = "prob"),
    predict(pregnancy_fit, new_data = pregnancy_data, type = "class")
  )

pregnancy_predictions |>
  slice_head(n = 10)
         Y .pred_Preterm .pred_Intermediate .pred_FullTerm  .pred_class
1  Preterm   0.094211592         0.28500287     0.62078554     FullTerm
2  Preterm   0.254206080         0.56122868     0.18456524 Intermediate
3  Preterm   0.219529135         0.43748955     0.34298132 Intermediate
4  Preterm   0.334546722         0.63828545     0.02716783 Intermediate
5  Preterm   0.474676396         0.39196650     0.13335711      Preterm
6  Preterm   0.497278175         0.38791106     0.11481077      Preterm
7  Preterm   0.009569405         0.03898897     0.95144163     FullTerm
8  Preterm   0.335197462         0.56741578     0.09738676 Intermediate
9  Preterm   0.658559599         0.31368981     0.02775059      Preterm
10 Preterm   0.186635188         0.40894662     0.40441819 Intermediate

Each row’s three probabilities add to 1.

pregnancy_predictions |>
  mutate(total = .pred_Preterm + .pred_Intermediate + .pred_FullTerm) |>
  summarize(min_total = min(total), max_total = max(total))
  min_total max_total
1         1         1

A confusion matrix now has one row and one column per category.

pregnancy_confusion <- conf_mat(
  pregnancy_predictions,
  truth = Y,
  estimate = .pred_class
)

pregnancy_confusion
              Truth
Prediction     Preterm Intermediate FullTerm
  Preterm           12            4        4
  Intermediate      10           23        5
  FullTerm           4            8       32
autoplot(pregnancy_confusion, type = "heatmap") +
  scale_fill_gradient(low = "white", high = "#0072B2") +
  labs(title = "Confusion matrix, multinomial model") +
  theme_minimal()

Heatmap of the multinomial model's confusion matrix with predicted categories in rows and true categories in columns. Most counts are on the diagonal; the largest off-diagonal count is 10 true preterm pregnancies predicted as intermediate.

The model is right for 67 of the 102 pregnancies. Full-term pregnancies are classified best (32 of 41) and preterm pregnancies worst (12 of 26). Ten preterm pregnancies are called intermediate, which matches what the coefficients said: the model has trouble telling these two categories apart.

Accuracy and multinomial log loss summarize the predictions. We add the same metrics for a “model” that ignores the predictors and always predicts the overall category proportions, which is the multinomial version of the no-information rate in Example 24.11.

category_proportions <- pregnancy_data |>
  count(Y) |>
  mutate(p = n / sum(n))

null_predictions <- pregnancy_data |>
  select(Y) |>
  mutate(
    .pred_Preterm = category_proportions$p[1],
    .pred_Intermediate = category_proportions$p[2],
    .pred_FullTerm = category_proportions$p[3],
    .pred_class = factor("FullTerm", levels = levels(Y))
  )

class_metrics <- metric_set(accuracy, mn_log_loss)

bind_rows(
  class_metrics(
    pregnancy_predictions,
    truth = Y,
    .pred_Preterm:.pred_FullTerm,
    estimate = .pred_class
  ) |>
    mutate(model = "Multinomial"),
  class_metrics(
    null_predictions,
    truth = Y,
    .pred_Preterm:.pred_FullTerm,
    estimate = .pred_class
  ) |>
    mutate(model = "No predictors")
) |>
  select(model, .metric, .estimate)
# A tibble: 4 × 3
  model         .metric     .estimate
  <chr>         <chr>           <dbl>
1 Multinomial   accuracy        0.657
2 Multinomial   mn_log_loss     0.827
3 No predictors accuracy        0.402
4 No predictors mn_log_loss     1.08 

Always predicting full term is right about 40% of the time, so the model’s 66% is a real improvement. Log loss falls from about 1.08 to about 0.83.

Accuracy uses only the predicted class. Log loss uses the predicted probability of the category that actually occurred, so it rewards confident correct predictions and penalizes confident wrong ones. Two models can have the same accuracy and very different log loss, as the ordinal model below will show.

These are in-sample numbers. With 12 coefficients and 102 observations, they are optimistic, and the cross-validation methods of the model validation chapter (or the stratified resampling in the previous chapter) would give a fairer estimate.

WarningIndependence of irrelevant alternatives

The multinomial logit model implies that the odds of choosing category \(A\) over category \(B\) do not depend on what other categories are available. This property is called the independence of irrelevant alternatives (IIA).

It is unrealistic when two categories are close substitutes. In the standard example, commuters choose between a car and a red bus with probability 1/2 each. Adding a blue bus that is identical to the red bus should split the bus riders, leaving car 1/2, red bus 1/4, blue bus 1/4. The multinomial logit model instead keeps the car-to-red-bus odds at 1 and gives each option 1/3.

IIA matters most for choice data, such as product or travel-mode choice, and when one wants to predict what happens if an option is added or removed. For outcomes like pregnancy duration, where the categories are fixed intervals of one quantity, it is rarely a concern.

25.3 Ordinal Regression

25.3.1 Ordinal Response

When the response categories have a meaningful order, the response is ordinal. Pregnancy duration can be treated as ordinal because

\[ \text{Preterm} < \text{Intermediate} < \text{FullTerm}. \]

Multinomial logistic regression can still be used, but it ignores the ordering. Ordinal logistic regression uses it. The most common ordinal model is the proportional odds model, which models cumulative probabilities

\[ P(Y_i \le j), \qquad j=1,\ldots,J-1, \]

rather than the probabilities \(P(Y_i=j)\) of single categories. For pregnancy duration, the two cumulative probabilities are \(P(Y_i\le\text{Preterm})\) and \(P(Y_i\le\text{Intermediate})\). The third, \(P(Y_i\le\text{FullTerm})\), is always 1.

The model puts each cumulative probability on the logit scale. In the parameterization used by MASS::polr(),

\[ \log\left(\frac{P(Y_i\le j)}{P(Y_i> j)}\right)=\zeta_j-\eta_i, \qquad \eta_i=\beta_1x_{i1}+\cdots+\beta_{p-1}x_{i,p-1}. \]

The \(\zeta_j\) are cutpoints, one for each of the \(J-1\) boundaries between adjacent categories, with \(\zeta_1<\zeta_2<\cdots<\zeta_{J-1}\). The linear predictor \(\eta_i\) has no intercept, because the cutpoints play that role.

Because \(\eta_i\) is subtracted, a positive \(\beta_k\) makes the cumulative probabilities smaller and so moves probability toward the higher categories. Some software (SAS, and some R packages) writes the model as \(\zeta_j+\eta_i\) instead, which reverses every sign. Before interpreting an ordinal model’s coefficients, check which form the software uses.

The probability of a single category is a difference of cumulative probabilities:

\[ P(Y_i=j)=P(Y_i\le j)-P(Y_i\le j-1). \]

NoteWhy use an ordinal model?

The proportional odds model is more parsimonious. It has one slope per predictor plus \(J-1\) cutpoints, while the multinomial model has \(J-1\) slopes per predictor. For the pregnancy data, that is 7 parameters instead of 12. With more categories the savings grow: a five-category response with five predictors needs 9 parameters in the ordinal model and 24 in the multinomial model.

Fewer parameters mean smaller standard errors when the model is right. The price is a stronger assumption, described next.

25.3.2 A Latent-Variable View

A useful way to think about the proportional odds model is that there is an unobserved continuous variable behind the categories. For pregnancy duration, that variable could be the length of the pregnancy itself, which we observe only after it has been grouped into three bins.

Suppose

\[ Y_i^* = \eta_i + \varepsilon_i, \]

where \(\varepsilon_i\) has a standard logistic distribution, and we observe category \(j\) when \(Y_i^*\) falls between \(\zeta_{j-1}\) and \(\zeta_j\). Then \(P(Y_i\le j)=P(Y_i^*\le\zeta_j)=F(\zeta_j-\eta_i)\), where \(F\) is the logistic CDF. That is exactly the model above.

In this picture, changing the predictors slides the whole distribution of \(Y^*\) left or right, while the cutpoints stay put.

cutpoints <- c(2.93, 5.02)

latent_curves <- crossing(
  y_star = seq(-3, 11, by = 0.02),
  eta = c(3, 5)
) |>
  mutate(
    density = dlogis(y_star, location = eta),
    eta_label = paste("Linear predictor =", eta)
  )

latent_curves |>
  ggplot(aes(x = y_star, y = density, color = eta_label)) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = cutpoints, linetype = "dashed") +
  annotate("text", x = 0.5, y = 0.27, label = "Preterm") +
  annotate("text", x = 3.98, y = 0.27, label = "Intermediate") +
  annotate("text", x = 8, y = 0.27, label = "FullTerm") +
  scale_color_manual(values = c("#D55E00", "#0072B2")) +
  labs(
    x = "Latent variable Y*",
    y = "Density",
    color = NULL,
    title = "Shifting the latent distribution past fixed cutpoints"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Two logistic density curves for a latent variable, centered at linear predictor values 3 and 5, with dashed vertical lines at cutpoints 2.93 and 5.02. The curve centered at 5 puts more of its area to the right of the upper cutpoint.

The cutpoints in the plot are the ones estimated in Example 25.8. When \(\eta\) goes from 3 to 5, more of the distribution lies above the upper cutpoint, so a full-term birth becomes more likely and a preterm birth less likely.

25.3.3 Proportional Odds Assumption

The proportional odds model assumes that each predictor has the same effect at every cumulative split of the ordered response. For the pregnancy duration categories, the splits are:

Split Comparison
1 Preterm versus Intermediate or FullTerm
2 Preterm or Intermediate versus FullTerm

The cutpoints differ from split to split, but the slopes are shared. On the cumulative logit scale, the curves for the two splits are parallel, which is why the assumption is also called the parallel slopes assumption. The name “proportional odds” comes from the fact that, for two people with linear predictors \(\eta_a\) and \(\eta_b\), the ratio of their cumulative odds is \(\exp(\eta_b-\eta_a)\) at every split.

WarningWhen the assumption may be questionable

The proportional odds assumption may fail if a predictor affects one boundary much more than another.

For example, if smoking history strongly separates Preterm from the other categories but has little relationship to whether a pregnancy is FullTerm, then one shared slope is too restrictive. In that case, a multinomial model or a more flexible ordinal model (a partial proportional odds model, which lets some predictors have split-specific slopes) may be more appropriate.

Example 25.8  

ExampleFitting a proportional odds model

We fit the model with MASS::polr(). The response must be an ordered factor, with its levels in the right order.

ordinal_data <- pregnancy_data |>
  mutate(
    Y = ordered(
      Y,
      levels = c("Preterm", "Intermediate", "FullTerm")
    )
  )

ordinal_fit <- MASS::polr(
  Y ~ X1 + X2 + X3 + X4 + X5,
  data = ordinal_data,
  Hess = TRUE
)

broom::tidy(
  ordinal_fit,
  exponentiate = TRUE,
  conf.int = TRUE
) |>
  filter(coef.type == "coefficient") |>
  select(term, estimate, conf.low, conf.high, statistic)
# A tibble: 5 × 5
  term  estimate conf.low conf.high statistic
  <chr>    <dbl>    <dbl>     <dbl>     <dbl>
1 X1       1.05    1.03       1.08       4.13
2 X2       0.139   0.0430     0.416     -3.43
3 X3       0.256   0.0850     0.735     -2.50
4 X4       0.188   0.0718     0.467     -3.51
5 X5       0.204   0.0813     0.481     -3.52

Hess = TRUE keeps the information matrix from the fit, which is needed for standard errors.

The exponentiated coefficients are cumulative odds ratios. Because polr() uses \(\zeta_j-\eta_i\), an odds ratio above 1 means higher values of the predictor go with longer pregnancies. Specifically:

  • A one-point increase in nutritional status multiplies the odds of being in a higher category, at either split, by about 1.05. Over 10 points, the factor is \(\exp(0.489)\approx 1.63\).
  • Smokers have about 0.20 times the odds of nonsmokers of being in a higher category. Equivalently, their odds of being in a lower category are about \(1/0.20=4.9\) times as large.
  • Mothers aged 20 or younger, and those over 30, both have lower odds of a longer pregnancy than mothers aged 21 to 30, with odds ratios of about 0.14 and 0.26.

“A higher category” means Intermediate or FullTerm rather than Preterm at the first split, and FullTerm rather than Preterm or Intermediate at the second. The model says the odds ratio is the same for both.

The cutpoints are reported separately.

broom::tidy(ordinal_fit) |>
  filter(coef.type == "scale")
# A tibble: 2 × 5
  term                  estimate std.error statistic coef.type
  <chr>                    <dbl>     <dbl>     <dbl> <chr>    
1 Preterm|Intermediate      2.93      1.49      1.96 scale    
2 Intermediate|FullTerm     5.02      1.54      3.25 scale    

The cutpoints are rarely of interest by themselves. Their values depend on where the predictors are centered: here \(\eta_i\) is computed with nutritional scores around 135, so the cutpoints are around 3 and 5 rather than near 0.

Example 25.9  

ExampleFitted probabilities from the ordinal model

We plot the ordinal model’s fitted category probabilities on the same grid used in Example 25.6, next to the multinomial model’s.

ordinal_grid_probs <- predict(ordinal_fit, newdata = nutrition_grid, type = "probs") |>
  as_tibble()

ordinal_curve_data <- nutrition_grid |>
  bind_cols(ordinal_grid_probs) |>
  pivot_longer(
    Preterm:FullTerm,
    names_to = "category",
    values_to = "probability"
  ) |>
  mutate(
    category = factor(category, levels = c("Preterm", "Intermediate", "FullTerm")),
    smoking = if_else(X5 == 1, "Smoker", "Nonsmoker"),
    model = "Proportional odds"
  )

bind_rows(
  nutrition_probs |> mutate(model = "Multinomial"),
  ordinal_curve_data
) |>
  ggplot(aes(x = X1, y = probability, color = category)) +
  geom_line(linewidth = 1) +
  facet_grid(model ~ smoking) +
  scale_color_manual(values = duration_colors) +
  labs(
    x = "Nutritional status",
    y = "Fitted probability",
    color = "Category",
    title = "Multinomial and proportional odds fitted probabilities"
  ) +
  theme_minimal()

Four panels of fitted category probabilities against nutritional status, for the multinomial and proportional odds models and for a nonsmoker and a smoker. The two models give similar curves.

The two models tell much the same story, even though the ordinal model has five fewer parameters. In the ordinal model, the probability of the middle category always rises and then falls as \(\eta\) increases, because the latent distribution slides across both cutpoints; within the plotted range, the rise shows up only for the smoker, whose linear predictor starts lower.

Example 25.10  

ExampleChecking the proportional odds assumption

A simple check fits a separate binary logistic regression at each split and compares the slopes. If the proportional odds assumption holds, the slopes should be similar, up to sampling variation. The binary models below use \(P(Y>j)\) as the event, which has the same sign convention as polr().

split_1_fit <- glm(
  I(Y != "Preterm") ~ X1 + X2 + X3 + X4 + X5,
  data = pregnancy_data,
  family = binomial
)

split_2_fit <- glm(
  I(Y == "FullTerm") ~ X1 + X2 + X3 + X4 + X5,
  data = pregnancy_data,
  family = binomial
)

split_slopes <- bind_rows(
  tidy(split_1_fit, conf.int = TRUE) |>
    mutate(fit = "Split 1: above Preterm"),
  tidy(split_2_fit, conf.int = TRUE) |>
    mutate(fit = "Split 2: FullTerm"),
  tidy(ordinal_fit, conf.int = TRUE) |>
    filter(coef.type == "coefficient") |>
    mutate(fit = "Proportional odds")
) |>
  filter(term != "(Intercept)")

split_slopes |>
  select(fit, term, estimate, std.error) |>
  pivot_wider(
    id_cols = term,
    names_from = fit,
    values_from = c(estimate, std.error)
  )
# A tibble: 5 × 7
  term  estimate_Split 1: above …¹ estimate_Split 2: Fu…² estimate_Proportiona…³
  <chr>                      <dbl>                  <dbl>                  <dbl>
1 X1                        0.0373                 0.0531                 0.0489
2 X2                       -1.02                  -2.93                  -1.98  
3 X3                       -0.799                 -1.94                  -1.36  
4 X4                       -1.36                  -1.45                  -1.67  
5 X5                       -0.998                 -2.31                  -1.59  
# ℹ abbreviated names: ¹​`estimate_Split 1: above Preterm`,
#   ²​`estimate_Split 2: FullTerm`, ³​`estimate_Proportional odds`
# ℹ 3 more variables: `std.error_Split 1: above Preterm` <dbl>,
#   `std.error_Split 2: FullTerm` <dbl>, `std.error_Proportional odds` <dbl>
split_slopes |>
  mutate(term = fct_rev(factor(term))) |>
  ggplot(aes(x = estimate, y = term, color = fit)) +
  geom_vline(xintercept = 0, color = "gray60") +
  geom_pointrange(
    aes(xmin = conf.low, xmax = conf.high),
    position = position_dodge(width = 0.6)
  ) +
  scale_color_manual(values = c("#009E73", "#D55E00", "#0072B2")) +
  labs(
    x = "Slope (log cumulative odds ratio)",
    y = NULL,
    color = NULL,
    title = "Slopes at each split compared with the shared slope"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Dot-and-interval plot of slopes for five predictors from two separate binary logistic regressions and the proportional odds model. The split 2 slopes for age 20 or younger and smoking are about twice the split 1 slopes, but the intervals overlap widely.

For age 20 or younger (\(X_2\)) and smoking (\(X_5\)), the slope at the second split is more than twice the slope at the first. For alcohol history the two slopes are close, and for nutrition they differ by less. Except for alcohol history, the proportional odds slope sits between the two split slopes.

Do these differences mean the assumption fails? The intervals overlap a great deal, so the data do not clearly say so. With 102 observations, a check like this has little power: it can flag large departures, but it cannot confirm the assumption. Formal tests, such as the Brant test, have the same limitation and in small samples are often unreliable.

We can also compare the models by AIC. The two models are not nested, so a likelihood ratio test between them is not valid, but AIC applies.

tibble(
  model = c("Multinomial", "Proportional odds"),
  parameters = c(12, 7),
  deviance = c(deviance(full_multinom), deviance(ordinal_fit)),
  AIC = c(AIC(full_multinom), AIC(ordinal_fit))
)
# A tibble: 2 × 4
  model             parameters deviance   AIC
  <chr>                  <dbl>    <dbl> <dbl>
1 Multinomial               12     169.  193.
2 Proportional odds          7     174.  188.

The multinomial model fits better, with a deviance about 4.8 lower, but it uses five more parameters to get there, and its AIC is about 5 higher. The proportional odds model is the better choice by this criterion.

Example 25.11  

ExamplePredictions from an ordinal logistic regression model

Like the multinomial model, the ordinal model returns one predicted probability for each category.

ordinal_probabilities <- predict(
  ordinal_fit,
  newdata = ordinal_data,
  type = "probs"
) |>
  as_tibble() |>
  rename_with(\(x) paste0(".pred_", x))

ordinal_predictions <- ordinal_data |>
  select(Y) |>
  bind_cols(
    ordinal_probabilities,
    tibble(
      .pred_class = predict(
        ordinal_fit,
        newdata = ordinal_data,
        type = "class"
      )
    )
  )

ordinal_predictions |>
  slice_head(n = 10)
         Y .pred_Preterm .pred_Intermediate .pred_FullTerm  .pred_class
1  Preterm   0.056827016         0.27179270     0.67138028     FullTerm
2  Preterm   0.239742367         0.47950086     0.28075677 Intermediate
3  Preterm   0.150070798         0.43915298     0.41077622 Intermediate
4  Preterm   0.560196430         0.35167985     0.08812372      Preterm
5  Preterm   0.423470637         0.43299765     0.14353172 Intermediate
6  Preterm   0.459606967         0.41396070     0.12643233      Preterm
7  Preterm   0.009988634         0.06576689     0.92424447     FullTerm
8  Preterm   0.384644784         0.45082830     0.16452692 Intermediate
9  Preterm   0.751897195         0.20907082     0.03903198      Preterm
10 Preterm   0.121488681         0.40757743     0.47093389     FullTerm
ordinal_confusion <- conf_mat(
  ordinal_predictions,
  truth = Y,
  estimate = .pred_class
)

ordinal_confusion
              Truth
Prediction     Preterm Intermediate FullTerm
  Preterm           13            7        1
  Intermediate       8           21        7
  FullTerm           5            7       33
bind_rows(
  class_metrics(
    pregnancy_predictions,
    truth = Y,
    .pred_Preterm:.pred_FullTerm,
    estimate = .pred_class
  ) |>
    mutate(model = "Multinomial"),
  class_metrics(
    ordinal_predictions,
    truth = Y,
    .pred_Preterm:.pred_FullTerm,
    estimate = .pred_class
  ) |>
    mutate(model = "Proportional odds")
) |>
  select(model, .metric, .estimate)
# A tibble: 4 × 3
  model             .metric     .estimate
  <chr>             <chr>           <dbl>
1 Multinomial       accuracy        0.657
2 Multinomial       mn_log_loss     0.827
3 Proportional odds accuracy        0.657
4 Proportional odds mn_log_loss     0.851

The two models have the same in-sample accuracy, 67 of 102, but the errors are in different places. Of the 35 errors each model makes, 6 of the ordinal model’s skip a category (preterm called full term, or the reverse), compared with 8 of the multinomial model’s.

The multinomial model’s log loss is a little lower, which is expected in-sample because it has more parameters to fit the data with. Plain accuracy treats calling a full-term pregnancy “preterm” as the same mistake as calling it “intermediate”. For an ordered response, the first mistake is worse, and a metric that counts how far off a prediction is, or a weighted kappa, may be more appropriate.

Example 25.12  

ExampleAn ordinal model with the levels in the wrong order

polr() takes the order of the categories from the levels of the factor. If the factor is created with ordered() from character data and no levels argument, R puts the levels in alphabetical order, and the model is fitted to that order without any warning.

alphabetical_data <- pregnancy_data |>
  mutate(Y = ordered(as.character(Y)))

levels(alphabetical_data$Y)
[1] "FullTerm"     "Intermediate" "Preterm"     
MASS::polr(Y ~ X1 + X2 + X3 + X4 + X5, data = alphabetical_data) |>
  coef()
         X1          X2          X3          X4          X5 
-0.04887218  1.97596533  1.36345022  1.66985496  1.59153103 

Alphabetical order happens to be the reverse of the true order here (FullTerm, Intermediate, Preterm), so every sign flips. Read at face value, this output says that better nutrition shortens pregnancy and that smoking lengthens it.

With a different set of labels, alphabetical order could scramble the categories rather than reverse them (for example, “mild”, “moderate”, “severe” sorts correctly, but “low”, “medium”, “high” sorts as “high” < “low” < “medium”). A scrambled order gives a model that has no sensible interpretation at all. Always set the levels explicitly and check them with levels() before fitting.

25.4 Poisson Regression

Poisson regression is used when the response is a count:

\[ Y_i = 0,1,2,\ldots \]

Examples include the number of store visits, hospitalizations, manufacturing defects, insurance claims, or accidents at an intersection, each counted over some fixed period or area.

25.4.1 The Poisson Distribution

The Poisson probability distribution is

\[ f(Y) = \frac{\mu^Y \exp(-\mu)}{Y!}, \qquad Y=0,1,2,\ldots \]

For a Poisson random variable,

\[ \begin{align*} E(Y) &= \mu,\\ Var(Y) &= \mu. \end{align*} \]

The mean and the variance are the same. A Poisson model has no separate variance parameter like \(\sigma^2\) in linear regression: once the mean is known, so is the variance. This is the assumption that most often fails in practice, and we return to it below.

crossing(mu = c(1, 4, 10), y = 0:22) |>
  mutate(
    probability = dpois(y, mu),
    mu_label = factor(paste("Mean =", mu), levels = paste("Mean =", c(1, 4, 10)))
  ) |>
  ggplot(aes(x = y, y = probability)) +
  geom_col(fill = "#0072B2") +
  facet_wrap(~ mu_label) +
  labs(
    x = "Count",
    y = "Probability",
    title = "Poisson distributions with different means"
  ) +
  theme_minimal()

Three bar charts of Poisson probability distributions with means 1, 4, and 10. The mean 1 distribution is concentrated at 0 and 1 and skewed right; the mean 10 distribution is wider and nearly symmetric.

When the mean is small, the distribution is piled up near zero and skewed to the right. As the mean grows, it spreads out (its standard deviation is \(\sqrt{\mu}\)) and becomes more symmetric. A linear model with constant variance cannot describe both shapes.

NoteCounts are not just another continuous response

A count is nonnegative and discrete, and its variance tends to grow with its mean. A linear model can predict negative counts, and it assumes the same variance everywhere. A Poisson model with a log link keeps the fitted mean positive and lets the variance grow with the mean.

Transforming the response, for example fitting a linear model to \(\log(Y+1)\), is a common workaround. It handles skewness somewhat, but the constant added before taking logs is arbitrary, the coefficients describe the mean of \(\log(Y+1)\) rather than the mean count, and it behaves poorly when many counts are 0 or 1.

25.4.2 Poisson Regression Model

In Poisson regression, we assume

\[ Y_i \sim \text{Poisson}(\mu_i) \]

and use the log link

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

Equivalently,

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

This guarantees that the fitted mean count is positive. It also makes the predictors act multiplicatively. A one-unit increase in \(x_k\) adds \(\beta_k\) to \(\log(\mu_i)\), which multiplies \(\mu_i\) by \(\exp(\beta_k)\). So \(\exp(\beta_k)\) is a rate ratio: the factor by which the expected count changes per unit of \(x_k\), holding the other predictors fixed. A rate ratio of 1.18 means an 18% increase in the expected count, and 0.88 means a 12% decrease.

As with logistic regression, the coefficients are estimated by maximum likelihood, the fit is summarized by the deviance, and nested models are compared with likelihood ratio tests.

Example 25.13  

ExamplePoisson regression for store customer counts

The Miller Lumber Company is a large retailer of lumber, paint, plumbing, electrical supplies, and other household supplies.

During a representative two-week period, in-store surveys were conducted and addresses of customers were obtained. The addresses were used to identify the metropolitan-area census tracts in which the customers lived. At the end of the survey period, the total number of customers who visited the store from each census tract was recorded.

The response is \(Y\), the number of customers who visited the store from the census tract. The predictors are:

Variable Meaning
\(X_1\) Number of housing units
\(X_2\) Average income, in dollars
\(X_3\) Average housing-unit age, in years
\(X_4\) Distance to nearest competitor, in miles
\(X_5\) Distance to store, in miles
lumber_data <- read.table("CH14TA14.txt")

names(lumber_data) <- c("Y", "X1", "X2", "X3", "X4", "X5")

lumber_data |>
  slice_head(n = 10)
    Y   X1    X2 X3   X4   X5
1   9  606 41393  3 3.04 6.32
2   6  641 23635 18 1.95 8.89
3  28  505 55475 27 6.54 2.05
4  11  866 64646 31 1.67 5.81
5   4  599 31972  7 0.72 8.11
6   4  520 41755 23 2.24 6.81
7   0  354 46014 26 0.77 9.27
8  14  483 34626  1 3.51 7.92
9  16 1034 85207 13 4.23 4.40
10 13  456 33021 32 3.07 6.03
lumber_data |>
  summarize(
    tracts = n(),
    mean_count = mean(Y),
    variance_count = var(Y),
    zero_counts = sum(Y == 0)
  )
  tracts mean_count variance_count zero_counts
1    110       11.2       44.08807           3

There are 110 tracts with between 0 and 32 customers each. Three tracts sent no customers at all.

The variance of the counts, about 44, is four times their mean, about 11. That looks like a violation of the Poisson assumption, but it is not evidence of one. The Poisson assumption is about the variance of \(Y\) given the predictors. Tracts differ in size and distance from the store, so their means differ, and that alone makes the overall variance larger than the overall mean. We check the conditional variance after fitting the model.

To see how the counts relate to each predictor, we plot them with a one-predictor Poisson fit for each.

lumber_data |>
  pivot_longer(X1:X5, names_to = "predictor", values_to = "value") |>
  mutate(
    predictor = recode(
      predictor,
      X1 = "Housing units",
      X2 = "Average income",
      X3 = "Average housing age",
      X4 = "Miles to competitor",
      X5 = "Miles to store"
    )
  ) |>
  ggplot(aes(x = value, y = Y)) +
  geom_point(alpha = 0.6) +
  geom_smooth(
    method = "glm",
    method.args = list(family = poisson),
    se = FALSE,
    color = "#0072B2"
  ) +
  facet_wrap(~ predictor, scales = "free_x") +
  labs(
    x = NULL,
    y = "Customers from tract",
    title = "Customer counts against each predictor"
  ) +
  theme_minimal()

Five scatterplots of customer counts against each predictor with a fitted Poisson regression curve. Counts fall clearly with distance to the store and rise with distance to the nearest competitor; the relationships with the other predictors are weaker.

Distance to the store has the clearest relationship: tracts that are farther away send fewer customers. Tracts that are farther from a competitor send more.

Example 25.14  

ExampleFitting and interpreting a Poisson regression model
lumber_recipe <- recipe(Y ~ ., data = lumber_data)

lumber_model <- poisson_reg() |>
  set_engine("glm")

lumber_workflow <- workflow() |>
  add_recipe(lumber_recipe) |>
  add_model(lumber_model)

lumber_fit <- lumber_workflow |>
  fit(data = lumber_data)

lumber_fit |>
  tidy()
# A tibble: 6 × 5
  term          estimate  std.error statistic  p.value
  <chr>            <dbl>      <dbl>     <dbl>    <dbl>
1 (Intercept)  2.94      0.207          14.2  9.47e-46
2 X1           0.000606  0.000142        4.26 2.02e- 5
3 X2          -0.0000117 0.00000211     -5.53 3.13e- 8
4 X3          -0.00373   0.00178        -2.09 3.65e- 2
5 X4           0.168     0.0258          6.53 6.39e-11
6 X5          -0.129     0.0162         -7.95 1.89e-15

The coefficients are on the log-mean scale. Exponentiating them gives rate ratios.

lumber_fit |>
  tidy(exponentiate = TRUE, conf.int = TRUE) |>
  select(term, estimate, conf.low, conf.high)
# A tibble: 6 × 4
  term        estimate conf.low conf.high
  <chr>          <dbl>    <dbl>     <dbl>
1 (Intercept)   19.0     12.6      28.5  
2 X1             1.00     1.00      1.00 
3 X2             1.000    1.000     1.000
4 X3             0.996    0.993     1.000
5 X4             1.18     1.12      1.24 
6 X5             0.879    0.851     0.907

Several of these rate ratios are close to 1 because the predictors are measured in small units. A rate ratio per dollar of income is not a useful number. The rate ratio for \(c\) units is \(\exp(c\beta_k)\), so we rescale to units that make sense for each predictor.

lumber_fit |>
  tidy() |>
  filter(term != "(Intercept)") |>
  mutate(
    unit = c(100, 10000, 10, 1, 1),
    unit_label = c(
      "100 housing units", "$10,000 income", "10 years of housing age",
      "1 mile to competitor", "1 mile to store"
    ),
    rate_ratio = exp(unit * estimate),
    percent_change = 100 * (rate_ratio - 1)
  ) |>
  select(term, unit_label, rate_ratio, percent_change)
# A tibble: 5 × 4
  term  unit_label              rate_ratio percent_change
  <chr> <chr>                        <dbl>          <dbl>
1 X1    100 housing units            1.06            6.24
2 X2    $10,000 income               0.890         -11.0 
3 X3    10 years of housing age      0.963          -3.66
4 X4    1 mile to competitor         1.18           18.3 
5 X5    1 mile to store              0.879         -12.1 

Holding the other predictors fixed:

  • Each additional mile from the store goes with about 12% fewer expected customers.
  • Each additional mile from the nearest competitor goes with about 18% more.
  • An extra 100 housing units goes with about 6% more.
  • A $10,000 higher average income goes with about 11% fewer.

The effects compound multiplicatively. Five more miles from the store multiplies the expected count by \(0.879^5\approx 0.53\), not by \(1-5(0.12)=0.40\).

Likelihood ratio tests for each predictor come from drop1() on the glm fit. As in the previous chapter, we refit with glm() so that the model has an ordinary response name.

lumber_glm <- glm(Y ~ X1 + X2 + X3 + X4 + X5, data = lumber_data, family = poisson)

drop1(lumber_glm, test = "LRT")
Single term deletions

Model:
Y ~ X1 + X2 + X3 + X4 + X5
       Df Deviance    AIC    LRT  Pr(>Chi)    
<none>      114.98 571.02                     
X1      1   133.19 587.23 18.203 1.986e-05 ***
X2      1   146.78 600.82 31.794 1.714e-08 ***
X3      1   119.36 573.40  4.379   0.03638 *  
X4      1   156.65 610.68 41.660 1.086e-10 ***
X5      1   182.49 636.52 67.500 < 2.2e-16 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

All five predictors are significant at the 5% level. Housing age is the weakest, with a deviance change of about 4.4.

25.4.3 Checking the Fit

A Poisson model can go wrong in a few specific ways: the variance can be larger than the mean (overdispersion), there can be more zeros than the model expects, or the log of the mean can depend on a predictor in a way that is not linear. Each one has a direct check.

Example 25.15  

ExampleChecking for overdispersion

If the Poisson model is right, the Pearson residuals

\[ r_i=\frac{Y_i-\hat{\mu}_i}{\sqrt{\hat{\mu}_i}} \]

have variance about 1. The sum of their squares divided by the residual degrees of freedom estimates the dispersion, which should be close to 1. A value well above 1 is overdispersion.

tibble(
  pearson_dispersion = sum(residuals(lumber_glm, type = "pearson")^2) /
    df.residual(lumber_glm),
  residual_deviance = deviance(lumber_glm),
  df = df.residual(lumber_glm),
  goodness_of_fit_p = pchisq(residual_deviance, df, lower.tail = FALSE)
)
# A tibble: 1 × 4
  pearson_dispersion residual_deviance    df goodness_of_fit_p
               <dbl>             <dbl> <int>             <dbl>
1              0.980              115.   104             0.217

The dispersion estimate is about 0.98, and the residual deviance, about 115 on 104 degrees of freedom, is consistent with the Poisson model (the goodness-of-fit \(p\)-value is about 0.22). Once the predictors are taken into account, the counts vary about as much as a Poisson model says they should. The marginal variance of 44 in Example 25.13 came from differences between the tracts’ means.

The deviance goodness-of-fit test needs fairly large fitted counts to be trustworthy. The smallest fitted mean here is about 4, which is adequate. When many fitted means are below 1 or 2, the deviance does not follow a \(\chi^2\) distribution well and the test should not be relied on.

A plot of Pearson residuals against fitted values shows the same thing graphically: no funnel shape, and all but 8 of the 110 residuals between \(-2\) and 2, close to the 5% one would expect by chance. The largest is about 2.5.

lumber_diagnostics <- lumber_data |>
  mutate(
    fitted = fitted(lumber_glm),
    pearson = residuals(lumber_glm, type = "pearson"),
    zero = if_else(Y == 0, "Zero customers", "One or more")
  )

lumber_diagnostics |>
  ggplot(aes(x = fitted, y = pearson, color = zero)) +
  geom_hline(yintercept = c(-2, 0, 2), linetype = c("dashed", "solid", "dashed"), color = "gray50") +
  geom_point(alpha = 0.8) +
  scale_color_manual(values = c("Zero customers" = "#D55E00", "One or more" = "#0072B2")) +
  labs(
    x = "Fitted count",
    y = "Pearson residual",
    color = NULL,
    title = "Pearson residuals for the Poisson model"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Scatterplot of Pearson residuals against fitted counts for the Poisson model, with horizontal reference lines at -2, 0, and 2. The spread is roughly constant; three points near the bottom are tracts with zero customers.

Example 25.16  

ExampleObserved and expected count frequencies

Another check compares how often each count occurs with how often the fitted model says it should. For each count \(k\), the expected number of tracts with \(Y=k\) is \(\sum_i P(Y_i=k)=\sum_i f(k;\hat{\mu}_i)\).

lumber_mu <- fitted(lumber_glm)

count_frequencies <- tibble(k = 0:32) |>
  mutate(
    observed = map_int(k, \(x) sum(lumber_data$Y == x)),
    expected = map_dbl(k, \(x) sum(dpois(x, lumber_mu)))
  )

count_frequencies |>
  ggplot(aes(x = k)) +
  geom_col(aes(y = observed), fill = "gray75") +
  geom_line(aes(y = expected), color = "#0072B2", linewidth = 1) +
  geom_point(aes(y = expected), color = "#0072B2") +
  labs(
    x = "Customers from tract",
    y = "Number of tracts",
    title = "Observed (bars) and expected (line) count frequencies"
  ) +
  theme_minimal()

Bar chart of the observed number of tracts with each customer count from 0 to 32, with a line and points showing the expected number under the Poisson model. The observed count of 3 tracts at zero is far above the expected value near 0.1.

count_frequencies |>
  filter(k <= 3)
# A tibble: 4 × 3
      k observed expected
  <int>    <int>    <dbl>
1     0        3    0.146
2     1        0    0.720
3     2        1    1.89 
4     3        5    3.55 

The fit is reasonable over most of the range, but there are three tracts with zero customers where the model expects about 0.15. A single excess zero can happen by chance; three, when the expected number is that small, suggests something the model does not describe.

lumber_diagnostics |>
  filter(Y == 0) |>
  select(Y, X1:X5, fitted)
  Y  X1    X2 X3   X4   X5   fitted
1 0 354 46014 26 0.77 9.27 4.298174
2 0 828 85664  4 1.30 9.66 4.067281
3 0 180 44588 14 0.88 9.38 4.131026

All three tracts are more than 9 miles from the store and within about 1.3 miles of a competitor. Perhaps customers beyond some distance stop coming altogether, which a smooth exponential decline in distance cannot capture. Possible remedies include a more flexible term for distance or a zero-inflated model, which mixes a Poisson distribution with a separate process that produces extra zeros. With only three zeros, the data cannot tell these explanations apart.

Example 25.17  

ExampleWhat overdispersion does to inference

The lumber data are not overdispersed, so we simulate data that are. We generate counts from a negative binomial distribution, whose variance is \(\mu+\mu^2/\theta\), larger than its mean. With \(\theta=2\) and means around 3 to 4, the variance is roughly three times the mean. We fit an ordinary Poisson model and a quasi-Poisson model to each of 1,000 simulated datasets and record whether the 95% confidence interval for the slope contains the true value, 0.5.

The quasi-Poisson model has the same coefficient estimates as the Poisson model but multiplies the standard errors by the square root of the estimated dispersion.

set.seed(3386)

n_obs <- 100
x_sim <- runif(n_obs)
true_slope <- 0.5

overdispersion_sim <- map(1:1000, \(rep) {
  y_sim <- rnbinom(n_obs, mu = exp(1 + true_slope * x_sim), size = 2)

  poisson_fit <- glm(y_sim ~ x_sim, family = poisson)
  quasi_fit <- glm(y_sim ~ x_sim, family = quasipoisson)

  bind_rows(
    tidy(poisson_fit, conf.int = TRUE, conf.method = "Wald") |>
      mutate(model = "Poisson"),
    tidy(quasi_fit) |>
      mutate(
        conf.low = estimate - qt(0.975, n_obs - 2) * std.error,
        conf.high = estimate + qt(0.975, n_obs - 2) * std.error,
        model = "Quasi-Poisson"
      )
  ) |>
    filter(term == "x_sim") |>
    mutate(
      rep = rep,
      dispersion = sum(residuals(poisson_fit, type = "pearson")^2) / (n_obs - 2)
    )
}) |>
  list_rbind()

overdispersion_sim |>
  group_by(model) |>
  summarize(
    mean_std_error = mean(std.error),
    coverage = mean(conf.low <= true_slope & true_slope <= conf.high),
    mean_dispersion = mean(dispersion)
  )
# A tibble: 2 × 4
  model         mean_std_error coverage mean_dispersion
  <chr>                  <dbl>    <dbl>           <dbl>
1 Poisson                0.180    0.767            2.72
2 Quasi-Poisson          0.295    0.944            2.72

The average estimated dispersion is about 2.7. The Poisson model’s intervals are too narrow and contain the true slope only about 77% of the time, far short of the nominal 95%. The quasi-Poisson intervals are wider and have close to the right coverage. The coefficient estimates themselves are the same in both models and are unbiased; the problem is entirely in the standard errors, and so in every test and interval.

overdispersion_sim |>
  filter(rep <= 40) |>
  mutate(covers = if_else(conf.low <= true_slope & true_slope <= conf.high, "Covers", "Misses")) |>
  ggplot(aes(y = rep, x = estimate, xmin = conf.low, xmax = conf.high, color = covers)) +
  geom_vline(xintercept = true_slope) +
  geom_pointrange(size = 0.2) +
  facet_wrap(~ model) +
  scale_color_manual(values = c(Covers = "#0072B2", Misses = "#D55E00")) +
  labs(
    x = "Slope estimate and 95% interval",
    y = "Simulated dataset",
    color = NULL,
    title = "Confidence intervals under overdispersion"
  ) +
  theme_minimal() +
  theme(legend.position = "bottom")

Interval plot of the first 40 simulated 95 percent confidence intervals for the slope, Poisson on the left and quasi-Poisson on the right, with a vertical line at the true slope of 0.5. Many Poisson intervals miss the true value; the quasi-Poisson intervals are wider and miss less often.

When the dispersion is clearly above 1, use quasi-Poisson standard errors or a negative binomial model (MASS::glm.nb()), which estimates \(\theta\) along with the coefficients. Overdispersion is common in real count data, because there is almost always variation between units that the predictors do not capture.

A negative binomial fit to data that are not overdispersed is a fringe case of its own. For the lumber data, glm.nb() cannot find a finite \(\theta\) and gives a warning:

lumber_nb <- MASS::glm.nb(Y ~ X1 + X2 + X3 + X4 + X5, data = lumber_data)
Warning in theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace =
control$trace > : iteration limit reached
Warning in theta.ml(Y, mu, sum(w), w, limit = control$maxit, trace =
control$trace > : iteration limit reached
lumber_nb$theta
[1] 92024.56

The estimate of \(\theta\) heads toward infinity, which is the Poisson limit of the negative binomial. The warning here does not mean the analysis has failed; it means the data have no extra variation for the model to estimate, and the coefficients are essentially the Poisson coefficients.

25.4.4 Exposure and Offsets

Counts often come from units of different sizes or observed for different lengths of time: accidents at intersections with different traffic volumes, infections among hospitals with different numbers of patient-days, customers from census tracts with different numbers of households. Then the natural quantity to model is a rate, the count per unit of exposure \(t_i\):

\[ \log\left(\frac{\mu_i}{t_i}\right)=\mathbf{x}_i^\prime\boldsymbol{\beta} \quad\Longleftrightarrow\quad \log(\mu_i)=\log(t_i)+\mathbf{x}_i^\prime\boldsymbol{\beta}. \]

The term \(\log(t_i)\) is an offset: a predictor whose coefficient is fixed at 1 rather than estimated. It says that doubling the exposure doubles the expected count, all else equal. In R, it goes in the formula as offset(log(t)).

An offset is an assumption, and it can be checked by putting \(\log(t_i)\) in the model as an ordinary predictor and seeing whether its coefficient is near 1.

Example 25.18  

ExampleShould housing units be an offset?

It seems natural to treat the number of housing units in a tract, \(X_1\), as exposure: a tract with twice as many households might be expected to send twice as many customers. We fit the model with \(\log(X_1)\) as an offset and with \(\log(X_1)\) as an estimated predictor.

lumber_offset <- glm(
  Y ~ offset(log(X1)) + X2 + X3 + X4 + X5,
  data = lumber_data,
  family = poisson
)

lumber_log_units <- glm(
  Y ~ log(X1) + X2 + X3 + X4 + X5,
  data = lumber_data,
  family = poisson
)

tidy(lumber_log_units, conf.int = TRUE) |>
  filter(term == "log(X1)") |>
  select(term, estimate, conf.low, conf.high)
# A tibble: 1 × 4
  term    estimate conf.low conf.high
  <chr>      <dbl>    <dbl>     <dbl>
1 log(X1)    0.202   0.0769     0.334
tibble(
  model = c("Offset log(X1)", "Estimated log(X1)", "Linear X1 (original)"),
  AIC = c(AIC(lumber_offset), AIC(lumber_log_units), AIC(lumber_glm))
)
# A tibble: 3 × 2
  model                  AIC
  <chr>                <dbl>
1 Offset log(X1)        693.
2 Estimated log(X1)     579.
3 Linear X1 (original)  571.

The estimated coefficient on \(\log(X_1)\) is about 0.20, with an interval of roughly 0.08 to 0.33. A coefficient of 0.2 means doubling the number of housing units multiplies the expected count by only \(2^{0.2}\approx 1.15\). The offset forces that factor to be 2, and its AIC is more than 100 higher than the others. Customer counts here are not proportional to tract size, perhaps because larger tracts cover more area and so contain households farther from the store.

The lesson is general: use an offset when the count is proportional to exposure by the way the data were collected (a count over twice the time period, for instance), and check the assumption when proportionality is only plausible.

Example 25.19  

ExamplePredicted counts from a Poisson regression model
lumber_predictions <- lumber_data |>
  select(Y) |>
  bind_cols(
    predict(lumber_fit, new_data = lumber_data, type = "numeric")
  )

lumber_predictions |>
  slice_head(n = 10)
    Y     .pred
1   9 12.337775
2   6  8.767095
3  28 28.125856
4  11  8.407109
5   4  7.260584
6   4  8.881802
7   0  4.298174
8  14 10.998852
9  16 14.443973
10 13 11.634382

The predictions are expected counts. They are not whole numbers, and they should not be rounded: the first tract’s prediction of 12.3 says the model expects about 12.3 customers on average from tracts like this one, and any particular tract will send a whole number near it, with a Poisson standard deviation of about \(\sqrt{12.3}\approx 3.5\). (This one sent 9.)

lumber_predictions |>
  metrics(truth = Y, estimate = .pred)
# A tibble: 3 × 3
  .metric .estimator .estimate
  <chr>   <chr>          <dbl>
1 rmse    standard       3.24 
2 rsq     standard       0.762
3 mae     standard       2.48 
lumber_predictions |>
  ggplot(aes(x = .pred, y = Y)) +
  geom_point(alpha = 0.75) +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  labs(
    x = "Predicted count",
    y = "Observed count",
    title = "Observed versus predicted customer counts"
  ) +
  theme_minimal()

Observed customer counts plotted against predicted customer counts from a Poisson regression model, with a dashed identity line. The points scatter around the line, with more spread at larger predicted counts.

If the model predicted every count perfectly, all points would fall on the dashed line. The spread around the line grows with the predicted count, which is what a Poisson model expects, since the variance equals the mean. The RMSE and \(R^2\) from metrics() are rough summaries; they treat a miss of 3 at a predicted count of 4 the same as a miss of 3 at a predicted count of 30, even though the first is much more surprising under the model.

Because the predictors act multiplicatively, predictions outside the range of the data can grow quickly. The farthest tract in the data is 9.9 miles from the store. Predicting for a tract 20 miles away extrapolates the exponential decline in distance to a range the data say nothing about, where (as the zero counts suggest) the true pattern may be quite different.

25.5 Things to Watch Out For

WarningCommon mistakes with multinomial, ordinal, and Poisson models
  • Reading a multinomial coefficient without its comparison category. Every coefficient compares a category with the baseline; say which two categories are being compared.
  • Reading the sign of a multinomial coefficient as the direction in which that category’s probability moves. The probability of a middle category can fall even when its coefficient is positive (Example 25.6).
  • Using a rare category as the multinomial baseline, which inflates the standard errors of every coefficient.
  • Testing a multinomial predictor one coefficient at a time. A predictor has \(J-1\) coefficients, and the test of the predictor has \(J-1\) degrees of freedom (Example 25.5).
  • Fitting too many coefficients for the size of the smallest category. With 26 preterm births, the pregnancy data support only a handful of predictors in a multinomial model.
  • Letting R choose the order of an ordinal response. Alphabetical order can reverse or scramble the categories without a warning (Example 25.12).
  • Interpreting polr() coefficients with the sign convention of another program. polr() uses \(\zeta_j-\eta_i\), so positive coefficients mean higher categories.
  • Taking a nonsignificant check of the proportional odds assumption as proof that it holds. With small samples, the check has little power (Example 25.10).
  • Treating ordinal codes 1, 2, 3 as a numeric response in a linear model. That assumes the categories are equally spaced, which the data cannot confirm.
  • Judging overdispersion from the raw mean and variance of the counts. The assumption is about the variance given the predictors (Example 25.15).
  • Ignoring overdispersion. The coefficients are fine, but standard errors, tests, and intervals are all too optimistic (Example 25.17).
  • Using an offset without checking that the count is proportional to the exposure (Example 25.18).
  • Fitting a linear model to counts, or to \(\log(Y+1)\), when many counts are small.
  • Extrapolating a log-linear model. Predicted counts grow or shrink exponentially outside the range of the data.

25.6 Recap

This chapter introduced three regression models for categorical and count responses.

Idea Meaning
Nominal response A categorical response whose categories have no natural order.
Multinomial logistic regression A model for nominal responses with more than two categories.
Baseline category The category every other category is compared with in a multinomial model. Changing it changes the printed comparisons but not the fitted probabilities.
Category-specific coefficients Separate coefficients for each non-baseline category comparison, \((J-1)p\) in all.
Multinomial predicted probabilities One fitted probability for each response category, adding to 1.
Multinomial log loss A metric that evaluates the predicted probability of the category that occurred.
Independence of irrelevant alternatives The multinomial logit property that the odds of one category over another do not depend on the other categories.
Ordinal response A categorical response whose categories have a meaningful order.
Proportional odds model An ordinal logistic model for cumulative probabilities, with shared slopes and separate cutpoints.
Cutpoints Thresholds that separate adjacent ordered categories on the logit scale.
Latent variable An unobserved continuous variable whose position relative to the cutpoints determines the observed category.
Proportional odds assumption The assumption that each predictor’s effect is the same at every cumulative split; also called parallel slopes.
Count response A nonnegative integer response variable.
Poisson distribution A count distribution whose mean and variance are both \(\mu\).
Poisson regression A regression model for counts with a log link, \(\log(\mu_i)=\mathbf{x}_i^\prime\boldsymbol{\beta}\).
Rate ratio The exponentiated Poisson coefficient: the factor by which the expected count is multiplied per unit increase in the predictor.
Overdispersion Variance larger than the Poisson model allows, given the predictors. It makes Poisson standard errors too small.
Quasi-Poisson and negative binomial models Two ways to allow for overdispersion.
Offset A term with its coefficient fixed at 1, used to model counts per unit of exposure.
Observed versus expected frequencies A comparison of how often each count occurs with how often the model predicts it, which can reveal excess zeros.

25.7 Check your understanding

NoteProblems
  1. What is the difference between a nominal response and an ordinal response? Give an example of each that is not in this chapter.

  2. A response has four categories and the model has three predictors. How many coefficients does a multinomial logistic regression model have? How many parameters does a proportional odds model have?

  3. In the pregnancy duration example, what does it mean that Preterm is the baseline category?

  4. The multinomial X5 coefficients are \(-0.222\) for Intermediate and \(-2.452\) for FullTerm, with Preterm as the baseline. What is the odds ratio for smoking for full term versus intermediate?

  5. If the baseline category is changed, what happens to the coefficients, and what happens to the fitted probabilities?

  6. Why is a rare category a poor choice of baseline?

  7. How many degrees of freedom does the likelihood ratio test for one quantitative predictor have in a multinomial model with five categories? Why?

  8. The Intermediate coefficient for nutritional status is positive, but the fitted probability of an intermediate birth falls at high nutritional scores. How can both be true?

  9. Why is accuracy alone not enough to compare the multinomial model with a model that has no predictors?

  10. Why can accuracy miss information that multinomial log loss uses?

  11. Explain the independence of irrelevant alternatives in your own words. Why is it seldom a concern for the pregnancy duration data?

  12. Why might an ordinal model be preferred over a multinomial model for ordered categories?

  13. What are cumulative probabilities in the proportional odds model, and how are single-category probabilities obtained from them?

  14. In polr(), the model is \(\text{logit}\,P(Y\le j)=\zeta_j-\eta_i\). Does a positive coefficient move probability toward higher or lower categories?

  15. The polr() coefficient for smoking is about \(-1.59\). Interpret \(\exp(-1.59)\) in terms of pregnancy duration.

  16. Describe the latent-variable interpretation of the proportional odds model. What changes when a predictor changes, and what stays fixed?

  17. What does the proportional odds assumption say, and how can it be checked with binary logistic regressions?

  18. In Example 25.10, the separate-split slopes for smoking were about \(-1.0\) and \(-2.3\). Why does this not settle whether the proportional odds assumption fails?

  19. Why can a likelihood ratio test not be used to compare the multinomial and proportional odds models? What was used instead?

  20. What goes wrong if an ordinal response is created with ordered(as.character(Y))?

  21. Why does Poisson regression use a log link, and what does it imply about how predictors affect the expected count?

  22. The Poisson rate ratio for distance to the store is about 0.879 per mile. What is the rate ratio for 3 miles? Express it as a percent change.

  23. The lumber counts have mean 11.2 and variance 44.1. Why does this not show that the data are overdispersed? What check should be used instead?

  24. What is overdispersion, and what does it do to the coefficients, standard errors, and confidence intervals of a Poisson model?

  25. What is an offset? When should the log of exposure be used as an offset, and how can that choice be checked?

  26. The Poisson model expected 0.15 tracts with zero customers, and 3 were observed. What might explain this, and what kinds of models could address it?

  27. Why should the multinomial, ordinal, and Poisson models not be treated as interchangeable?

  1. Nominal categories have no natural order; ordinal categories do. Favorite music genre is nominal; letter grade (A through F) is ordinal.

  2. The multinomial model has \((4-1)(3+1)=12\) coefficients. The proportional odds model has 3 slopes and 3 cutpoints, 6 parameters in all.

  3. Each coefficient row compares one of the other categories with preterm. The Intermediate row is about the odds of intermediate rather than preterm, and the FullTerm row is about the odds of full term rather than preterm.

  4. The log odds ratio is \(-2.452-(-0.222)=-2.230\), so the odds ratio is \(\exp(-2.230)\approx 0.11\). Smokers have about one-ninth the odds of a full-term rather than an intermediate birth.

  5. The coefficients change, because they now describe comparisons with a different category, but they are linear combinations of the old ones. The fitted probabilities do not change.

  6. Every comparison involves the baseline. If the baseline has few observations, every coefficient is estimated imprecisely.

  7. Four. The predictor has one coefficient for each of the \(5-1=4\) non-baseline categories, and the test asks whether all four are zero.

  8. The coefficient describes the odds of intermediate relative to preterm, and that ratio does increase with nutrition. But full-term births increase faster, so at high nutritional scores probability moves from intermediate to full term, and the probability of intermediate falls.

  9. The model’s accuracy has to be compared with what is possible without predictors. Always predicting the largest category, FullTerm, is right 40% of the time, so the model’s 66% has to be judged against 40%, not 0% or 33%.

  10. Accuracy uses only the predicted class. Log loss uses the predicted probability of the category that occurred, so it distinguishes a confident correct prediction from a lucky guess and penalizes confident mistakes heavily.

  11. The odds of choosing one category over another do not depend on which other categories exist. It matters when categories can be substitutes for each other, as in choices among products or modes of transport. Pregnancy duration categories are intervals of one quantity, not alternatives a person chooses among, so the property means little there.

  12. It uses the order. It has fewer parameters, so its estimates are more precise when its assumption holds, and its coefficients have a single interpretation in terms of higher versus lower categories.

  13. They are probabilities of being at or below a category, such as \(P(Y\le\text{Intermediate})\). A single category’s probability is a difference of adjacent cumulative probabilities, \(P(Y=j)=P(Y\le j)-P(Y\le j-1)\).

  14. Toward higher categories. A larger \(\eta_i\) makes \(\zeta_j-\eta_i\) smaller and so makes every cumulative probability \(P(Y\le j)\) smaller.

  15. \(\exp(-1.59)\approx 0.20\). At either split, smokers have about 0.20 times the odds of nonsmokers of being in a longer duration category, holding the other predictors fixed. Equivalently, smokers’ odds of a shorter duration category are about 4.9 times as large.

  16. An unobserved continuous variable \(Y^*=\eta_i+\varepsilon_i\) determines the category: the observed category is whichever interval between cutpoints \(Y^*\) falls into. A change in a predictor shifts the distribution of \(Y^*\); the cutpoints and the shape of the distribution stay fixed.

  17. It says each predictor has the same slope at every cumulative split. One check fits a binary logistic regression for each split, such as preterm versus the rest and full term versus the rest, and compares the slopes. Similar slopes support the assumption.

  18. The slopes have standard errors of about 0.5 to 0.6, and their intervals overlap widely. With 102 observations, the difference could be sampling variation. The check has little power, so it cannot show that the assumption holds either.

  19. The two models are not nested: the proportional odds model is not obtained by setting some multinomial coefficients to zero. AIC was used instead. The proportional odds model had the lower AIC, about 187.5 compared with 192.7.

  20. The levels are placed in alphabetical order. For the pregnancy data, that reverses the true order and flips the sign of every coefficient; for other labels it can scramble the categories. No warning is given.

  21. The log link keeps the expected count positive. Because \(\mu_i=\exp(\mathbf{x}_i^\prime\boldsymbol{\beta})\), each predictor multiplies the expected count by \(\exp(\beta_k)\) per unit, so effects are multiplicative.

  22. \(0.879^3\approx 0.68\), a decrease of about 32% in the expected count.

  23. The Poisson assumption concerns the variance of \(Y\) given the predictors. Tracts have different means, so the unconditional variance is larger than the unconditional mean even if each tract’s count is Poisson. The check is the Pearson dispersion statistic from the fitted model, which was about 0.98.

  24. Overdispersion is variance larger than the mean, given the predictors. The coefficient estimates are still consistent, but the standard errors are too small, so tests reject too often and confidence intervals are too narrow. In the simulation, nominal 95% intervals covered the true slope only about 77% of the time.

  25. An offset is a term in the linear predictor with its coefficient fixed at 1. The log of exposure is used as an offset when the count should be proportional to exposure, for example when units are observed for different lengths of time. To check it, put the log of exposure in as an ordinary predictor and see whether its coefficient is close to 1. For the lumber data it was about 0.20, so housing units should not be an offset.

  26. All three zero tracts were more than 9 miles from the store and close to a competitor, so customers beyond some distance may stop coming altogether, which a smooth exponential decline does not capture. A more flexible term for distance, or a zero-inflated Poisson model, could address it.

  27. They are designed for different kinds of response, and their coefficients mean different things. Multinomial coefficients compare pairs of categories, ordinal coefficients describe shifts toward higher categories, and Poisson coefficients describe multiplicative changes in an expected count. Using the wrong model gives coefficients that answer the wrong question.