Applied Health Economics, RWE & HTA
Overview / Module 2 / Day 11
Module 2 · Biostatistics & econometrics · Day 11 of 100

Skewed Costs: Log Models, Smearing and Gamma GLMs

A budget impact analysis needs the mean cost, because the payer pays for everyone. Health care costs are badly skewed, so the mean is hard to model. The habit of taking logs gives a good-looking regression that predicts the wrong mean. Today you fit OLS, log-OLS with Duan's smearing, and gamma GLMs to the cohort's 2025 costs. A simulation with a known answer shows when each one works, and cross-validation shows which predicts best on new people.

▶
Video for Day 11 coming soon

By the end of today you can

  • python day11/build_analysis_file.py builds m2/analysis.parquet, and git ignores it
  • explain why exp(predicted log cost) is not the mean, and correct it with smearing
  • fit a gamma GLM with a log link and report ratios of means and dollar increments
  • run and read a modified Park test
  • compare cost models out of sample on bias and calibration, not only RMSE

Today's 5.5-hour plan

LessonProjectBreakCommitFrançais
0:00–0:25
11.1 Set up Module 2: one analysis file
0:25–1:05
11.2 The shape of costs, and what it does to OLS
1:05–1:20
Break
1:20–2:00
11.3 Log models and the retransformation problem
2:00–2:40
11.4 A simulation with a known answer
2:40–2:55
Break
2:55–3:35
11.5 The gamma GLM: model the mean directly
3:35–3:55
11.6 Which family? The modified Park test
3:55–4:10
11.7 A budget from exp(log cost)
4:10–4:50
11.8 Mini-project: which model predicts best?
4:50–5:00
11.9 Save your work
5:00–5:30
Bloc français

In this lesson

11.1 Set up Module 2: one analysis file (25 min)

Every Module 2 day uses the same people: the Module 1 capstone cohort (6,224 adults aged 66+ with type 2 diabetes and CKD, index date 1 January 2025). One builder joins the capstone files to what the statistics days need from the warehouse: follow-up visit and stay counts, and the day of the first admission.

pip install statsmodels==0.15.0 scipy==1.18.1
python day10/build_capstone.py          # if capstone/output/ is empty
python day11/build_analysis_file.py
"""Module 2: one person-level analysis file for Days 11-19.

    python day11/build_analysis_file.py      # writes m2/analysis.parquet (person-level: git-ignored)

It starts from the Module 1 capstone (cohort and 3-year costs, index 2025-01-01) and adds what the
statistics days need from the warehouse: follow-up visit and stay counts, and the first admission.
"""

import os

from corridor.db import ROOT

M2 = os.path.join(ROOT, "m2")
ANALYSIS = os.path.join(M2, "analysis.parquet").replace("\\", "/")
CAPSTONE = os.path.join(ROOT, "capstone", "output").replace("\\", "/")
END = "DATE '2025-12-31'"

ANALYSIS_SQL = f"""
WITH c AS (SELECT * FROM read_parquet('{CAPSTONE}/cohort.parquet')),
k AS (SELECT * FROM read_parquet('{CAPSTONE}/costs_3yr.parquet')),
visits AS (
    SELECT c.person_id, count(*) AS fu_visits
    FROM c JOIN fct_physician_claims p ON p.person_id = c.person_id
         AND p.service_date BETWEEN c.index_date AND c.end_date
    GROUP BY 1),
stays AS (
    SELECT c.person_id, count(*) AS fu_stays, min(s.admit_date) AS first_admit
    FROM c JOIN fct_hospital_stays s ON s.person_id = c.person_id
         AND s.admit_date BETWEEN c.index_date AND c.end_date
    GROUP BY 1)
SELECT c.person_id, c.province, c.region, c.sex, c.age, c.income_quintile, c.rural,
       c.heart_failure, c.hypertension, c.copd, c.prior_stays, c.physician_visits AS base_visits,
       c.nephrology_visit, c.insulin, c.sglt2, c.drug_classes,
       b.total AS base_cost,
       c.index_date, c.end_date, c.died,
       f.days AS fu_days, f.hospital AS fu_hospital, f.physician AS fu_physician, f.drug AS fu_drug,
       f.total AS fu_cost,
       coalesce(v.fu_visits, 0) AS fu_visits, coalesce(s.fu_stays, 0) AS fu_stays,
       -- time to event in days from the index date (day 1 = index date)
       date_diff('day', c.index_date, c.end_date) + 1 AS t_end,
       date_diff('day', c.index_date, s.first_admit) + 1 AS t_admit
FROM c
JOIN k b ON b.person_id = c.person_id AND b.period = 'baseline_1'
JOIN k f ON f.person_id = c.person_id AND f.period = 'follow_up'
LEFT JOIN visits v ON v.person_id = c.person_id
LEFT JOIN stays s ON s.person_id = c.person_id
ORDER BY c.person_id
"""

def build(con):
    """Write m2/analysis.parquet from a warehouse connection and return the row count."""
    os.makedirs(M2, exist_ok=True)
    con.execute(f"COPY ({ANALYSIS_SQL}) TO '{ANALYSIS}' (FORMAT parquet)")
    return con.execute(f"SELECT count(*) FROM '{ANALYSIS}'").fetchall()[0][0]

def load(con=None, survivors=False):
    """The analysis file as a pandas DataFrame, with the derived columns the lessons use."""
    import duckdb
    import numpy as np

    if not os.path.exists(ANALYSIS):
        raise FileNotFoundError("m2/analysis.parquet is missing: run  python day11/build_analysis_file.py")
    con = con or duckdb.connect()
    df = con.sql(f"SELECT * FROM '{ANALYSIS}'").df()
    for col in ("rural", "heart_failure", "hypertension", "copd", "nephrology_visit", "insulin", "sglt2", "died"):
        df[col] = df[col].astype(int)
    df["age10"] = (df["age"] - 75) / 10           # age in decades, centred at 75
    df["male"] = (df["sex"] == "M").astype(int)
    df["qc"] = (df["province"] == "QC").astype(int)
    df["log_base"] = np.log(df["base_cost"] + 100)  # baseline cost on a log scale (+$100 for the few near 0)
    df["py"] = df["fu_days"] / 365.25             # follow-up person-years
    if survivors:
        df = df[df["died"] == 0].reset_index(drop=True)
    return df
"""Day 11: build the Module 2 analysis file from the capstone outputs and the warehouse."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.db import show, warehouse  # noqa: E402
from corridor.m2 import ANALYSIS, build  # noqa: E402

con = warehouse()
n = build(con)
print(f"m2/analysis.parquet: {n:,} people")
show(con, f"""
    SELECT coalesce(province, 'All') AS province, count(*) AS people, sum(died::INT) AS deaths,
           round(avg(fu_cost)) AS mean_cost, sum(fu_visits) AS visits, sum(fu_stays) AS stays,
           count(t_admit) AS admitted
    FROM '{ANALYSIS}' GROUP BY ROLLUP (province) ORDER BY grouping(province), province""")
m2/analysis.parquet: 6,224 people
province  people  deaths  mean_cost  visits  stays  admitted
      ON    3956     265       5397   42867   1494      1222
      QC    2268     167       4795   24164    828       652
     All    6224     432       5178   67031   2322      1874

m2/analysis.parquet is person-level, so .gitignore keeps it out of git, like the capstone files. Days 11 and 12 model costs for the 5,792 people who survived 2025, because each of them has a full year of costs. People who died have shorter and costlier follow-up. Days 12 and 13 bring them back in with offsets and survival models.

Why it matters at work: One analysis file per project, built by code from versioned inputs, is what lets a reviewer rerun your numbers. Every Module 2 result traces back to the Module 1 capstone's fingerprints.

Where you'll meet this: the "analysis dataset" in every statistical analysis plan · ICES and Statistics Canada research data centres, where only the analysis file comes into the project folder


11.2 The shape of costs, and what it does to OLS (40 min)

"""Day 11.1: the shape of a year of costs, and what it does to OLS."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib  # noqa: E402

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
from scipy import stats  # noqa: E402
from statsmodels.stats.diagnostic import het_breuschpagan  # noqa: E402

from corridor.costmodels import fit_ols  # noqa: E402
from corridor.db import ROOT  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)        # people alive all of 2025: a full year of costs each
y = df["fu_cost"]
print(f"Survivors with a full 2025: {len(df):,}")
print(f"mean {y.mean():,.0f}   median {y.median():,.0f}   sd {y.std():,.0f}   max {y.max():,.0f}")
print(f"skewness {stats.skew(y):.2f}   (log scale: {stats.skew(np.log(y)):.2f})")
print(f"zeros: {(y == 0).sum()}   any hospital stay: {(df.fu_hospital > 0).mean():.1%}")

ols = fit_ols(df, "fu_cost")
lm, pval, _, _ = het_breuschpagan(ols.resid, ols.model.exog)
print(f"\nOLS: R2 {ols.rsquared:.3f}   mean prediction {ols.fittedvalues.mean():,.0f}   "
      f"lowest prediction {ols.fittedvalues.min():,.0f}   negative predictions {(ols.fittedvalues < 0).sum()}")
print(f"Breusch-Pagan test for constant variance: chi2 {lm:,.0f}, p = {pval:.1e}")
print("\nResidual spread by decile of the OLS prediction:")
dec = np.ceil(ols.fittedvalues.rank(pct=True) * 10).astype(int)
spread = ols.resid.groupby(dec).std()
print("  decile  " + "  ".join(f"{d:>6}" for d in spread.index))
print("  sd($)   " + "  ".join(f"{v:>6,.0f}" for v in spread.values))

fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].hist(y / 1000, bins=60, color="#4f9cf9")
ax[0].set(title="2025 cost per survivor", xlabel="$ thousands", ylabel="people")
ax[1].hist(np.log(y), bins=60, color="#a78bfa")
ax[1].set(title="log(cost): two humps", xlabel="log dollars")
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day11_shape.png"), dpi=130)
Survivors with a full 2025: 5,792
mean 4,841   median 1,528   sd 6,905   max 59,464
skewness 2.51   (log scale: 0.49)
zeros: 0   any hospital stay: 27.7%

OLS: R2 0.098   mean prediction 4,841   lowest prediction 1,374   negative predictions 0
Breusch-Pagan test for constant variance: chi2 159, p = 1.5e-29

Residual spread by decile of the OLS prediction:
  decile       1       2       3       4       5       6       7       8       9      10
  sd($)    4,715   5,093   4,831   5,549   6,135   5,748   6,553   7,218   8,222   9,709

2025 cost per survivor, in dollars and in logs

The mean ($4,841) is three times the median ($1,528), and the skewness is 2.5. On the log scale the distribution is almost symmetric, but it has two humps: people without a hospital stay (around $1,100) and people with one (around $12,000). Day 12 models those two groups separately.

OLS on dollars is not wrong for the mean. With an intercept, its predictions average exactly to the observed mean, and its slopes are unbiased under the usual conditions. Its problems are elsewhere:

  • The variance is not constant. The residual spread doubles from the lowest to the highest decile of prediction (Breusch–Pagan p ≈ 10⁻²⁹). Use robust (HC1) standard errors, which fit_ols does.
  • The effects are additive. Heart failure adds the same dollars to everyone. Costs usually work in proportions: heart failure multiplies an already high cost.
  • Predictions can be negative. None are here, but with a sicker or healthier subgroup they can be.

The usual fix is to take logs. That fix has a trap.


11.3 Log models and the retransformation problem (40 min)

Fit OLS to $\log y$:

log⁡yi=xi′β+εi\log y_i = x_i'\beta + \varepsilon_i

The prediction $\exp(x_i'\hat\beta)$ estimates the geometric mean, not the mean. If $\varepsilon$ is normal with variance $\sigma^2$,

E[yi∣xi]=exp⁡(xi′β)×E[eεi]=exp⁡ ⁣(xi′β+σ22)E[y_i \mid x_i] = \exp(x_i'\beta) \times E[e^{\varepsilon_i}] = \exp\!\left(x_i'\beta + \tfrac{\sigma^2}{2}\right)

Duan's smearing estimator (1983) drops the normality assumption and estimates $E[e^{\varepsilon}]$ by the average of $\exp(\hat\varepsilon_i)$ over the sample:

def smearing_factor(log_model, groups=None):
    """Duan's smearing factor: the mean of exp(residual). With `groups` (an array aligned with the
    estimation sample), one factor per group, for errors whose variance differs by group."""
    e = np.exp(log_model.resid)
    if groups is None:
        return float(e.mean())
    return e.groupby(np.asarray(groups)).mean().to_dict()

def predict_log_ols(log_model, df, smear=1.0, groups=None):
    """exp(x'b) x smearing. `smear` is a number, or a dict looked up with `groups` (aligned with df)."""
    base = np.exp(log_model.predict(df))
    if isinstance(smear, dict):
        return base * np.array([smear[g] for g in np.asarray(groups)])
    return base * smear
"""Day 11.2: OLS on log(cost), and getting back to dollars with Duan's smearing."""

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.costmodels import fit_log_ols, predict_log_ols, smearing_factor  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
lm = fit_log_ols(df, "fu_cost")
print("log-OLS coefficients (x100 = approximate % change in the GEOMETRIC mean):")
print(lm.params.round(3).to_string())
print(f"residual sd on the log scale: {np.sqrt(lm.scale):.3f}")

naive = predict_log_ols(lm, df)                                  # exp(x'b): the geometric mean
s = smearing_factor(lm)
smeared = predict_log_ols(lm, df, s)
by_hf = smearing_factor(lm, df["heart_failure"])
smeared_hf = predict_log_ols(lm, df, by_hf, df["heart_failure"])
print(f"\nsmearing factor: {s:.3f}    by heart failure: "
      + ", ".join(f"HF={k}: {v:.3f}" for k, v in by_hf.items()))

print("\nMean cost by heart failure: observed and predicted")
print(f"{'group':<8}{'observed':>10}{'exp(xb)':>10}{'smeared':>10}{'smeared by HF':>15}")
for g in (0, 1, "all"):
    m = slice(None) if g == "all" else (df["heart_failure"] == g).to_numpy()
    print(f"{('HF=' + str(g)) if g != 'all' else 'all':<8}{df['fu_cost'][m].mean():>10,.0f}{naive[m].mean():>10,.0f}"
          f"{smeared[m].mean():>10,.0f}{smeared_hf[m].mean():>15,.0f}")
log-OLS coefficients (x100 = approximate % change in the GEOMETRIC mean):
Intercept           6.002
age10              -0.010
male                0.005
qc                 -0.230
heart_failure       0.763
copd                0.455
hypertension       -0.055
nephrology_visit    0.298
insulin             0.353
log_base            0.185
residual sd on the log scale: 1.128

smearing factor: 2.046    by heart failure: HF=0: 2.071, HF=1: 1.895

Mean cost by heart failure: observed and predicted
group     observed   exp(xb)   smeared  smeared by HF
HF=0         4,139     2,066     4,227          4,278
HF=1         9,113     5,175    10,588          9,809
all          4,841     2,505     5,125          5,059

Three lessons are in that table:

  1. exp(x'b) predicts half the cost. $2,505 against $4,841 observed. The smearing factor is 2.05: the mean is twice the geometric mean.
  2. One smearing factor assumes the log-scale variance is the same for everyone. It is not. The factor is 2.07 without heart failure and 1.90 with it. With one factor, the HF group is overpredicted by $1,475.
  3. Even smeared by group, log-OLS overpredicts ($5,059 vs $4,841). The log-scale errors are not one distribution shifted by $x'\beta$. They are a mixture of two humps, and smearing cannot fix a mixture.

The coefficients are also on a different scale from the question. A log-OLS coefficient of 0.763 for heart failure says the geometric mean is $e^{0.763} = 2.14$ times higher. The payer wants the ratio of means.

Try it (10 min). Compute one smearing factor per province. Compare the predicted mean cost in each province with one factor and with two, and with the observed means.

Solution
"""Day 11 try it: smearing factors by province. Does one factor fit both provinces?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.costmodels import fit_log_ols, predict_log_ols, smearing_factor  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
lm = fit_log_ols(df, "fu_cost")
one = smearing_factor(lm)
by = smearing_factor(lm, df["province"])
print(f"one factor {one:.3f}   by province: " + ", ".join(f"{k} {v:.3f}" for k, v in by.items()))
for name, p in (("one factor", predict_log_ols(lm, df, one)),
                ("by province", predict_log_ols(lm, df, by, df["province"]))):
    m = p.groupby(df["province"]).mean()
    print(f"{name:<12} ON {m['ON']:,.0f}  QC {m['QC']:,.0f}  difference {m['ON'] - m['QC']:,.0f}")
obs = df.groupby("province")["fu_cost"].mean()
print(f"{'observed':<12} ON {obs['ON']:,.0f}  QC {obs['QC']:,.0f}  difference {obs['ON'] - obs['QC']:,.0f}")
one factor 2.046   by province: ON 1.963, QC 2.191
one factor   ON 5,581  QC 4,326  difference 1,255
by province  ON 5,356  QC 4,632  difference 723
observed     ON 5,081  QC 4,421  difference 660

The Quebec residuals are more spread out on the log scale (factor 2.19 against 1.96), so one factor exaggerates the provincial gap: $1,255 against $660 observed. Province-specific factors bring it to $723. A smearing factor per group is a model of the variance. You have to choose the groups, and it is easy to choose wrong.


11.4 A simulation with a known answer (40 min)

Real data never tell you the true mean. A simulation does. corridor/sim.py draws log-normal costs where the log-scale standard deviation is 1.0 for everyone (homoscedastic), or 1.0 without and 1.5 with heart failure (heteroscedastic):

"""Day 11: simulated costs with a known true mean, to see which estimators recover it.

log(cost) = 7.3 + 0.8 hf + 0.1 age10 + e,   e ~ Normal(0, sigma^2)
sigma = 1.0 for everyone (homoscedastic), or 1.0 without and 1.5 with heart failure (heteroscedastic).
The true mean is exp(x'b + sigma^2 / 2), so every estimate can be checked against it.
"""

import numpy as np
import pandas as pd

B0, B_HF, B_AGE = 7.3, 0.8, 0.1

def skewed_costs(n=20_000, hetero=False, seed=2026):
    rng = np.random.default_rng(seed)
    hf = (rng.random(n) < 0.15).astype(int)
    age10 = rng.normal(0, 0.8, n)
    sigma = np.where(hf == 1, 1.5, 1.0) if hetero else np.ones(n)
    xb = B0 + B_HF * hf + B_AGE * age10
    cost = np.exp(xb + rng.normal(0, sigma))
    return pd.DataFrame({"hf": hf, "age10": age10, "cost": cost, "true_mean": np.exp(xb + sigma**2 / 2)})

def true_hf_increment(df, hetero):
    """True average incremental cost of heart failure in this sample (set hf to 1, then to 0)."""
    s1 = 1.5 if hetero else 1.0
    xb0 = B0 + B_AGE * df["age10"]
    return float(np.mean(np.exp(xb0 + B_HF + s1**2 / 2) - np.exp(xb0 + 0.5)))

The question is the one an HTA asks: what is the average incremental cost of heart failure? Each estimator answers with recycled predictions: predict everyone's cost with heart failure switched on, then off, and take the difference of the averages.

def recycled_difference(predict, df, var, a=1, b=0):
    """Average predicted mean with `var` set to `a` for everyone, minus the same with `var` = `b`.
    `predict` is a function df -> predicted means. This is the incremental effect in dollars."""
    d1, d0 = df.copy(), df.copy()
    d1[var], d0[var] = a, b
    m1, m0 = np.mean(predict(d1)), np.mean(predict(d0))
    return float(m1), float(m0), float(m1 - m0)
"""Day 11.3: which estimator recovers the true mean? Simulated costs with a known answer."""

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 gamma_log, recycled_difference  # noqa: E402
from corridor.sim import skewed_costs, true_hf_increment  # noqa: E402

for hetero in (False, True):
    df = skewed_costs(hetero=hetero)
    truth = true_hf_increment(df, hetero)
    lm = smf.ols("np.log(cost) ~ hf + age10", df).fit()
    s = float(np.mean(np.exp(lm.resid)))
    s_g = np.exp(lm.resid).groupby(df["hf"]).mean()
    gl = smf.glm("cost ~ hf + age10", df, family=gamma_log()).fit()
    ols = smf.ols("cost ~ hf + age10", df).fit()
    preds = {
        "OLS on dollars": ols.predict,
        "log-OLS, exp(xb)": lambda d: np.exp(lm.predict(d)),
        "log-OLS, smeared": lambda d: np.exp(lm.predict(d)) * s,
        "log-OLS, smeared by HF": lambda d: np.exp(lm.predict(d)) * d["hf"].map(s_g),
        "gamma GLM, log link": gl.predict,
    }
    print(f"\n=== {'Heteroscedastic' if hetero else 'Homoscedastic'} errors (sd 1.0{', 1.5 with HF' if hetero else ''})"
          f"   true mean {df.true_mean.mean():,.0f}   true HF increment {truth:,.0f}")
    print(f"{'estimator':<26}{'mean':>9}{'HF increment':>14}{'error':>9}")
    for name, f in preds.items():
        _, _, inc = recycled_difference(f, df, "hf")
        print(f"{name:<26}{np.mean(f(df)):>9,.0f}{inc:>14,.0f}{100 * (inc / truth - 1):>8.1f}%")
    s1 = 1.5 if hetero else 1.0
    print(f"hf slope: log-OLS {lm.params['hf']:.3f} (true 0.8, the log ratio of GEOMETRIC means)   "
          f"gamma GLM {gl.params['hf']:.3f} (true {0.8 + (s1**2 - 1) / 2:.3f}, the log ratio of MEANS)")
=== Homoscedastic errors (sd 1.0)   true mean 2,886   true HF increment 3,001
estimator                      mean  HF increment    error
OLS on dollars                2,866         2,975    -0.9%
log-OLS, exp(xb)              1,738         1,764   -41.2%
log-OLS, smeared              2,862         2,905    -3.2%
log-OLS, smeared by HF        2,868         2,988    -0.4%
gamma GLM, log link           2,867         2,986    -0.5%
hf slope: log-OLS 0.784 (true 0.8, the log ratio of GEOMETRIC means)   gamma GLM 0.801 (true 0.800, the log ratio of MEANS)

=== Heteroscedastic errors (sd 1.0, 1.5 with HF)   true mean 3,575   true HF increment 7,732
estimator                      mean  HF increment    error
OLS on dollars                3,562         7,747     0.2%
log-OLS, exp(xb)              1,734         1,735   -77.6%
log-OLS, smeared              3,237         3,240   -58.1%
log-OLS, smeared by HF        3,570         7,807     1.0%
gamma GLM, log link           3,566         7,793     0.8%
hf slope: log-OLS 0.776 (true 0.8, the log ratio of GEOMETRIC means)   gamma GLM 1.437 (true 1.425, the log ratio of MEANS)
  • With constant variance, every estimator except the naive exp(xb) is within about 3% of the truth.
  • When the variance differs by heart failure, one smearing factor misses the increment by 58%: it reports $3,240 against the true $7,732. Smearing by group fixes it only because we know which group drives the variance.
  • The gamma GLM gets it right without being told. Its slope for heart failure is 1.437, not 0.8. It estimates the log ratio of means, which is 0.8 + (1.5² − 1²)/2 = 1.425 here. Log-OLS estimates the log ratio of geometric means. The two answer different questions, and only one of them is about money.
  • OLS on dollars is also unbiased for the mean. It is noisier, and it cannot give a ratio.

11.5 The gamma GLM: model the mean directly (40 min)

A generalized linear model with a log link models the mean itself:

log⁡E[yi∣xi]=xi′β⟹E[yi∣xi]=exp⁡(xi′β)\log E[y_i \mid x_i] = x_i'\beta \qquad\Longrightarrow\qquad E[y_i \mid x_i] = \exp(x_i'\beta)

There is no retransformation. $e^{\beta_k}$ is a ratio of means. The family (gamma, Poisson) only says how the variance grows with the mean. It affects efficiency, not consistency: if the mean is right, the estimates are consistent whatever the true distribution, and robust standard errors take care of inference.

def fit_glm(df, y, family="gamma", x=COVARIATES, offset=None):
    """GLM with a log link. family: 'gamma' or 'poisson' (Poisson here = quasi-likelihood: robust SEs,
    any non-negative y, no assumption that y is a count)."""
    fam = gamma_log() if family == "gamma" else sm.families.Poisson()
    return smf.glm(f"{y} ~ {x}", df, family=fam, offset=offset).fit(cov_type="HC1")
"""Day 11.4: a gamma GLM with a log link models the mean directly."""

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 fit_glm, recycled_difference  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
g = fit_glm(df, "fu_cost", "gamma")
ci = g.conf_int()
table = pd.DataFrame({"coef": g.params, "ratio of means": np.exp(g.params),
                      "95% CI low": np.exp(ci[0]), "95% CI high": np.exp(ci[1])})
print("Gamma GLM, log link, robust (HC1) standard errors")
print(table.drop("Intercept").round(3).to_string())
print(f"\nmean prediction {g.fittedvalues.mean():,.0f}  vs observed {df.fu_cost.mean():,.0f}")

print("\nIncremental cost in dollars (recycled predictions: everyone with, then everyone without)")
for var in ("heart_failure", "copd", "insulin", "qc"):
    m1, m0, d = recycled_difference(g.predict, df, var)
    print(f"  {var:<15} with {m1:>7,.0f}   without {m0:>7,.0f}   difference {d:>7,.0f}   ratio {m1 / m0:.3f}")
Gamma GLM, log link, robust (HC1) standard errors
                   coef  ratio of means  95% CI low  95% CI high
age10            -0.013           0.987       0.943        1.032
male             -0.011           0.989       0.919        1.065
qc               -0.127           0.881       0.814        0.953
heart_failure     0.708           2.030       1.858        2.218
copd              0.358           1.430       1.260        1.623
hypertension     -0.031           0.969       0.889        1.056
nephrology_visit  0.326           1.385       1.286        1.492
insulin           0.148           1.159       1.072        1.254
log_base          0.135           1.144       1.105        1.185

mean prediction 4,862  vs observed 4,841

Incremental cost in dollars (recycled predictions: everyone with, then everyone without)
  heart_failure   with   8,505   without   4,191   difference   4,315   ratio 2.030
  copd            with   6,769   without   4,734   difference   2,036   ratio 1.430
  insulin         with   5,405   without   4,661   difference     743   ratio 1.159
  qc              with   4,475   without   5,079   difference    -604   ratio 0.881

People with heart failure cost 2.03 times as much (95% CI 1.86 to 2.22), holding the other covariates fixed. In dollars, the average increment is $4,315 per person per year. Quebec residents cost 12% less than comparable Ontarians, about $600. The drug exercise below and Day 12 split that between drugs and hospital care. The mean prediction ($4,862) is within 0.5% of the observed mean, with no smearing.

Check it in R. The same model with glm(..., family = Gamma(link = "log")):

# Day 11: the same gamma GLM in R. The coefficients should match Python to 3 decimals.
suppressPackageStartupMessages({ library(DBI); library(duckdb) })
con <- dbConnect(duckdb(shared_home = FALSE))
df <- dbGetQuery(con, "SELECT * FROM read_parquet('m2/analysis.parquet') WHERE NOT died")
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))
fit <- glm(fu_cost ~ age10 + male + qc + heart_failure + copd + hypertension + nephrology_visit + insulin + log_base,
           family = Gamma(link = "log"), data = df)
cat(sprintf("%-22s %8s %10s\n", "term", "coef", "ratio"))
for (k in names(coef(fit))) cat(sprintf("%-22s %8.3f %10.3f\n", k, coef(fit)[k], exp(coef(fit)[k])))
cat(sprintf("\nmean prediction %s  vs observed %s\n", format(round(mean(fitted(fit))), big.mark = ","),
            format(round(mean(df$fu_cost)), big.mark = ",")))
term                       coef      ratio
(Intercept)               7.118   1233.881
age10                    -0.013      0.987
male                     -0.011      0.989
qc                       -0.127      0.881
heart_failureTRUE         0.708      2.030
copdTRUE                  0.358      1.430
hypertensionTRUE         -0.031      0.969
nephrology_visitTRUE      0.326      1.385
insulinTRUE               0.148      1.159
log_base                  0.135      1.144

mean prediction 4,862  vs observed 4,841

The coefficients agree to three decimals.

Try it (10 min). Model 2025 drug costs for survivors. Some people have none. Which family can you use? What is the Quebec–Ontario ratio, and the difference in dollars?

Solution
"""Day 11 try it: model 2025 drug costs (some are zero) and compare the provinces."""

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.costmodels import fit_glm, recycled_difference  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
print(f"people with no public drug cost in 2025: {(df.fu_drug == 0).sum()} ({(df.fu_drug == 0).mean():.1%})")
g = fit_glm(df, "fu_drug", "poisson")         # a Poisson (quasi-likelihood) GLM accepts zeros; a gamma GLM does not
lo, hi = np.exp(g.conf_int().loc["qc"])
print(f"QC vs ON ratio of mean drug cost: {np.exp(g.params['qc']):.3f} (95% CI {lo:.3f} to {hi:.3f})")
m1, m0, d = recycled_difference(g.predict, df, "qc")
print(f"everyone in QC {m1:,.0f}   everyone in ON {m0:,.0f}   difference {d:,.0f} per person")
people with no public drug cost in 2025: 156 (2.7%)
QC vs ON ratio of mean drug cost: 0.766 (95% CI 0.715 to 0.821)
everyone in QC 817   everyone in ON 1,067   difference -250 per person

A gamma GLM needs every $y > 0$; 156 people have a zero. A Poisson GLM with a log link (often called PPML, Poisson pseudo-maximum likelihood) needs only $y \ge 0$: it does not assume the outcome is a count, and with robust SEs it is a safe default for non-negative outcomes. Quebec's public plan pays 23% less per person than Ontario's for comparable people. That is RAMQ's deductible and coinsurance again (Day 1).

Why it matters at work: "Patients with heart failure cost $4,315 more per year" is a sentence a payer can put in a budget. "Heart failure raises log costs by 0.76" is not. Report ratios of means with dollar increments from recycled predictions.

Where you'll meet this: burden-of-illness studies · cost inputs for CDA-AMC and INESSS models · RWE cost comparisons between treatments (Module 3)


11.6 Which family? The modified Park test (20 min)

The family should match how the variance grows with the mean: $\text{Var}(y \mid x) \propto \mu^\lambda$. Manning and Mullahy's modified Park test estimates $\lambda$ by regressing the log squared residual on the log prediction:

log⁡(yi−μ^i)2=γ0+λlog⁡μ^i+ui\log (y_i - \hat\mu_i)^2 = \gamma_0 + \lambda \log \hat\mu_i + u_i
def park_test(y, mu):
    """Modified Park test: regress log((y - mu)^2) on log(mu). The slope says how the variance grows
    with the mean: about 0 Gaussian, 1 Poisson, 2 gamma, 3 inverse Gaussian."""
    r = np.log((np.asarray(y) - np.asarray(mu)) ** 2)
    fit = sm.OLS(r, sm.add_constant(np.log(np.asarray(mu)))).fit(cov_type="HC1")
    return float(fit.params[1]), float(fit.bse[1])
"""Day 11.5: the modified Park test - how does the variance grow with the mean?"""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
from corridor.costmodels import fit_glm, park_test  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
for family in ("gamma", "poisson"):
    g = fit_glm(df, "fu_cost", family)
    lam, se = park_test(df["fu_cost"], g.fittedvalues)
    print(f"start from a {family:<7} GLM: lambda = {lam:.2f}  (95% CI {lam - 1.96 * se:.2f} to {lam + 1.96 * se:.2f})")
print("lambda: 0 = Gaussian (constant variance), 1 = Poisson, 2 = gamma, 3 = inverse Gaussian")
start from a gamma   GLM: lambda = 1.27  (95% CI 1.14 to 1.39)
start from a poisson GLM: lambda = 1.30  (95% CI 1.17 to 1.42)
lambda: 0 = Gaussian (constant variance), 1 = Poisson, 2 = gamma, 3 = inverse Gaussian

$\lambda \approx 1.3$, with a confidence interval that excludes 2. The variance grows more slowly than the gamma family assumes, closer to Poisson. That is the two-hump mixture again. Both families give consistent means, so the choice matters for efficiency only, and the next section shows how little.


11.7 A budget from exp(log cost) (15 min)

Bug of the day. An analyst fits OLS to log costs (it looks great: symmetric residuals, a higher R²), predicts each person's log cost, exponentiates and adds up:

"""Day 11 bug of the day: a budget built from exp(predicted log cost)."""

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.costmodels import fit_glm, fit_log_ols  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
lm = fit_log_ols(df, "fu_cost")
budget_bug = np.exp(lm.predict(df)).sum()                 # the bug: back-transform without smearing
g = fit_glm(df, "fu_cost", "gamma")
print(f"Actual 2025 spending on these {len(df):,} people: ${df.fu_cost.sum() / 1e6:,.1f} M")
print(f"Budget from exp(log-OLS prediction):            ${budget_bug / 1e6:,.1f} M  "
      f"({100 * (budget_bug / df.fu_cost.sum() - 1):+.0f}%)")
print(f"Budget from the gamma GLM:                      ${g.fittedvalues.sum() / 1e6:,.1f} M  "
      f"({100 * (g.fittedvalues.sum() / df.fu_cost.sum() - 1):+.1f}%)")
Actual 2025 spending on these 5,792 people: $28.0 M
Budget from exp(log-OLS prediction):            $14.5 M  (-48%)
Budget from the gamma GLM:                      $28.2 M  (+0.4%)

The budget is short by 48%: $14.5 M against $28.0 M. Nothing errors and the regression output looks textbook. Never exponentiate a log-scale prediction and call it a mean. Use a GLM with a log link, or smear and check the result against the observed mean.


11.8 Mini-project: which model predicts best? (40 min)

Compare five models out of sample. Ten-fold cross-validation fits each model on nine tenths of the people and predicts the tenth it has not seen. Report the root mean squared error (RMSE), the mean absolute error (MAE), the mean error (bias), and the worst gap between mean predicted and mean observed cost across the ten deciles of prediction (calibration).

"""Day 11 mini-project: which cost model predicts best out of sample? Ten-fold cross-validation."""

import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
import matplotlib  # noqa: E402

matplotlib.use("Agg")
import matplotlib.pyplot as plt  # noqa: E402
import numpy as np  # noqa: E402
import pandas as pd  # noqa: E402

from corridor.costmodels import (fit_glm, fit_log_ols, fit_ols, kfold_ids, predict_log_ols,  # noqa: E402
                                 smearing_factor)
from corridor.db import ROOT  # noqa: E402
from corridor.m2 import load  # noqa: E402

df = load(survivors=True)
y = "fu_cost"

def log_smeared(train, test):
    lm = fit_log_ols(train, y)
    return predict_log_ols(lm, test, smearing_factor(lm))

def log_smeared_hf(train, test):
    lm = fit_log_ols(train, y)
    return predict_log_ols(lm, test, smearing_factor(lm, train["heart_failure"]), test["heart_failure"])

MODELS = {
    "OLS": lambda tr, te: fit_ols(tr, y).predict(te),
    "log-OLS + smearing": log_smeared,
    "log-OLS + smearing by HF": log_smeared_hf,
    "gamma GLM": lambda tr, te: fit_glm(tr, y, "gamma").predict(te),
    "Poisson GLM": lambda tr, te: fit_glm(tr, y, "poisson").predict(te),
}

fold = kfold_ids(len(df))
pred = pd.DataFrame(index=df.index, columns=list(MODELS), dtype=float)
for k in range(10):
    train, test = df[fold != k], df[fold == k]
    for name, f in MODELS.items():
        pred.loc[test.index, name] = np.asarray(f(train, test))

rows = []
for name in MODELS:
    e = df[y] - pred[name]
    dec = np.ceil(pred[name].rank(pct=True) * 10).astype(int)
    calib = (df[y].groupby(dec).mean() - pred[name].groupby(dec).mean()).abs().max()
    rows.append({"model": name, "RMSE": np.sqrt((e**2).mean()), "MAE": e.abs().mean(),
                 "mean error": e.mean(), "worst decile gap": calib})
print("Out-of-sample (10-fold) prediction of 2025 cost per survivor, dollars")
print(pd.DataFrame(rows).round(0).to_string(index=False))

fig, ax = plt.subplots(figsize=(5.2, 4.2))
for name, colour in (("log-OLS + smearing", "#e5484d"), ("gamma GLM", "#4f9cf9")):
    dec = np.ceil(pred[name].rank(pct=True) * 10).astype(int)
    ax.plot(pred[name].groupby(dec).mean() / 1000, df[y].groupby(dec).mean() / 1000, "o-", color=colour, label=name)
lim = [0, 16]
ax.plot(lim, lim, color="#888", lw=1, ls="--")
ax.set(xlabel="mean predicted ($ thousands)", ylabel="mean observed ($ thousands)", xlim=lim, ylim=lim,
       title="Calibration by decile of prediction")
ax.legend()
fig.tight_layout()
fig.savefig(os.path.join(ROOT, "figures", "day11_calibration.png"), dpi=130)
Out-of-sample (10-fold) prediction of 2025 cost per survivor, dollars
                   model   RMSE    MAE  mean error  worst decile gap
                     OLS 6572.0 4540.0        -1.0             522.0
      log-OLS + smearing 6704.0 4650.0      -284.0            3008.0
log-OLS + smearing by HF 6672.0 4634.0      -218.0            2323.0
               gamma GLM 6581.0 4558.0       -23.0            1090.0
             Poisson GLM 6578.0 4564.0        -2.0            1012.0

Calibration by decile of prediction

How to read it:

  • RMSE barely separates the models. OLS is best ($6,572), the GLMs are within $10, log-OLS is $100–$130 worse. With R² around 0.10, most of the variation in one person's cost is unpredictable from these covariates.
  • Bias and calibration separate them clearly. Both log-OLS versions over-predict on average (by $218–$284 out of sample; the mean error is observed minus predicted) and over-predict the top decile by $2,300–$3,000. The GLMs are unbiased and their worst decile is off by about $1,000.
  • Choose by the question. For a mean difference in a large sample, OLS with robust SEs is fine. For ratios, predictions for subgroups, or anything that must stay positive, use a log-link GLM. Log-OLS is the one to avoid when the answer is in dollars.

Write two sentences for your notes: which model you would use for the Renavex budget impact cost inputs, and why.

11.9 Save your work

python -m pytest -q
git add .
git commit -m "Day 11: analysis file, log-OLS and smearing, gamma GLMs, model choice"

Day 11 checklist

  • python day11/build_analysis_file.py builds m2/analysis.parquet, and git ignores it
  • I can explain why exp(predicted log cost) is not the mean, and correct it with smearing
  • I fit a gamma GLM with a log link and report ratios of means and dollar increments
  • I can run and read a modified Park test
  • I compare cost models out of sample on bias and calibration, not only RMSE