Zeros, Two-Part Models and Counts
Yesterday's costs had two humps: people with a hospital stay and people without one. Today you model the two groups separately with a two-part model, which also splits an effect into "more people admitted" and "costlier when admitted". Then you model counts: physician visits and hospital stays. You use person-years as an offset, and test for overdispersion with Poisson and negative binomial models. A truth check finds where the overdispersion comes from.
By the end of today you can
- fit a two-part model and split an effect into its extensive and intensive margins
- never model costs only among people with a positive cost when I need the cost per person
- My count models use log(person-years) as an offset, and I report incidence rate ratios
- check overdispersion and use robust SEs or a negative binomial model
- compare observed and predicted zeros before considering a zero-inflated model
Today's 5.5-hour plan
In this lesson
12.1 Two humps, two groups (30 min)
"""Day 12.1: the two humps of Day 11 are two groups of people."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
from corridor.m2 import load # noqa: E402
df = load(survivors=True)
df["stay"] = np.where(df.fu_hospital > 0, "any stay", "no stay")
g = df.groupby("stay")["fu_cost"]
print(f"{'group':<10}{'people':>8}{'share':>8}{'mean':>9}{'median':>9}{'mean log':>10}")
for k, s in g:
print(f"{k:<10}{len(s):>8,}{len(s) / len(df):>8.1%}{s.mean():>9,.0f}{s.median():>9,.0f}{np.log(s).mean():>10.2f}")
print(f"\nHospital cost: {(df.fu_hospital == 0).mean():.1%} zeros; "
f"mean {df.fu_hospital.mean():,.0f}; mean among people with a stay {df.fu_hospital[df.fu_hospital > 0].mean():,.0f}")
group people share mean median mean log
any stay 1,607 27.7% 13,600 11,399 9.38
no stay 4,185 72.3% 1,478 1,165 7.05
Hospital cost: 72.3% zeros; mean 3,310; mean among people with a stay 11,931
The two humps of Day 11 are exactly these groups. A survivor with a stay costs $13,600 on average and one without costs $1,478. Hospital cost itself is zero for 72% of people. When the people with a stay have it, it averages $11,931. One regression has to explain two different things at once: whether someone is admitted, and how much it costs when they are. Those can depend on covariates in different ways.
12.2 The two-part model (45 min)
Split the mean into two parts:
class TwoPart:
"""Two-part model: Pr(y > 0) by logit, E[y | y > 0] by a gamma GLM with a log link.
The mean is the product: E[y] = Pr(y > 0) x E[y | y > 0]."""
def __init__(self, df, y, x=COVARIATES):
df = df.assign(_any=(df[y] > 0).astype(int))
self.part1 = smf.logit(f"_any ~ {x}", df).fit(disp=0)
self.part2 = smf.glm(f"{y} ~ {x}", df[df._any == 1], family=gamma_log()).fit(cov_type="HC1")
def prob(self, df):
return np.asarray(self.part1.predict(df))
def cond_mean(self, df):
return np.asarray(self.part2.predict(df))
def predict(self, df):
return self.prob(df) * self.cond_mean(df)
"""Day 12.2: a two-part model for hospital costs, and its two margins."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from corridor.costmodels import TwoPart, fit_glm, recycled_difference # noqa: E402
from corridor.m2 import load # noqa: E402
df = load(survivors=True)
tp = TwoPart(df, "fu_hospital")
t = pd.DataFrame({"part 1: odds ratio, any stay": np.exp(tp.part1.params),
"part 2: ratio of means, cost if a stay": np.exp(tp.part2.params)}).drop("Intercept")
print(t.round(3).to_string())
ppml = fit_glm(df, "fu_hospital", "poisson") # one-part alternative: a Poisson GLM on all, zeros included
print(f"\nmean hospital cost: observed {df.fu_hospital.mean():,.0f} two-part {tp.predict(df).mean():,.0f} "
f"one-part Poisson GLM {ppml.fittedvalues.mean():,.0f}")
print("\nHeart failure, incremental hospital cost (recycled predictions)")
p1, p0, dp = recycled_difference(tp.prob, df, "heart_failure")
c1, c0, dc = recycled_difference(tp.cond_mean, df, "heart_failure")
m1, m0, dm = recycled_difference(tp.predict, df, "heart_failure")
_, _, d_one = recycled_difference(ppml.predict, df, "heart_failure")
print(f" Pr(any stay): {p1:.3f} vs {p0:.3f}")
print(f" cost if a stay: {c1:,.0f} vs {c0:,.0f}")
print(f" expected cost: {m1:,.0f} vs {m0:,.0f} difference {dm:,.0f} (one-part Poisson GLM: {d_one:,.0f})")
d1, d0 = df.assign(heart_failure=1), df.assign(heart_failure=0)
extensive = np.mean((tp.prob(d1) - tp.prob(d0)) * tp.cond_mean(d0))
print(f" of which more people admitted (extensive margin): {extensive:,.0f}; "
f"costlier when admitted (intensive margin): {dm - extensive:,.0f}")
part 1: odds ratio, any stay part 2: ratio of means, cost if a stay
age10 0.969 0.999
male 0.990 1.007
qc 0.881 0.987
heart_failure 3.093 1.257
copd 1.874 1.047
hypertension 1.045 0.967
nephrology_visit 1.622 1.136
insulin 1.073 0.986
log_base 1.076 1.027
mean hospital cost: observed 3,310 two-part 3,310 one-part Poisson GLM 3,310
Heart failure, incremental hospital cost (recycled predictions)
Pr(any stay): 0.490 vs 0.242
cost if a stay: 13,825 vs 10,997
expected cost: 6,850 vs 2,703 difference 4,147 (one-part Poisson GLM: 4,035)
of which more people admitted (extensive margin): 2,746; costlier when admitted (intensive margin): 1,401
The two parts tell different stories. Heart failure triples the odds of a stay (OR 3.09) and makes a stay 26% costlier. COPD almost doubles the odds of a stay, but a COPD stay costs about the same as any other. Quebec residents are a little less likely to be admitted, and their stays cost the same.
The extensive margin (more people admitted) gives $2,746 of heart failure's $4,147 increment. The intensive margin (costlier stays) gives $1,401. A disease management program that prevents admissions acts on the first. A shorter length of stay acts on the second. That split is why payers like two-part models.
The overall answer barely depends on the model. The two-part model and a one-part Poisson GLM both reproduce the mean exactly, and their increments differ by $112. Use the two-part model when the two margins matter for the question, not because there are zeros.
12.3 Dropping the zeros (20 min)
Bug of the day. An analyst can't fit a gamma GLM to hospital costs ("the response must be positive"), so they keep the people with a stay, fit it, and use the predictions as everyone's expected cost:
"""Day 12 bug of the day: a hospital-cost model fitted only to people with a stay."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import statsmodels.formula.api as smf # noqa: E402
from corridor.costmodels import COVARIATES, TwoPart, gamma_log # noqa: E402
from corridor.m2 import load # noqa: E402
df = load(survivors=True)
pos = df[df.fu_hospital > 0]
g = smf.glm(f"fu_hospital ~ {COVARIATES}", pos, family=gamma_log()).fit() # the bug: zeros dropped
print(f"Expected hospital cost per person, used for a budget of {len(df):,} people:")
print(f" gamma GLM on people with a stay: {g.predict(df).mean():>8,.0f} -> ${g.predict(df).sum() / 1e6:,.1f} M")
print(f" two-part model: {TwoPart(df, 'fu_hospital').predict(df).mean():>8,.0f} "
f"-> ${TwoPart(df, 'fu_hospital').predict(df).sum() / 1e6:,.1f} M")
print(f" observed: {df.fu_hospital.mean():>8,.0f} -> ${df.fu_hospital.sum() / 1e6:,.1f} M")
Expected hospital cost per person, used for a budget of 5,792 people:
gamma GLM on people with a stay: 11,403 -> $66.0 M
two-part model: 3,310 -> $19.2 M
observed: 3,310 -> $19.2 M
The budget is $66.0 M instead of $19.2 M. The model answers "what does a stay cost?", not "what does a person cost?". Dropping zeros changes the question. Keep part 1, or use a model that accepts zeros (Poisson GLM).
Why it matters at work: Costs of adverse events, hospital costs, and costs of a rare procedure all have mostly zeros. Reviewers check whether the cost per patient includes the patients who had none.
Where you'll meet this: cost inputs for economic models (Module 5) · RWE comparisons of hospital use between drugs · budget impact analyses
12.4 Counts: Poisson, offsets and overdispersion (45 min)
Now use everyone, including the 432 people who died. Their follow-up is shorter, so they had less time to see a doctor. A count model handles that with an offset: $\log(\text{person-years})$ enters the model with its coefficient fixed at 1, so the model is for the rate:
$e^{\beta_k}$ is an incidence rate ratio (IRR).
def fit_counts(df, y, x=COVARIATES, exposure="py"):
"""Poisson GLM and negative binomial (NB2) for a count, with log(person-years) as the offset."""
off = np.log(df[exposure])
pois = smf.glm(f"{y} ~ {x}", df, family=sm.families.Poisson(), offset=off).fit()
nb = smf.negativebinomial(f"{y} ~ {x}", df, offset=off).fit(disp=0, maxiter=200)
return pois, nb
"""Day 12.4: physician visits as a count - Poisson, overdispersion and the negative binomial."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from corridor.costmodels import dispersion, fit_counts # noqa: E402
from corridor.m2 import load # noqa: E402
df = load() # everyone, including the 432 who died: the offset handles short follow-up
print(f"{len(df):,} people, {df.py.sum():,.1f} person-years, {df.fu_visits.sum():,} visits "
f"({df.fu_visits.sum() / df.py.sum():.2f} per person-year)")
print(f"visits per person: mean {df.fu_visits.mean():.2f}, variance {df.fu_visits.var():.2f}")
pois, nb = fit_counts(df, "fu_visits")
print(f"Poisson Pearson dispersion: {dispersion(pois):.2f} NB2 alpha: {nb.params['alpha']:.3f}")
robust = pois.model.fit(cov_type="HC1") # same coefficients, sandwich standard errors
t = pd.DataFrame({"IRR": np.exp(pois.params), "SE Poisson": pois.bse, "SE robust": robust.bse,
"IRR NB2": np.exp(nb.params.drop("alpha")), "SE NB2": nb.bse.drop("alpha")})
print(t.drop("Intercept").round(3).to_string())
6,224 people, 6,003.8 person-years, 67,031 visits (11.16 per person-year)
visits per person: mean 10.77, variance 20.64
Poisson Pearson dispersion: 1.37 NB2 alpha: 0.032
IRR SE Poisson SE robust IRR NB2 SE NB2
age10 1.028 0.005 0.006 1.029 0.006
male 0.992 0.008 0.009 0.992 0.009
qc 0.992 0.008 0.009 0.991 0.009
heart_failure 1.414 0.010 0.012 1.412 0.012
copd 1.139 0.015 0.017 1.138 0.018
hypertension 1.062 0.009 0.011 1.062 0.010
nephrology_visit 1.134 0.008 0.009 1.134 0.009
insulin 1.000 0.009 0.010 0.999 0.010
log_base 1.015 0.004 0.004 1.015 0.004
A Poisson count has variance equal to its mean. Here the variance (20.6) is about twice the mean (10.8), and the Pearson dispersion is 1.37. This is overdispersion. It does not bias the Poisson coefficients, but the Poisson standard errors are too small, here by 15–20%. Two fixes give the same answer:
- Robust (sandwich) standard errors on the Poisson model.
- A negative binomial (NB2) model, with variance $\mu + \alpha\mu^2$. Here $\hat\alpha = 0.032$.
The IRRs barely move. Heart failure means 41% more visits per person-year, COPD 14% more.
Check it in R. MASS::glm.nb reports $\theta = 1/\alpha$. The script also refits the two-part model:
# Day 12: negative binomial and two-part models in R. Compare with the Python output.
suppressPackageStartupMessages({ library(DBI); library(duckdb); library(MASS) })
con <- dbConnect(duckdb(shared_home = FALSE))
df <- dbGetQuery(con, "SELECT * FROM read_parquet('m2/analysis.parquet')")
dbDisconnect(con, shutdown = TRUE)
df <- transform(df, age10 = (age - 75) / 10, male = as.integer(sex == "M"), qc = as.integer(province == "QC"),
log_base = log(base_cost + 100), py = fu_days / 365.25)
x <- "age10 + male + qc + heart_failure + copd + hypertension + nephrology_visit + insulin + log_base"
nb <- glm.nb(as.formula(paste("fu_visits ~", x, "+ offset(log(py))")), data = df)
cat(sprintf("NB2 visits: theta %.1f, so alpha = 1/theta = %.3f; HF IRR %.3f\n",
nb$theta, 1 / nb$theta, exp(coef(nb)[["heart_failureTRUE"]])))
s <- subset(df, !died)
p1 <- glm(as.formula(paste("I(fu_hospital > 0) ~", x)), family = binomial, data = s)
p2 <- glm(as.formula(paste("fu_hospital ~", x)), family = Gamma(link = "log"), data = subset(s, fu_hospital > 0))
pred <- function(d) predict(p1, d, type = "response") * predict(p2, d, type = "response")
cat(sprintf("two-part mean hospital cost %s (observed %s)\n",
format(round(mean(pred(s))), big.mark = ","), format(round(mean(s$fu_hospital)), big.mark = ",")))
hf1 <- transform(s, heart_failure = TRUE); hf0 <- transform(s, heart_failure = FALSE)
cat(sprintf("HF increment %s\n", format(round(mean(pred(hf1)) - mean(pred(hf0))), big.mark = ",")))
NB2 visits: theta 31.4, so alpha = 1/theta = 0.032; HF IRR 1.412
two-part mean hospital cost 3,310 (observed 3,310)
HF increment 4,147
Try it (10 min). Add died to the visit model and fit it with and without the offset. What happens to the IRR for died?
Solution
"""Day 12 try it: the visit model without the person-years offset."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import statsmodels.api as sm # noqa: E402
import statsmodels.formula.api as smf # noqa: E402
from corridor.costmodels import COVARIATES # noqa: E402
from corridor.m2 import load # noqa: E402
df = load()
x = COVARIATES + " + died"
with_off = smf.glm(f"fu_visits ~ {x}", df, family=sm.families.Poisson(), offset=np.log(df.py)).fit()
no_off = smf.glm(f"fu_visits ~ {x}", df, family=sm.families.Poisson()).fit()
for name, m in (("with offset", with_off), ("no offset", no_off)):
print(f"{name:<12} IRR for died: {np.exp(m.params['died']):.2f}")
rate = df.groupby("died").apply(lambda g: g.fu_visits.sum() / g.py.sum(), include_groups=False)
count = df.groupby("died").fu_visits.mean()
print(f"visits per person: survivors {count[0]:.1f}, died {count[1]:.1f}")
print(f"visits per person-year: survivors {rate[0]:.1f}, died {rate[1]:.1f}")
with offset IRR for died: 1.04
no offset IRR for died: 0.52
visits per person: survivors 11.1, died 6.4
visits per person-year: survivors 11.1, died 12.9
Without the offset, people who died seem to use half as much care (IRR 0.52). Per person-year, they use slightly more (12.9 against 11.1 visits). Forgetting the offset turns "observed for less time" into "uses less care". That is Day 7's per-person versus per-person-year lesson, in a regression.
12.5 Where overdispersion comes from (25 min)
Truth check. Overdispersion usually means unobserved differences between people: some see the doctor more for reasons the data don't record. The generator gives each person a hidden frailty that multiplies their visit rate. Real data never have this column; data/truth/ does.
"""Day 12.5 (truth check): where does the overdispersion in visits come from?
The generator gives each person a hidden frailty that multiplies their visit rate. Real data have
no such column; here data/truth/ has it, so we can add it and watch the overdispersion shrink.
"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import duckdb # noqa: E402
import numpy as np # noqa: E402
from corridor.costmodels import COVARIATES, dispersion, fit_counts # noqa: E402
from corridor.m2 import load # noqa: E402
from corridor.truth import TRUTH # noqa: E402
df = load()
frailty = duckdb.sql(f"SELECT person_id, frailty FROM read_csv('{TRUTH}/persons_truth.csv')").df()
df = df.merge(frailty, on="person_id")
df["log_frailty"] = np.log(df["frailty"])
print(f"hidden frailty in the cohort: mean {df.frailty.mean():.2f}, sd {df.frailty.std():.2f}")
for label, x in (("observed covariates", COVARIATES), ("+ hidden frailty", COVARIATES + " + log_frailty")):
pois, nb = fit_counts(df, "fu_visits", x)
print(f"{label:<22} Poisson dispersion {dispersion(pois):.2f} NB2 alpha {nb.params['alpha']:.3f} "
f"HF IRR {np.exp(pois.params['heart_failure']):.3f}")
hidden frailty in the cohort: mean 1.10, sd 0.53
observed covariates Poisson dispersion 1.37 NB2 alpha 0.032 HF IRR 1.414
+ hidden frailty Poisson dispersion 1.11 NB2 alpha 0.009 HF IRR 1.438
With the hidden frailty added, the dispersion falls from 1.37 to 1.11 and $\alpha$ from 0.032 to 0.009. The negative binomial's $\alpha$ was standing in for frailty. This is the gamma–Poisson mixture behind NB2: a Poisson rate multiplied by a gamma-distributed frailty gives a negative binomial count. The heart failure IRR rises a little when frailty is controlled (1.414 to 1.438). For a count model the omitted frailty is independent of heart failure here, so it adds noise rather than bias.
12.6 Seventy percent zeros are not excess zeros (30 min)
Seventy percent of the cohort had no hospital stay in follow-up. That tempts people to fit a zero-inflated model. First ask: does a plain Poisson already predict 70% zeros?
"""Day 12.6: hospital stays - 70% zeros, but are they EXCESS zeros?"""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from scipy import stats # noqa: E402
from corridor.costmodels import dispersion, fit_counts # noqa: E402
from corridor.m2 import load # noqa: E402
df = load()
pois, nb = fit_counts(df, "fu_stays")
mu_p = pois.fittedvalues.to_numpy()
mu_n = nb.predict(df, offset=np.log(df.py)).to_numpy()
a = nb.params["alpha"]
k = np.arange(3)
rows = {"observed": [(df.fu_stays == j).mean() for j in k] + [(df.fu_stays >= 3).mean()],
"Poisson": [stats.poisson.pmf(j, mu_p).mean() for j in k] + [stats.poisson.sf(2, mu_p).mean()],
"NB2": [stats.nbinom.pmf(j, 1 / a, 1 / (1 + a * mu_n)).mean() for j in k]
+ [stats.nbinom.sf(2, 1 / a, 1 / (1 + a * mu_n)).mean()]}
print("Share of people with 0, 1, 2, 3+ stays in follow-up")
print((100 * pd.DataFrame(rows, index=["0", "1", "2", "3+"]).T).round(2).to_string())
print(f"\nPoisson dispersion {dispersion(pois):.2f} NB2 alpha {a:.4f}")
r2 = pois.resid_pearson**2
top = r2.sort_values(ascending=False).index[:10]
print(f"the 10 largest Pearson terms: {r2[top].sum():.0f} of {r2.sum():,.0f}; all 10 died within "
f"{df.loc[top, 'fu_days'].max()} days of index with a stay")
surv, _ = fit_counts(df[df.died == 0], "fu_stays")
print(f"Poisson dispersion among survivors: {dispersion(surv):.2f}")
print("IRRs (Poisson):", ", ".join(f"{v} {np.exp(pois.params[v]):.2f}" for v in ("heart_failure", "copd", "nephrology_visit", "qc")))
Share of people with 0, 1, 2, 3+ stays in follow-up
0 1 2 3+
observed 69.89 24.12 5.0 1.00
Poisson 70.07 23.85 5.0 1.08
NB2 70.07 23.84 5.0 1.08
Poisson dispersion 1.37 NB2 alpha 0.0002
the 10 largest Pearson terms: 905 of 8,504; all 10 died within 31 days of index with a stay
Poisson dispersion among survivors: 1.04
IRRs (Poisson): heart_failure 2.30, copd 1.49, nephrology_visit 1.44, qc 0.98
Yes. The Poisson model predicts 70.07% zeros against 69.89% observed, and gets the 1s, 2s and 3+ right too. The NB2 model finds almost no extra variance ($\alpha$ = 0.0002). Many zeros are not excess zeros: a rare event with a low rate gives lots of zeros on its own. Check observed against predicted counts before you reach for a zero-inflated model.
The Pearson dispersion of 1.37 is misleading here. Ten people who died within a month of index, each with a stay, contribute 905 of the Pearson statistic's 8,504. Their offset is tiny, so one stay is a huge residual. Among survivors, the dispersion is 1.04. Look at what drives a diagnostic before you act on it.
12.7 Mini-project: hospital cost by province, with bootstrap CIs (65 min)
The burden-of-illness question for Module 2's capstone: what is the expected hospital cost per person in each province, and what is heart failure's increment? Standardize both provinces to the whole cohort's case mix (recycled predictions), and get 95% confidence intervals from 200 bootstrap samples: draw people with replacement, refit both parts, recompute. It takes about 30 seconds.
"""Day 12 mini-project: expected hospital cost by province and for heart failure, with bootstrap CIs."""
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import numpy as np # noqa: E402
import pandas as pd # noqa: E402
from corridor.costmodels import TwoPart, recycled_difference # noqa: E402
from corridor.m2 import load # noqa: E402
df = load(survivors=True)
def estimates(d):
tp = TwoPart(d, "fu_hospital")
p_on, p_qc = (tp.prob(d.assign(qc=v)).mean() for v in (0, 1))
m_qc, m_on, d_qc = recycled_difference(tp.predict, d, "qc")
_, _, d_hf = recycled_difference(tp.predict, d, "heart_failure")
return {"Pr(stay) ON": p_on, "Pr(stay) QC": p_qc, "cost ON": m_on, "cost QC": m_qc,
"QC - ON": d_qc, "HF increment": d_hf}
point = estimates(df)
rng = np.random.default_rng(2026)
boot = pd.DataFrame([estimates(df.iloc[rng.integers(0, len(df), len(df))]) for _ in range(200)])
print("Two-part model, hospital cost per survivor in 2025 (standardized to the whole cohort's mix)")
print(f"{'quantity':<14}{'estimate':>10}{'95% CI (bootstrap, 200)':>28}")
for k, v in point.items():
lo, hi = boot[k].quantile([0.025, 0.975])
fmt = (lambda z: f"{z:.3f}") if k.startswith("Pr") else (lambda z: f"{z:,.0f}")
print(f"{k:<14}{fmt(v):>10}{fmt(lo):>16} to {fmt(hi):>8}")
Two-part model, hospital cost per survivor in 2025 (standardized to the whole cohort's mix)
quantity estimate 95% CI (bootstrap, 200)
Pr(stay) ON 0.286 0.272 to 0.301
Pr(stay) QC 0.262 0.244 to 0.281
cost ON 3,425 3,261 to 3,636
cost QC 3,108 2,859 to 3,439
QC - ON -317 -650 to 39
HF increment 4,147 3,602 to 4,739
At the same case mix, Quebec residents are a little less likely to have a stay (26.2% vs 28.6%), and their expected hospital cost is $317 lower, but the interval includes zero (−$650 to $39). Heart failure adds $4,147 (95% CI $3,602 to $4,739). The bootstrap resamples people, not rows, so it respects the fact that each person's two parts come from the same data.
Write a short paragraph a provincial analyst could read: the expected cost in each province, the uncertainty, and the heart failure increment, split into its two margins (12.2).
12.8 Save your work
python -m pytest -q
git add .
git commit -m "Day 12: two-part models, count models with offsets, overdispersion"
Day 12 checklist
- I can fit a two-part model and split an effect into its extensive and intensive margins
- I never model costs only among people with a positive cost when I need the cost per person
- My count models use log(person-years) as an offset, and I report incidence rate ratios
- I check overdispersion and use robust SEs or a negative binomial model
- I compare observed and predicted zeros before considering a zero-inflated model
Bloc français (30 min)
Thème : les zéros et les données de comptage.
Sept personnes sur dix n'ont eu aucun séjour à l'hôpital. Le modèle en deux parties estime d'abord la probabilité d'un séjour, puis le coût d'un séjour. Pour les visites médicales, on utilise un modèle de Poisson avec le logarithme des personnes-années comme terme de décalage. La variance des visites dépasse leur moyenne : c'est la surdispersion. Le modèle binomial négatif en tient compte.
| Français | English |
|---|---|
| le modèle en deux parties | the two-part model |
| la probabilité d'un séjour | the probability of a stay |
| la marge extensive | the extensive margin |
| la marge intensive | the intensive margin |
| les données de comptage | count data |
| le terme de décalage | the offset |
| le rapport des taux d'incidence | the incidence rate ratio (IRR) |
| la surdispersion | overdispersion |
| la loi binomiale négative | the negative binomial distribution |
| l'excès de zéros | excess zeros |
| le rééchantillonnage (bootstrap) | the bootstrap |
| l'intervalle de confiance | the confidence interval |
Exercices
- Translate: "Without the offset, people who died seem to use less care."
- Translate: « La plupart des zéros ne sont pas un excès de zéros. »
- In three French sentences, explain the two margins of the heart failure increment.
Réponses
- Sans le terme de décalage, les personnes décédées semblent utiliser moins de soins.
- "Most of the zeros are not excess zeros."
- Example: L'insuffisance cardiaque augmente la probabilité d'être hospitalisé : c'est la marge extensive. Elle augmente aussi le coût d'un séjour : c'est la marge intensive. Environ deux tiers du coût différentiel viennent de la première marge.