---
title: "Week 10 seminar"
author: "Joshua Loftus"
format:
  html:
    toc: true
    embed-resources: false
execute:
  echo: true
  warning: false
  message: false
  error: false
---

::: {.callout-note}
This is the student version of the notebook. The code you write goes where a line says `# ...` or has a `____`. A code chunk with a blank starts with `#| eval: false`, so the file renders as it stands; delete that line once you have filled the blank. Working through the chunks one at a time in RStudio (Ctrl/Cmd+Enter) is unaffected. Answers are revealed in the seminar.
:::

```{r}
#| label: setup
library(tidyverse)   # should've already install.packages("tidyverse")
library(xgboost)     # coding part 1; version 3 or later
library(ggdag)       # drawing DAGs; might need to install.packages("ggdag")
library(patchwork)   # two plots side by side
theme_set(theme_minimal())
brier <- function(y, p) mean((y - p)^2)
pct <- function(v) sprintf("%.0f%%", 100 * v)
```

## Before the seminar

<!-- At home, before the seminar. -->

Exercise 1 is the derivation from the lecture with the slides closed; exercises 2 and 3 apply the label-shift identity and Hoeffding's inequality with numbers. Do all three on paper before the seminar.

::: {.callout-warning title="Hints"}
Each exercise has hints, collapsed below it. Do not open a hint unless you have been stuck for at least a few minutes, and open them in order. Solutions are shown in the seminar if you ask.
:::

**Exercise 1 (the covariate-shift identity).** A model $f$ has been fitted and is now fixed. Under training, $(X, Y)$ has density $p_{\text{train}}(x, y)$; where the model will be used, $p_{\text{test}}(x, y)$. The risks are $R_{\text{train}}(f) = \mathbb E_{\text{train}}[\ell(Y, f(X))]$ and $R_{\text{test}}(f) = \mathbb E_{\text{test}}[\ell(Y, f(X))]$. Assume $p_{\text{test}}(y \mid x) = p_{\text{train}}(y \mid x)$ for every $x$, and $p_{\text{train}}(x) > 0$ wherever $p_{\text{test}}(x) > 0$.

(a) With the slides closed, show that $R_{\text{test}}(f) = \mathbb E_{\text{train}}\big[w(X)\,\ell(Y, f(X))\big]$, where $w(x) = p_{\text{test}}(x)/p_{\text{train}}(x)$. Say which assumption each step uses.

(b) A model was trained and tuned on patients aged 18 to 64, with age among its inputs, and is to be used on patients aged 65 and over. Which step of (a) fails? Could any reweighting of the tuning rows estimate its risk on the new patients? What could?

::: {.callout-note collapse="true" title="Hint 1"}
(a) Write $r(x) = \mathbb E[\ell(Y, f(X)) \mid X = x]$. Which assumption makes $r$ the same under training and under deployment?
:::

::: {.callout-note collapse="true" title="Hint 2"}
(a) Write $R_{\text{test}}(f) = \int r(x)\,p_{\text{test}}(x)\,dx$. What happens if you multiply and divide by $p_{\text{train}}(x)$, and where is that allowed?
:::

**Exercise 2 (label shift, with numbers).** A score is calibrated for a condition where 20% of patients have it: $s(x) = P_{\text{train}}(Y = 1 \mid X = x)$. It is to be used in a clinic where 2% of patients have it. How patients with and without the condition present, $p(x \mid y)$, is the same in both places.

(a) For a patient with $s(x) = 0.5$, what is the probability that they have the condition, in the clinic?

(b) Missing a case costs 9 times as much as a false alarm. What is the optimal threshold on the clinic's probability? What threshold on the old score $s(x)$ gives the same decisions?

(c) Does ranking the clinic's patients by $s(x)$ give the same order as ranking them by the correct clinic probability?

::: {.callout-note collapse="true" title="Hint 1"}
(a) By Bayes' rule, the odds $P(Y = 1 \mid X = x)/P(Y = 0 \mid X = x)$ are $\frac{p(x \mid 1)}{p(x \mid 0)} \cdot \frac{q}{1 - q}$, with $q = P(Y = 1)$. Which factor changes?
:::

::: {.callout-note collapse="true" title="Hint 2"}
(b) Did the costs change? The optimal threshold theorem gives a threshold from the costs alone: a threshold on which probability?
:::

**Exercise 3 (how many rows?).** Losses are between 0 and 1. Hoeffding's inequality with the union bound says: for $K$ models fixed before $m$ independent held-out rows are drawn, with probability at least $1 - \delta$ every score is within $t_K = \sqrt{\log(2K/\delta)/(2m)}$ of its risk.

(a) How many held-out rows are needed so that 6 models are all within 0.01 of their risks, with probability at least 0.95? And 600 models?

(b) After looking at the six scores, an analyst designs a seventh model and scores it on the same rows. Why does the guarantee in (a) not cover the seventh model, even though the union bound needs no independence between the scores? What would?

::: {.callout-note collapse="true" title="Hint 1"}
(a) Solve $t_K \le 0.01$ for $m$.
:::

::: {.callout-note collapse="true" title="Hint 2"}
(b) The union bound adds up one bound per model. What does Hoeffding's inequality need, for one model, about the model and the rows?
:::

## Problems

<!-- In the room, about 50 minutes. Minutes for each problem are in its own comment. Hints are revealed in order after a few minutes, the answer last. Each answer is written to stand alone. -->

Most of these problems ask which idea from the course applies, and why. A good answer names the idea and gives the reason in a sentence or two; a short calculation helps where one is asked for.

**Problem 1 (find the problems in this report).** <!-- About 16 min: 8 in groups, 8 together. --> A hospital trust wants to phone patients after discharge if a model predicts they are at high risk of being readmitted within 30 days. Below is an invented evaluation report for such a model. The analysts had 20,000 past discharges, one per patient, and 400 candidate inputs.

> 1. We split the 20,000 discharges at random into training (12,000), tuning (4,000), and test (4,000) rows.
> 2. We dropped the inputs with more than 30% missing values. Of those left, we kept the 40 with the largest absolute correlation with readmission, computed on all 20,000 discharges so that the correlations would be as precise as possible.
> 3. We standardized each input using the mean and standard deviation of the training rows, and applied the same transformation to the tuning and test rows.
> 4. About 20% of discharges were followed by a readmission. A model that predicts no readmission for everyone would have accuracy 0.80, so we compared models by their Brier score, not their accuracy.
> 5. We tuned boosted trees over 200 configurations (depth 2 to 6, learning rates from 0.01 to 0.3, 100 to 2,000 rounds), fitting each on the training rows. The best had a tuning Brier score of 0.142, which we report as the model's expected Brier score on new discharges.
> 6. The lasso, with its penalty chosen by 10-fold cross-validation on the training rows, scored 0.145 on the same tuning rows, so boosted trees are the better model.
> 7. We refit the chosen configuration on the training and tuning rows together and scored it once on the test rows: a Brier score of 0.149, with a standard error of 0.004 (the standard deviation of the 4,000 losses divided by $\sqrt{4000}$).
> 8. To turn probabilities into decisions, we compared thresholds from 0.05 to 0.95 in steps of 0.01 and kept 0.46, which gave the highest accuracy, 0.81, on the 4,000 test discharges.
> 9. We grouped the test discharges into tenths by predicted probability. In each group, the readmission rate was within 0.03 of the group's mean prediction.
> 10. The trust's second hospital, whose patients are on average seven years older, uses the same records system, so every input is available there. Since the model is calibrated on the test rows, its probabilities will be right there too.
> 11. The partial dependence plot for the number of follow-up calls a patient received after earlier discharges slopes down: each extra call lowers the model's predicted probability of readmission by about 2 percentage points, so the phone program will work.
> 12. The lasso kept 12 of the 40 inputs, and kept the same 12 in 9 of the 10 cross-validation folds. These are the causes of readmission, and the trust should target them.
> 13. In use, the model will flag patients whose predicted probability is above 0.5. A readmission costs the trust about five times as much as a phone call.

For each line with a problem, name the idea from the course that it breaks, and say what you would do instead. Some lines have no problem: which, and why are they fine? Finally, which of the problems could a fresh test set fix, and which need evidence about what the calls do?

**Problem 2 (shift in a graph).** <!-- About 10 min. --> A firm that runs vehicle inspections predicts whether a car will fail its annual safety inspection. The DAG below is about the whole population of cars brought for inspection. $S$ records which sample a car is in: the training rows, the test rows, or a new region the firm is moving into. A car's age $A$ affects its mileage $M$ and whether it fails, $Y$, and mileage affects $Y$. The training and test rows are a random split of the firm's records from its first region; the cars in the new region are older.

```{r}
#| label: dag-cars
#| echo: false
#| fig-width: 6
#| fig-height: 2.6
dag_cars <- dagify(Y ~ A + M, M ~ A, A ~ S,
                   coords = list(x = c(S = 0, A = 1, M = 2, Y = 3), y = c(S = 0, A = 0, M = 0.8, Y = 0)))
ggdag(dag_cars, node_size = 14, text_size = 5) + theme_dag() + scale_x_continuous(expand = expansion(mult = 0.15)) + scale_y_continuous(expand = expansion(mult = 0.25))
```

::: {.callout-note title="Reminder: reading independence off a DAG"}
Read the DAG as a structural model: each variable is a function of its parents and its own noise, with all the noises independent. Two variables can be dependent only through a path between them, with the arrows along it pointing either way. Given the variables you condition on, a path is **blocked** if somewhere along it there is

- a chain $U \to V \to W$ or a fork $U \leftarrow V \to W$ whose middle variable $V$ is conditioned on, or
- a collider $U \to V \leftarrow W$ whose middle variable $V$ is not conditioned on, and neither is any descendant of $V$.

If every path between two variables (or two sets of variables) is blocked, they are independent given what you conditioned on, in every distribution the structural model can produce. If some path is open, the graph allows them to be dependent, and they usually are. A selection variable such as $S$ is read like any other: $p(y \mid x)$ is the same in every sample when $Y$ and $S$ are independent given $X$.
:::

(a) The only arrow out of $S$ goes into $A$. What does it say? Does it say that the training and test rows differ in age? What would an arrow $S \to Y$ mean?

(b) Model 1 uses both $A$ and $M$ as inputs. Explain why the new region is covariate shift for this model: why is $p(y \mid a, m)$ the same for all three values of $S$?

(c) Model 2 uses only $M$. Is the new region covariate shift for this model? What goes wrong if you reweight its test rows by $w(m) = p_{\text{new}}(m)/p_{\text{train}}(m)$? Can you still estimate Model 2's risk in the new region from the test rows, and with which weights?

(d) In the lecture, two shifted populations were made from the patients kept back: the sicker one by keeping each patient with a probability that rose with last year's chronic conditions, and the other by keeping every high-cost patient and a third of the others. Write $K$ for "kept", $X$ for last year's inputs, and $Y$ for high cost. The two DAGs below add $K$. For each, which conditional distribution is the same for the kept patients as for all patients, why does the graph say so, and so which kind of shift is it?

```{r}
#| label: dag-kept
#| echo: false
#| fig-width: 7
#| fig-height: 2.2
co <- list(x = c(X = 0, Y = 2, K = 1), y = c(X = 0, Y = 0, K = -0.8))
d1 <- ggdag(dagify(Y ~ X, K ~ X, coords = co), node_size = 12, text_size = 5) + theme_dag() + scale_x_continuous(expand = expansion(mult = 0.15)) + scale_y_continuous(expand = expansion(mult = 0.25)) + ggtitle("The sicker population")
d2 <- ggdag(dagify(Y ~ X, K ~ Y, coords = co), node_size = 12, text_size = 5) + theme_dag() + scale_x_continuous(expand = expansion(mult = 0.15)) + scale_y_continuous(expand = expansion(mult = 0.25)) + ggtitle("High cost twice as common")
d1 + d2
```

**Problem 3 (explain the result).** <!-- About 8 min. --> Each result below is what an idea from the course predicts. Name the idea, and explain the result in two or three sentences.

(a) A regression has 5 informative inputs. Adding 30 inputs that are pure noise makes 10-nearest neighbors' test error much worse, and barely changes the lasso's.

(b) Regressing house price on the number of bedrooms gives a positive coefficient. With floor area added as a second input, the coefficient on bedrooms is negative.

(c) While a model is trained by gradient descent, the training loss keeps falling, but the tuning loss falls until iteration 300 and then rises.

(d) For every model on a leaderboard, the training error is below the test error, and the gap is larger for a deep tree than for linear regression.

(e) A random forest with 5,000 trees scores the same as one with 500 trees. Lowering the number of inputs considered at each split (`mtry`) made it better.

**Problem 4 (which shift?).** <!-- About 8 min. --> A readmission model was trained on one hospital's 2025 discharges. For each change below, say which kind of shift it is (covariate shift, label shift, or another change in $p(y \mid x)$), what happens to the model's calibration and ranking, and what you would need to estimate its risk after the change.

(a) It is used at a second hospital, whose patients are older and have more chronic conditions; how treatment and discharge work is the same, and age and conditions are among the inputs.

(b) In flu season, readmissions are three times as common; the patients who are readmitted look like those readmitted before, and so do those who are not.

(c) A new follow-up clinic for heart failure patients lowers their readmissions, by an amount that varies between patients and is not yet known.

(d) The trust starts phoning the patients the model flags, and the calls work. Next year the model is retrained on that year's discharges.

(e) For (a), the reweighted tuning score has an effective sample size $(\sum_j w_j)^2/\sum_j w_j^2$ of 310, from 8,000 tuning rows. What does that tell you, and what would you do?

**Problem 5 (should this be predicted at all?).** <!-- About 8 min: groups take one task each, 4 minutes, then report. --> For each task below: which of the four MARA(s) conditions (measurement, adaptability, resilience, agnosis) is most in doubt, and for which stakeholders? Name one of Wang et al.'s objections that applies. Would a model with a better score make the decision better?

1. Which patients will cost the most next year, to offer them extra care.
2. Which defendants will be re-arrested before trial, to decide who is released.
3. Which job applicants will stay for two years, to decide who is hired.
4. Which drivers will make an insurance claim, to set the price they pay.

## Coding

<!-- In the room, about 10 minutes: part 1. Skeleton lines in comments are scaffolds: the statistical operation is what you write. -->

### 1. Another target

The lecture's competition asked which model best predicts whether a patient's cost next year is in the top quarter. Here the same learner, with the same settings and the same inputs, is trained on another target, and we compare who would be offered extra care. The data are the synthetic patient-years from the lecture ([data note](https://ml4ds.com/data/obermeyer.html)), split as in the lecture.

```{r}
#| label: data
hs <- read_csv("https://gitlab.com/labsysmed/dissecting-bias/-/raw/master/data/data_new.csv", show_col_types = FALSE)
outcomes_t <- c("risk_score_t", "program_enrolled_t", "gagne_sum_t", "cost_t", "cost_avoidable_t",
                "bps_mean_t", "ghba1c_mean_t", "hct_mean_t", "cre_mean_t", "ldl_mean_t")
inputs <- setdiff(names(hs), c(outcomes_t, "race"))   # the year before, without race
X <- as.matrix(hs[inputs])
set.seed(310)   # change this number: a different split, and different numbers below
id <- sample(nrow(hs))
i_train <- id[1:16000]; i_test <- id[24001:36000]   # the lecture's training and test rows
high <- as.numeric(hs$cost_t > quantile(hs$cost_t[i_train], 0.75))   # top quarter of next year's cost
test <- hs[i_test, ]
boost <- function(target, objective) xgboost(x = X[i_train, ], y = target, objective = objective,
  max_depth = 4, learning_rate = 0.05, nrounds = 400, nthread = 2)
fit_cost <- boost(factor(high[i_train]), "binary:logistic")   # the competition's winner
```

**Question 1.** Train the same learner to predict the number of active chronic conditions next year (`gagne_sum_t`), with the objective `"reg:squarederror"`. Write `top3()`, which marks the 3% of test patients with the highest scores. Then compare the two targets: how many of those marked are Black, their mean number of chronic conditions next year, and their share of all next-year cost among the test patients. How many patients are on both lists?

```{r}
#| eval: false
# fit_cond <- boost(____, "reg:squarederror")
# top3 <- function(score) ____    # TRUE for the 3% with the highest scores
```

```{r}
#| label: compare-targets
#| eval: !expr exists("fit_cond") && exists("top3")
scores <- list(`top-quarter cost` = predict(fit_cost, X[i_test, ]),
               `chronic conditions` = predict(fit_cond, X[i_test, ]))
compare <- imap_dfr(scores, function(s, target) {
  f <- top3(s)
  tibble(target, marked = sum(f), black = sum(test$race[f] == "black"),
         conditions = mean(test$gagne_sum_t[f]), share_of_cost = sum(test$cost_t[f]) / sum(test$cost_t))
})
compare
on_both <- sum(top3(scores[[1]]) & top3(scores[[2]]))
on_both
```

Checkpoint: each target marks the same number of patients.

```{r}
#| eval: !expr exists("compare")
stopifnot(all(compare$marked == round(0.03 * nrow(test))))
```

**Question 2.** Suppose a competitor beats boosted trees on the top-quarter cost leaderboard by a clear margin, on fresh test rows. Would that change the comparison in question 1? We can see who gets selected; what evidence would tell us who *benefits* from the program?

### 2. Shift by simulation

Complete this part after the seminar.

In a simulation we know $p(y \mid x)$ and can draw outcomes in the population where a model will be used, so each method can be checked against the truth. In questions 3 to 6, $P(Y = 1 \mid x)$ is the same curve and only the distribution of the inputs changes; in question 7 the share of each class changes, and with it $P(Y = 1 \mid x)$.

```{r}
#| label: sim-setup
p_true <- function(x) plogis(-1 + 1.5 * x - 0.5 * x^2)   # P(Y = 1 | x); the same in questions 3 to 6
draw <- function(n, mu) {                                 # inputs centered at mu
  x <- rnorm(n, mean = mu)
  tibble(x = x, y = rbinom(n, 1, p_true(x)))
}
sim_train <- draw(4000, mu = 0)
sim_tune <- draw(4000, mu = 0)
sim_new <- draw(4000, mu = 1.5)   # with outcomes, which only a simulation gives us
risk <- function(fit, mu) {                                # the true risk (Brier score) of a fitted model
  integrate(function(x) {                                  # in the population with inputs centered at mu
    p <- p_true(x)
    f <- predict(fit, data.frame(x = x), type = "response")
    (p * (1 - p) + (p - f)^2) * dnorm(x, mean = mu)
  }, -Inf, Inf)$value
}
```

**Question 3.** Fit a logistic regression with a straight line in `x` on `sim_train` (no $x^2$ term, so it is misspecified). Compute its Brier score on `sim_tune` and on `sim_new`. Why does its risk change, when $p(y \mid x)$ did not?

```{r}
#| eval: false
# fit_lin <- ____
# p_tune <- predict(fit_lin, sim_tune, type = "response")
# p_new <- predict(fit_lin, sim_new, type = "response")
# c(tune = brier(sim_tune$y, p_tune), new = brier(sim_new$y, p_new))
```

**Question 4.** Estimate the new population's score from the tuning rows alone, with the true weights $w(x) = p_{\text{new}}(x)/p_{\text{train}}(x)$, here the ratio of two normal densities. Compute the effective sample size $(\sum_j w_j)^2/\sum_j w_j^2$.

```{r}
#| eval: false
# loss_tune <- (sim_tune$y - p_tune)^2
# w <- ____
# c(reweighted = mean(w * loss_tune), truth = risk(fit_lin, 1.5), ess = ____)
```

**Question 5.** In practice $w$ is unknown. We have the new population's inputs, without outcomes. How could a classifier that tells tuning inputs from new inputs give an estimate of $w(x)$? Estimate $w$ this way, with a logistic regression on `x` and the inputs of `sim_new` (not its outcomes), and compare the reweighted score with question 4. Why is a logistic regression on `x` a good classifier here?

::: {.callout-note collapse="true" title="Hint"}
Pool the tuning inputs (label 0) with the new inputs (label 1) and fit the classifier. By Bayes' rule, with two samples of the same size, what are the odds $P(\text{new} \mid x)/P(\text{tuning} \mid x)$?
:::

```{r}
#| eval: false
# pool <- tibble(x = c(sim_tune$x, sim_new$x), new = rep(0:1, each = 4000))
# fit_w <- ____
# p_w <- predict(fit_w, sim_tune, type = "response")
# w_hat <- ____
# mean(w_hat * loss_tune)
```

**Question 6.** Now make overlap weaker. For $\mu$ = 0.5, 1, 1.5, 2, and 3, repeat 100 times: draw new tuning rows, compute the true-weight estimate, the true risk with `risk()`, and the effective sample size. Summarize the error of the estimate (its mean and standard deviation) and the median effective sample size. What happens as $\mu$ grows?

```{r}
#| eval: false
# one_run <- function(mu) {
#   tune <- draw(4000, mu = 0)
#   loss <- (tune$y - predict(fit_lin, tune, type = "response"))^2
#   w <- ____
#   tibble(mu, estimate = mean(w * loss), truth = risk(fit_lin, mu),
#          ess = ____)
# }
# runs <- map_dfr(rep(c(0.5, 1, 1.5, 2, 3), each = 100), one_run)
# runs |> group_by(mu) |> summarise(bias = mean(estimate - truth), sd = sd(estimate - truth), ess = median(ess))
```

**Question 7.** Label shift. Fit a logistic regression with `x` and `x^2` on `sim_train` (correctly specified, so calibrated in the training distribution). Make a label-shifted population: from 12,000 new rows with $\mu = 0$, keep every row with `y == 1` and each other row with probability $\frac13$. Explain why this triples the odds of `y == 1` at every $x$, and use that alone, before looking at the shifted outcomes, to correct the predictions. Then use the shifted rows' outcomes to check: compare the mean prediction, before and after the correction, with the share of `y == 1`; compare the predicted and observed shares within five bins of the corrected prediction; and compare the AUC with the AUC on `sim_tune`.

::: {.callout-note collapse="true" title="Hint"}
By Bayes' rule, what is $P(Y = 1 \mid x, \text{kept})$, in terms of $p(x) = P(Y = 1 \mid x)$ and the two keeping probabilities? What are its odds?
:::

```{r}
auc <- function(p, y) {   # the probability that a random 1 is scored above a random 0
  r <- rank(p); n1 <- sum(y); n0 <- length(y) - n1
  (sum(r[y == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}
```

```{r}
#| eval: false
# fit_q <- glm(y ~ x + I(x^2), family = binomial, data = sim_train)
# big <- draw(12000, mu = 0)
# sim_lab <- big[big$y == 1 | rbinom(12000, 1, 1/3) == 1, ]
# p_lab <- predict(fit_q, sim_lab, type = "response")
# p_fixed <- ____    # move every log-odds by the amount the selection implies
# q_train <- mean(sim_train$y); q_test <- mean(sim_lab$y)   # the check starts here
# c(share = q_test, mean_pred = mean(p_lab), mean_fixed = mean(p_fixed),
#   auc_tune = auc(predict(fit_q, sim_tune, type = "response"), sim_tune$y), auc_shifted = auc(p_lab, sim_lab$y))
# calib <- ____    # predicted and observed share of y == 1 in five bins of p_fixed
```

## References

- Kiviat, B. (2019). The moral limits of predictive practices: the case of credit-based insurance scores. *American Sociological Review* 84(6), 1134--1158. [doi:10.1177/0003122419884917](https://doi.org/10.1177/0003122419884917)
- Obermeyer, Z., Powers, B., Vogeli, C. and Mullainathan, S. (2019). Dissecting racial bias in an algorithm used to manage the health of populations. *Science* 366(6464), 447--453. [doi:10.1126/science.aax2342](https://doi.org/10.1126/science.aax2342)
- Rodu, J. and Baiocchi, M. (2023). When black box algorithms are (not) appropriate: a principled prediction-problem ontology. *Observational Studies* 9(2), 79--101. [doi:10.1353/obs.2023.0018](https://doi.org/10.1353/obs.2023.0018)
- Wang, A., Kapoor, S., Barocas, S. and Narayanan, A. (2024). Against predictive optimization: on the legitimacy of decision-making algorithms that optimize predictive accuracy. *ACM Journal on Responsible Computing* 1(1), 1--45. [doi:10.1145/3636509](https://doi.org/10.1145/3636509)
