::: {.callout-important}
## Instructions

Submit your solutions via [Gradescope](https://www.gradescope.com/courses/946202). In-person submissions will not be entertained. Please upload a single PDF file. Late submissions will not be accepted: anything submitted after 11:59 PM (IST), Sunday 22 November, 2026 will not be graded. You can raise your questions related to the assignment on [Piazza](https://piazza.com/iit_bombay/fall2026/dh801) - please tag these as `assignment_02`.

- The questions are in the assignment PDF; this file has only the code and answer spaces.
- Your final submission has to be the PDF that comes from this template - one single pdf. No Exceptions.
- Please mention the name(s) of people, including your LLM friends, with whom you collaborated and what exactly you discussed.
- **LLM prompts are required.** If you used an LLM (ChatGPT, Claude, Gemini, Copilot, ...) for any question, paste the exact prompt(s) you used under that question's answer. Unattributed LLM use, or LLM use without the prompts, will be graded zero.
- There are no partial marks for coding questions. For theory questions, show your reasoning; a bare final answer gets no credit. For interpretation questions, the reasoning is what earns the marks; a number without an interpretation gets no credit.
- Wherever a question says **"by hand"**, you may use R as a calculator (`sum`, `choose`, `pchisq`, `solve`, matrix algebra, ...) but not the test/model function being asked about (`fisher.test`, `chisq.test`, `prop.test`, `anova`, `glm`, `car::vif`, ...). Use those functions only to check your answer.
- Simulations: keep the `set.seed()` calls that are given, so that your numbers are reproducible.

**Making your submission:** Open this template in RStudio (you will need Quarto installed). Once you are done with your answers, use the "Render" button to create a pdf. You can also use Python or any other language, but there is no template; if you do, your submission must include both the code and the pdf.
:::

```{r}
#| echo: false
#| message: false
# !! DO NOT EDIT/REMOVE !!

required.packages <- c("tidyverse", "ggpubr", "patchwork",
                       "MASS", "AER", "car",
                       "glmnet", "vcd", "spls")

InstallMissing <- function(packages) {
  for (pkg in packages) {
    if (!require(pkg, character.only = TRUE)) {
      install.packages(pkg, dependencies = TRUE, repos = "https://cloud.r-project.org")
      library(pkg, character.only = TRUE)
    }
  }
}

InstallMissing(required.packages)

library(tidyverse)
library(patchwork)
library(ggpubr)
library(MASS)
library(glmnet)
select <- dplyr::select  
theme_set(theme_pubr())
```

# Problem 01: Me, the second opinion [18 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
ms4 <- vcd::MSPatients[, , "Winnipeg"]
ms <- matrix(c(sum(ms4[1:2, 1:2]), sum(ms4[3:4, 1:2]), sum(ms4[1:2, 3:4]), sum(ms4[3:4, 3:4])), 2,
             dimnames = list(`New Orleans` = c("MS", "not MS"), Winnipeg = c("MS", "not MS")))
ms
```

## 1a. Do they call MS equally often? [9 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 1b. Do they agree? [9 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

# Problem 02: Me, the shrink [24 points + 7 bonus]

```{r}
# !! DO NOT EDIT/REMOVE !!
prostate <- read.table("https://hastie.su.domains/ElemStatLearn/datasets/prostate.data",
                       header = TRUE)
train <- subset(prostate, train)[, 1:9]
test <- subset(prostate, !train)[, 1:9]
test_mse <- function(pred) mean((test$lpsa - pred)^2)
```

## 2a. Variance inflation by hand [7 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 2b. Greedy search [9 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 2c. Selection makes p-values lie [8 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
set.seed(808)
```

```{r}
# YOUR CODE HERE
```

**Answer:**

## 2d. Bonus: soft thresholding [7 bonus points]

```{r}
# !! DO NOT EDIT/REMOVE !!
set.seed(42)
n <- 100
X <- scale(matrix(rnorm(n * 4), n), scale = FALSE)
X <- qr.Q(qr(X)) * sqrt(n)
y <- drop(X %*% c(1.5, 0.6, 0.2, 0)) + rnorm(n, 0, 0.5)
y <- y - mean(y)
```

```{r}
# YOUR CODE HERE
```

**Answer:**

# Choosing a penalty: ridge, lasso or elastic net?

```{r}
#| echo: false
#| message: false
# !! DO NOT EDIT/REMOVE !!
# Every split, fold and simulated outcome is seeded here, so your numbers should match the key.
pd <- new.env()   # keeps Problem 02's `prostate` intact
data("prostate", package = "spls", envir = pd)

markers  <- pd$prostate$x             # 102 x 6033
colnames(markers) <- paste0("g", seq_len(ncol(markers)))
tumour <- pd$prostate$y             # 1 = tumour, 0 = normal

# Split b: one third held out (within each stratum), and 10 CV folds for the rest
make_split <- function(b, n, strata = rep(1, n)) {
  set.seed(801 + b)
  test <- unlist(lapply(split(seq_len(n), strata),
                        function(i) sample(i, round(length(i) / 3))))
  list(test = unname(test), foldid = sample(rep(1:10, length.out = n - length(test))))
}
# !! DO NOT EDIT/REMOVE !!

test_r2 <- function(pred, y) 1 - mean((y - pred)^2) / var(y)
# !! DO NOT EDIT/REMOVE !!

auc <- function(p, y) {
  r <- rank(p); n1 <- sum(y == 1); n0 <- sum(y == 0)
  (sum(r[y == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}
# !! DO NOT EDIT/REMOVE !!

# Mean overlap between all pairs of marker lists: 1 = always the same list, 0 = no overlap
jaccard <- function(lists) {
  pairs <- combn(length(lists), 2)
  mean(apply(pairs, 2, function(p) {
    a <- lists[[p[1]]]; b <- lists[[p[2]]]
    length(intersect(a, b)) / max(length(union(a, b)), 1)
  }))
}

# Problem 04: the real values of the 1000 most variable markers, with an outcome we invent
X_sim <- scale(markers[, order(apply(markers, 2, var), decreasing = TRUE)[1:1000]])
set.seed(801)
hub   <- sample(1000, 1)
block <- order(-abs(cor(X_sim[, hub], X_sim)))[1:20]   # 20 markers that move together

simulate_outcome <- function(truth, r) {
  set.seed(1000 * match(truth, c("sparse", "grouped", "dense")) + r)
  beta <- rep(0, 1000)
  if (truth == "sparse")  beta[sample(1000, 5)] <- sample(c(-1, 1), 5, replace = TRUE)
  if (truth == "grouped") beta[block] <- 0.4 * sign(cor(X_sim[, hub], X_sim[, block]))[1, ]
  if (truth == "dense")   beta <- rnorm(1000, 0, 0.1)
  signal <- drop(X_sim %*% beta)
  list(y = signal + rnorm(nrow(X_sim), 0, sd(signal) / 1.5), causal = which(beta != 0))
}
```

# Problem 03: Me, the consultant [30 points]

## 3a. A fair comparison [12 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 3b. Is the marker list reproducible? [10 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 3c. The lasso's markers are replaceable [8 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

# Problem 04: Me, the truth keeper [18 points]

## 4a. When we know the truth [10 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 4b. Your advice [8 points]

**Answer:**

# Problem 05: Me, the counter [24 points]

## 5a. Seasons of birth [14 points]

```{r}
#| echo: false
# !! DO NOT EDIT/REMOVE !!
# HMIS live births, mean per month over 2009-2020, moved back 9 months to the month of conception
births <- read.csv(text = "state,month,conceptions,temperature,humidity
Kerala,1,36524,24.4,64.2
Bihar,1,160729,16.3,70.3
Meghalaya,1,5854,14.7,73.7
Chhattisgarh,1,36911,19.3,54.2
Kerala,2,34852,25.7,60.3
Bihar,2,160659,19.9,59.2
Meghalaya,2,5565,17.2,66.3
Chhattisgarh,2,38440,22.8,45.7
Kerala,3,31757,26.6,67.2
Bihar,3,137061,25.2,45.0
Meghalaya,3,5336,20.6,63.0
Chhattisgarh,3,36909,27.0,37.1
Kerala,4,29867,26.5,77.9
Bihar,4,129318,29.6,40.3
Meghalaya,4,6271,22.1,77.5
Chhattisgarh,4,35957,30.8,33.5
Kerala,5,29186,25.6,85.3
Bihar,5,118916,30.8,53.2
Meghalaya,5,5694,23.2,86.3
Chhattisgarh,5,33260,33.0,34.2
Kerala,6,32391,23.7,91.5
Bihar,6,112461,30.6,67.5
Meghalaya,6,5882,24.3,88.9
Chhattisgarh,6,39009,29.7,61.7
Kerala,7,33205,23.3,90.7
Bihar,7,94718,28.5,82.4
Meghalaya,7,5368,24.4,89.1
Chhattisgarh,7,28159,25.8,84.7
Kerala,8,34418,23.3,90.3
Bihar,8,94790,28.2,84.0
Meghalaya,8,5088,24.5,89.0
Chhattisgarh,8,30728,25.4,86.1
Kerala,9,33133,23.6,88.7
Bihar,9,94239,27.7,84.0
Meghalaya,9,4745,23.9,88.8
Chhattisgarh,9,31616,25.7,83.1
Kerala,10,31369,23.9,87.3
Bihar,10,120875,25.6,76.3
Meghalaya,10,4952,22.2,83.9
Chhattisgarh,10,33002,24.6,71.9
Kerala,11,30885,23.9,83.6
Bihar,11,154161,21.9,65.8
Meghalaya,11,5439,19.0,76.6
Chhattisgarh,11,33690,22.1,63.2
Kerala,12,32903,23.9,76.3
Bihar,12,156454,17.7,67.6
Meghalaya,12,5847,15.9,75.3
Chhattisgarh,12,33799,19.4,58.6")
births$days <- c(31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[births$month]
births$s1 <- sin(2 * pi * births$month / 12)
births$c1 <- cos(2 * pi * births$month / 12)
```

```{r}
# YOUR CODE HERE
```

**Answer:**

## 5b. Season or climate? [10 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

# Air quality in Indian cities

```{r}
#| echo: false
#| message: false
# !! DO NOT EDIT/REMOVE !!
# Older versions lack cpcb_city_daily() and the *_bbox() downloaders, so update them too.
min_versions <- c(vayuayan = "0.3.0", varunayan = "0.4.0")
for (pkg in names(min_versions)) {
  if (!requireNamespace(pkg, quietly = TRUE) ||
      packageVersion(pkg) < min_versions[[pkg]]) {
    install.packages(pkg, repos = "https://cloud.r-project.org")
  }
}
library(vayuayan)
library(varunayan)
```

```{r}
#| echo: false
#| message: false
# !! DO NOT EDIT/REMOVE !!
cities <- tribble(
  ~city,                ~lat,  ~lon,
  "Kolkata",            22.57, 88.36,
  "Chennai",            13.08, 80.27,
  "Bengaluru",          12.97, 77.59,
  "Hyderabad",          17.39, 78.49,
  "Ahmedabad",          23.02, 72.57,
  "Pune",               18.52, 73.86,
  "Lucknow",            26.85, 80.95,
  "Patna",              25.59, 85.14,
  "Jaipur",             26.91, 75.79,
  "Kanpur",             26.45, 80.33,
  "Visakhapatnam",      17.69, 83.22,
  "Thiruvananthapuram",  8.52, 76.94,
  "Gurugram",           28.46, 77.03,
  "Varanasi",           25.32, 82.97,
  "Amritsar",           31.63, 74.87,
  "Jodhpur",            26.24, 73.02
)
reference <- tibble(city = c("Delhi", "Mumbai"), lat = c(28.61, 19.08), lon = c(77.21, 72.88))

assign_city <- function(roll_number) {
  seed <- sum(utf8ToInt(toupper(roll_number)) * seq_len(nchar(roll_number)))
  set.seed(seed)
  cities[sample(nrow(cities), 1), ]
}

# CPCB AQI categories
aqi_category <- function(aqi) {
  cut(aqi, c(-Inf, 50, 100, 200, 300, 400, Inf),
      labels = c("Good", "Satisfactory", "Moderate", "Poor", "Very Poor", "Severe"))
}

# IMD seasons
imd_season <- function(month) {
  factor(case_when(month %in% c(12, 1, 2) ~ "Winter",
                   month %in% 3:5 ~ "Pre-monsoon",
                   month %in% 6:9 ~ "Monsoon",
                   TRUE ~ "Post-monsoon"),
         levels = c("Winter", "Pre-monsoon", "Monsoon", "Post-monsoon"))
}

# Daily IMD weather for the 1-degree cell around a city
city_weather <- function(lat, lon, start_year, end_year, rain = TRUE) {
  quiet <- function(expr) { utils::capture.output(x <- suppressMessages(expr)); x }
  n <- lat + 0.5; s <- lat - 0.5; e <- lon + 0.5; w <- lon - 0.5
  tmax <- quiet(imd_temperature_bbox("tmax", start_year, end_year, n, s, e, w, var_type = "tmax"))
  tmin <- quiet(imd_temperature_bbox("tmin", start_year, end_year, n, s, e, w, var_type = "tmin"))
  out <- full_join(dplyr::select(tmax, date, tmax = temperature),
                   dplyr::select(tmin, date, tmin = temperature), by = "date")
  if (rain) {
    rainfall <- quiet(imd_rainfall_bbox("rain", start_year, end_year, n, s, e, w, resolution = 1))
    out <- full_join(dplyr::select(rainfall, date, rain = rainfall), out, by = "date")
  }
  arrange(out, date)
}

# Downloads are cached next to this file, so only the first render is slow
cached <- function(file, expr) {
  dir.create("a03_cache", showWarnings = FALSE)
  path <- file.path("a03_cache", file)
  if (!file.exists(path)) saveRDS(expr, path)
  readRDS(path)
}
```

```{r}
# Replace with YOUR roll number exactly as on Gradescope (e.g. "24D1234")
roll_number <- "YOUR ROLL NUMBER"
my <- assign_city(roll_number)
my
```

```{r}
#| echo: false
#| message: false
# !! DO NOT EDIT/REMOVE !!
# The first render downloads about 2-3 minutes of data; later renders use a03_cache/.
all_cities <- c(cities$city, reference$city)
aqi <- cached("aqi_2018_2025.rds", {
  map_dfr(2018:2025, function(y) {
    cpcb_city_daily(all_cities, y, cache_dir = "a03_cache") |> mutate(year = y)
  }) |>
    mutate(date = make_date(year, month, day)) |>
    filter(!is.na(date)) |>
    dplyr::select(city, date, year, month, aqi = value)
})

weather_recent <- function(place) {
  cached(paste0("weather_2018_2025_", place$city, ".rds"),
         city_weather(place$lat, place$lon, 2018, 2025))
}

# Your city and Delhi: AQI joined with the weather of the same day
my_daily <- aqi |> filter(city == my$city) |> left_join(weather_recent(my), by = "date")
delhi_daily <- aqi |> filter(city == "Delhi") |> left_join(weather_recent(reference[1, ]), by = "date")
```

# Problem 06: Me, the explorer [22 points]

## 6a. Look at your city [9 points]

| Quantity | Value |
|----------|-------|
| Your city | |
| Days with AQI, 2018-2025 | |
| Missing days | |
| Longest gap (days) | |
| Month with the highest median AQI, and that median | |
| Month with the lowest median AQI, and that median | |
| Highest / lowest monthly median, 1 decimal: your city, Delhi | |

```{r}
# YOUR CODE HERE
```

**Answer:**

## 6b. Categories and seasons [13 points]

| Quantity | Value |
|----------|-------|
| Independence test: $X^2$ (1 decimal), df, p-value | |
| Cell with the largest standardised residual, and its value (1 decimal) | |
| Winter "Poor or worse" %, 1 decimal: your city, Delhi | |
| Two-proportion test: $X^2$ (1 decimal), p-value | |

```{r}
# YOUR CODE HERE
```

**Answer:**

# Problem 07: Me, the Diwali detective [35 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
# Diwali days. In 2024 and 2025 some regions celebrated a day later.
diwali <- as.Date(c("2018-11-07", "2019-10-27", "2020-11-14", "2021-11-04",
                    "2022-10-24", "2023-11-12", "2024-10-31", "2025-10-20"))
```

## 7a. Delhi and Chennai, eight Diwalis [13 points]

| Quantity | Delhi | Chennai |
|----------|-------|---------|
| Years used | | |
| Years with $D > 0$ | | |
| Median $D$ (1 decimal) | | |
| Sign test p-value | | |
| Signed-rank p-value | | |

```{r}
# YOUR CODE HERE
```

**Answer:**

## 7b. All 18 cities [7 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 7c. Diwali, fake wali [10 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 7d. The 2020 puzzle [5 points]

**Answer:**

# Problem 08: Me, the forecaster [28 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
forecast_data <- my_daily |>
  arrange(date) |>
  mutate(y = log(aqi),
         lag1 = lag(y, 1), lag2 = lag(y, 2), lag3 = lag(y, 3), lag7 = lag(y, 7),
         rain1 = lag(rain, 1), tmax1 = lag(tmax, 1), tmin1 = lag(tmin, 1),
         month = factor(month)) |>
  filter(date - lag(date, 7) == 7) |>
  drop_na(y, lag1, lag2, lag3, lag7, rain1, tmax1, tmin1)
fc_train <- filter(forecast_data, year <= 2023)
fc_test <- filter(forecast_data, year >= 2024)
```

## 8a. Beat the lazy forecast [9 points]

| Quantity | Value |
|----------|-------|
| Test MSE, persistence (4 decimals) | |
| Test MSE, model 2 (4 decimals) | |
| Test MSE, model 3 (4 decimals) | |
| Slope of `lag1` in model 2, with 95% CI (3 decimals) | |

```{r}
# YOUR CODE HERE
```

**Answer:**

## 8b. Penalised forecasts, without peeking at the future [12 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
set.seed(2026)
```

```{r}
# YOUR CODE HERE
```

**Answer:**

## 8c. Is the improvement real? [7 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

# Problem 09: Me, the data scientist [26 points]

```{r}
# !! DO NOT EDIT/REMOVE !!
make_my_data <- function(roll_number) {
  seed <- sum(utf8ToInt(toupper(roll_number)) * seq_len(nchar(roll_number)))
  set.seed(seed)
  n <- sample(90:150, 1)
  pm25 <- round(pmax(10, rgamma(n, shape = 4, scale = 15)))
  baseline <- sample(c(2, 3, 4), 1)
  slope <- sample(c(0, 0.04, 0.08), 1)
  mu <- exp(log(baseline) + slope * (pm25 - 60) / 10)
  visits <- switch(sample(3, 1),
                   rpois(n, mu),
                   rnbinom(n, mu = mu, size = 1.5),
                   rpois(n, mu) * rbinom(n, 1, 0.75))
  data.frame(day = seq_len(n), pm25 = pm25, visits = visits)
}
```

```{r}
# Uses the roll_number you set before Problem 06
my_er <- make_my_data(roll_number)
head(my_er)
```

## 9a. Look before you model [9 points]

```{r}
# YOUR CODE HERE
```

**Answer:**

## 9b. Report [10 points]

| Quantity | Value |
|----------|-------|
| Roll number used | |
| Number of days $n$ | |
| Observed / Poisson-expected number of zero-visit days | |
| Poisson: rate ratio, 95% CI, p-value | |
| Dispersion $\hat\phi$ (Pearson) | |
| Quasi-Poisson: 95% CI, p-value | |
| Negative binomial: rate ratio, $\hat\theta$, p-value | |
| AIC: Poisson, negative binomial | |

```{r}
# YOUR CODE HERE
```

## 9c. In your own words [7 points]

**Answer:**

