library(tidyverse)
library(tidymodels)
library(here)
library(knitr)
stopifnot(requireNamespace("xgboost", quietly = TRUE))
utf8_locale <- if (.Platform$OS.type == "windows") {
"English_United States.utf8"
} else {
"C.UTF-8"
}
invisible(Sys.setlocale("LC_CTYPE", utf8_locale))Forecasting Hourly Precipitation at JFK Airport
A calibrated two-stage model with temporal validation
Objective
Hourly precipitation is a zero-inflated target: most observations are dry, while a small number of storms account for the largest errors. This notebook therefore answers two questions separately: will it rain? and, conditional on rain, how much?
Every transformation, model, and evaluation step is visible below. The forecast uses contemporaneous weather readings plus the previous precipitation observation; it never uses future information.
Packages
Read the reproducible snapshot
weather <- read_csv(
here("data", "jfk_weather_snapshot.csv"),
show_col_types = FALSE,
col_types = cols(date = col_datetime())
) |>
arrange(date)required_columns <- c(
"date", "humidity", "temperature_f", "station_pressure",
"wind_speed_mph", "precipitation_in"
)
stopifnot(
all(required_columns %in% names(weather)),
anyDuplicated(weather$date) == 0,
!any(weather$precipitation_in < 0, na.rm = TRUE)
)Engineer available-at-prediction-time features
weather <- weather |>
mutate(
rain = factor(if_else(precipitation_in > 0, "rain", "dry"),
levels = c("rain", "dry")),
precipitation_lag1 = lag(precipitation_in, default = 0),
rain_lag1 = lag(as.integer(precipitation_in > 0), default = 0),
gap_hours = as.numeric(difftime(date, lag(date), units = "hours")),
gap_hours = replace_na(gap_hours, median(gap_hours, na.rm = TRUE)),
month_sin = sin(2 * pi * month(date) / 12),
month_cos = cos(2 * pi * month(date) / 12),
hour_sin = sin(2 * pi * hour(date) / 24),
hour_cos = cos(2 * pi * hour(date) / 24)
)weather |>
summarise(
observations = n(),
first_observation = min(date),
last_observation = max(date),
wet_hours = sum(rain == "rain"),
wet_share = mean(rain == "rain")
) |>
kable(digits = 3)| observations | first_observation | last_observation | wet_hours | wet_share |
|---|---|---|---|---|
| 4067 | 2010-01-01 04:51:00 | 2018-07-26 10:51:00 | 393 | 0.097 |
Explore the target
ggplot(weather, aes(x = precipitation_in)) +
geom_histogram(binwidth = 0.01, boundary = 0,
fill = "#2A9D8F", color = "white") +
coord_cartesian(xlim = c(0, quantile(weather$precipitation_in, 0.995))) +
labs(
title = "Hourly precipitation is strongly zero-inflated",
x = "Precipitation (inches)", y = "Observations"
) +
theme_minimal(base_size = 12) +
theme(plot.title = element_text(face = "bold"))
weather |>
mutate(day = as.Date(date)) |>
group_by(day) |>
summarise(precipitation_in = sum(precipitation_in), .groups = "drop") |>
ggplot(aes(x = day, y = precipitation_in)) +
geom_col(fill = "#457B9D", width = 1) +
labs(
title = "Rain arrives in short, irregular episodes",
x = "Date", y = "Daily precipitation (inches)"
) +
theme_minimal(base_size = 12) +
theme(plot.title = element_text(face = "bold"))
Preserve the temporal order
The earliest 70% is used for model selection, the next 10% for calibration, and the latest 20% only once for final evaluation.
set.seed(2026)
final_split <- initial_time_split(weather, prop = 0.8)
development_data <- training(final_split)
testing_data <- testing(final_split)
validation_split <- initial_time_split(development_data, prop = 0.875)
modeling_data <- training(validation_split)
validation_data <- testing(validation_split)bind_rows(
modeling_data |> summarise(partition = "Modeling", n = n(), first = min(date), last = max(date)),
validation_data |> summarise(partition = "Calibration", n = n(), first = min(date), last = max(date)),
testing_data |> summarise(partition = "Final test", n = n(), first = min(date), last = max(date))
) |>
kable()| partition | n | first | last |
|---|---|---|---|
| Modeling | 2846 | 2010-01-01 04:51:00 | 2015-12-13 09:51:00 |
| Calibration | 407 | 2015-12-14 04:51:00 | 2016-11-05 18:51:00 |
| Final test | 814 | 2016-11-05 22:51:00 | 2018-07-26 10:51:00 |
class_resamples <- rolling_origin(
modeling_data,
initial = 1500,
assess = 325,
cumulative = TRUE,
skip = 324
)
class_resamples# Rolling origin forecast resampling
# A tibble: 4 × 2
splits id
<list> <chr>
1 <split [1500/325]> Slice1
2 <split [1825/325]> Slice2
3 <split [2150/325]> Slice3
4 <split [2475/325]> Slice4
Baselines
baseline_mean <- mean(development_data$precipitation_in)
baseline_predictions <- testing_data |>
transmute(
date, precipitation_in,
`Dry baseline` = 0,
`Historical mean` = baseline_mean
)Previous single-stage benchmark
polynomial_recipe <- recipe(
precipitation_in ~ humidity + temperature_f +
station_pressure + wind_speed_mph,
data = development_data
) |>
step_impute_median(all_numeric_predictors()) |>
step_normalize(all_numeric_predictors()) |>
step_poly(all_numeric_predictors(), degree = 2)polynomial_fit <- workflow() |>
add_recipe(polynomial_recipe) |>
add_model(linear_reg() |> set_engine("lm")) |>
fit(data = development_data)
polynomial_predictions <- predict(polynomial_fit, testing_data) |>
pull(.pred)Stage 1: rain occurrence
Classification recipe
occurrence_recipe <- recipe(
rain ~ humidity + temperature_f + station_pressure + wind_speed_mph +
precipitation_lag1 + rain_lag1 + gap_hours + month_sin + month_cos +
hour_sin + hour_cos,
data = modeling_data
) |>
step_impute_median(all_numeric_predictors())Classification model
occurrence_spec <- boost_tree(
trees = 600,
tree_depth = tune(),
min_n = tune(),
learn_rate = tune(),
loss_reduction = tune(),
sample_size = tune(),
mtry = tune()
) |>
set_mode("classification") |>
set_engine("xgboost")Classification grid
predictor_names <- c(
"humidity", "temperature_f", "station_pressure", "wind_speed_mph",
"precipitation_lag1", "rain_lag1", "gap_hours", "month_sin",
"month_cos", "hour_sin", "hour_cos"
)
occurrence_grid <- grid_space_filling(
tree_depth(c(2L, 7L)), min_n(c(5L, 35L)), learn_rate(c(-3, -0.7)),
loss_reduction(), sample_prop(c(0.65, 1)),
finalize(mtry(), modeling_data |> select(all_of(predictor_names))),
size = 12
)Temporal tuning
occurrence_results <- workflow() |>
add_recipe(occurrence_recipe) |>
add_model(occurrence_spec) |>
tune_grid(
resamples = class_resamples,
grid = occurrence_grid,
metrics = metric_set(pr_auc, roc_auc, mn_log_loss)
)
best_occurrence <- select_best(occurrence_results, metric = "pr_auc")
best_occurrence |> kable(digits = 4)| mtry | min_n | tree_depth | learn_rate | loss_reduction | sample_size | .config |
|---|---|---|---|---|---|---|
| 11 | 26 | 5 | 0.0069 | 0.2565 | 0.9682 | pre0_mod12_post0 |
Fit the selected classifier
occurrence_workflow <- workflow() |>
add_recipe(occurrence_recipe) |>
add_model(occurrence_spec) |>
finalize_workflow(best_occurrence)
occurrence_fit <- occurrence_workflow |>
fit(data = modeling_data)Stage 2: precipitation amount
The amount model sees only wet observations. This prevents thousands of dry hours from overwhelming the storm-size signal.
wet_modeling_data <- modeling_data |>
filter(rain == "rain")
amount_resamples <- rolling_origin(
wet_modeling_data,
initial = 140,
assess = 40,
cumulative = TRUE,
skip = 39
)Amount recipe
amount_recipe <- recipe(
precipitation_in ~ humidity + temperature_f + station_pressure +
wind_speed_mph + precipitation_lag1 + rain_lag1 + gap_hours +
month_sin + month_cos + hour_sin + hour_cos,
data = wet_modeling_data
) |>
step_impute_median(all_numeric_predictors())Amount model
amount_spec <- boost_tree(
trees = 600,
tree_depth = tune(),
min_n = tune(),
learn_rate = tune(),
loss_reduction = tune(),
sample_size = tune(),
mtry = tune()
) |>
set_mode("regression") |>
set_engine("xgboost")Amount grid and tuning
amount_grid <- grid_space_filling(
tree_depth(c(2L, 6L)), min_n(c(3L, 25L)), learn_rate(c(-3, -0.7)),
loss_reduction(), sample_prop(c(0.65, 1)),
finalize(mtry(), wet_modeling_data |> select(all_of(predictor_names))),
size = 12
)amount_results <- workflow() |>
add_recipe(amount_recipe) |>
add_model(amount_spec) |>
tune_grid(
resamples = amount_resamples,
grid = amount_grid,
metrics = metric_set(rmse, mae)
)
best_amount <- select_best(amount_results, metric = "rmse")
best_amount |> kable(digits = 4)| mtry | min_n | tree_depth | learn_rate | loss_reduction | sample_size | .config |
|---|---|---|---|---|---|---|
| 2 | 25 | 6 | 0.0042 | 2e-04 | 0.7773 | pre0_mod03_post0 |
Fit the selected amount model
amount_workflow <- workflow() |>
add_recipe(amount_recipe) |>
add_model(amount_spec) |>
finalize_workflow(best_amount)
amount_fit <- amount_workflow |>
fit(data = wet_modeling_data)Calibrate without touching the final test
validation_predictions <- validation_data |>
select(date, rain, precipitation_in) |>
bind_cols(predict(occurrence_fit, validation_data, type = "prob")) |>
bind_cols(predict(amount_fit, validation_data)) |>
rename(amount_raw = .pred) |>
mutate(
amount_raw = pmax(amount_raw, 0),
logit_probability = qlogis(pmin(pmax(.pred_rain, 0.001), 0.999))
)probability_calibration <- glm(
I(rain == "rain") ~ logit_probability,
data = validation_predictions,
family = binomial()
)
validation_predictions <- validation_predictions |>
mutate(rain_probability = predict(
probability_calibration, newdata = validation_predictions,
type = "response"
))amount_scale <- validation_predictions |>
filter(rain == "rain") |>
summarise(scale = sum(precipitation_in * amount_raw) / sum(amount_raw^2)) |>
pull(scale)
amount_scale[1] 0.8347213
threshold_results <- crossing(
threshold = seq(0.05, 0.60, by = 0.01),
validation_predictions
) |>
mutate(.pred = if_else(
rain_probability >= threshold, amount_raw * amount_scale, 0
)) |>
group_by(threshold) |>
summarise(rmse = sqrt(mean((precipitation_in - .pred)^2)), .groups = "drop")
best_threshold <- threshold_results |>
slice_min(rmse, n = 1, with_ties = FALSE) |>
pull(threshold)Refit on all development data
final_occurrence_fit <- occurrence_workflow |>
fit(data = development_data)
final_amount_fit <- amount_workflow |>
fit(data = development_data |> filter(rain == "rain"))holdout_predictions <- testing_data |>
select(date, rain, precipitation_in) |>
bind_cols(predict(final_occurrence_fit, testing_data, type = "prob")) |>
bind_cols(predict(final_amount_fit, testing_data)) |>
rename(amount_raw = .pred) |>
mutate(
amount_raw = pmax(amount_raw, 0),
logit_probability = qlogis(pmin(pmax(.pred_rain, 0.001), 0.999)),
rain_probability = predict(probability_calibration,
newdata = pick(everything()), type = "response"),
amount = amount_raw * amount_scale
)holdout_predictions <- holdout_predictions |>
mutate(
`Hurdle model` = if_else(
rain_probability >= best_threshold, amount, 0
),
`Expected precipitation` = rain_probability * amount,
`Single-stage polynomial` = polynomial_predictions,
`Dry baseline` = 0,
`Historical mean` = baseline_mean
)Final holdout performance
regression_metrics <- holdout_predictions |>
select(precipitation_in, `Dry baseline`, `Historical mean`,
`Single-stage polynomial`, `Hurdle model`, `Expected precipitation`) |>
pivot_longer(-precipitation_in, names_to = "model", values_to = ".pred") |>
group_by(model) |>
summarise(
rmse = sqrt(mean((precipitation_in - .pred)^2)),
mae = mean(abs(precipitation_in - .pred)),
wet_rmse = sqrt(mean((precipitation_in[precipitation_in > 0] -
.pred[precipitation_in > 0])^2)),
.groups = "drop"
) |>
arrange(rmse)
regression_metrics |> kable(digits = 4)| model | rmse | mae | wet_rmse |
|---|---|---|---|
| Expected precipitation | 0.0430 | 0.0098 | 0.1318 |
| Hurdle model | 0.0439 | 0.0091 | 0.1305 |
| Single-stage polynomial | 0.0444 | 0.0146 | 0.1345 |
| Historical mean | 0.0458 | 0.0120 | 0.1449 |
| Dry baseline | 0.0463 | 0.0068 | 0.1478 |
occurrence_metrics <- holdout_predictions |>
summarise(
pr_auc = pr_auc_vec(rain, rain_probability, event_level = "first"),
roc_auc = roc_auc_vec(rain, rain_probability, event_level = "first"),
brier_score = brier_class_vec(rain, rain_probability,
event_level = "first")
)
occurrence_metrics |> kable(digits = 3)| pr_auc | roc_auc | brier_score |
|---|---|---|
| 0.564 | 0.918 | 0.064 |
Inspect predictions over time
holdout_daily <- holdout_predictions |>
mutate(day = as.Date(date)) |>
group_by(day) |>
summarise(
Observed = sum(precipitation_in),
Predicted = sum(`Expected precipitation`),
.groups = "drop"
) |>
pivot_longer(c(Observed, Predicted), names_to = "series", values_to = "inches")ggplot(holdout_daily, aes(x = day, y = inches, color = series)) +
geom_line(linewidth = 0.8) +
scale_color_manual(values = c(Observed = "#264653", Predicted = "#E76F51")) +
labs(
title = "Observed and predicted precipitation - final holdout",
x = "Date", y = "Daily precipitation (inches)", color = NULL
) +
theme_minimal(base_size = 12) +
theme(plot.title = element_text(face = "bold"), legend.position = "top")
holdout_predictions |>
mutate(probability_bin = ntile(rain_probability, 10)) |>
group_by(probability_bin) |>
summarise(
predicted = mean(rain_probability),
observed = mean(rain == "rain"),
.groups = "drop"
) |>
ggplot(aes(x = predicted, y = observed)) +
geom_abline(slope = 1, intercept = 0, color = "#777777") +
geom_point(size = 2.5, color = "#2A9D8F") +
labs(title = "Calibrated rain probabilities", x = "Predicted", y = "Observed") +
theme_minimal(base_size = 12)
Conclusion
best_model <- regression_metrics |> slice_min(rmse, n = 1)
mean_baseline_rmse <- regression_metrics |>
filter(model == "Historical mean") |>
pull(rmse)
rmse_improvement <- 100 * (mean_baseline_rmse - best_model$rmse) /
mean_baseline_rmse- The best final prediction is Expected precipitation, with RMSE 0.0430 and a 6.2% reduction relative to the historical-mean baseline.
- The occurrence model reaches PR AUC 0.564 and ROC AUC 0.918 on the untouched final period.
- The calibration threshold (0.48) and amount correction (0.83) were learned from the middle 10%, not from the final test.
- The model is reproducible and leakage-aware, but it is not a production nowcast: radar, cloud cover, and denser hourly history would be needed for that claim.
See the Spanish version.