The idea

In a run-pass option (RPO) the quarterback decides after the snap whether to hand off or throw, based on what one defender does. Once the ball is snapped it is too late for the defence to adjust, so the only real counter is to see it coming.

This project builds a model that gives a live probability that a play is an RPO, updating from the moment the offence sets until the snap, and uses it to find the most common tells coaches should watch for.

Inspiration. The live, frame-by-frame idea comes from the 2025 Big Data Bowl winner, “Exposing Coverage Tells in the Presnap” (Bajaj and Sandwar, NYU), which predicted man or zone coverage as the defence moved. This project turns that idea on the offence. The second model follows SumerSports’ public transformer, which reads tracking frames directly. It was first released for the 2025 Big Data Bowl and updated for 2026 (SumerSports: Big Data Bowl 2026; code: SportsTrackingTransformer on GitHub). That post is by Vishakh Sandwar, one of the two authors of the winning 2025 entry, so both inspirations come from the same line of work.

How the model works

Input. One row per frame between lineset and snap, describing the look at that moment. The tracking data records 10 frames per second; every second frame is used (one every 0.2 s), because neighbouring frames are near-duplicates and the extra rows add computing time but almost no new information. The live demo still animates every frame. Each row describes:

Group Examples
Situation down, yards to go, field position, time left in the game (combines quarter and game clock), score, win probability
Personnel / formation formation, receiver alignment, RBs, TEs, WRs
Backfield QB depth, RB depth relative to QB, RB side vs receiver strength
Receivers average and widest split, formation width, TEs attached to the line
Defence box count, deep safeties, defenders on the line, safety movement
Motion who has moved, how far, jet / orbit / across motion

Output. XGBoost (many small decision trees added together) gives the probability of an RPO at every frame:

\[P(\text{RPO}) = \frac{1}{1 + e^{-\text{score}}}\]

A logistic regression with one row per play is the baseline it has to beat.

Linked frames. Neighbouring frames are near copies, so roughly 465,000 frames really come from about 15,800 plays. Each frame is weighted by 1 ÷ (frames in its play), every frame of a play stays on the same side of the train/test split, and all results are counted per play.

Testing. Leave-one-week-out: train on 8 weeks, test on the 9th, repeat for all 9 weeks. Because RPOs are rare, the main measures are ROC-AUC, PR-AUC and balanced accuracy (the average of how well RPOs are caught and non-RPOs cleared; 50% is a coin flip).

Feature glossary

Most features are not columns in the Kaggle data dictionary: they are built from the player tracking. This table gives each one a plain-English meaning and says where it comes from. The charts below use the readable names.

datatable(glossary[, .(Feature = label, `Code name` = feature, Group = group,
                       Meaning = meaning, Source = source)],
          rownames = FALSE, filter = "top",
          options = list(pageLength = 10, scrollX = TRUE, autoWidth = FALSE)) |>
  formatStyle("Meaning", `min-width` = "320px")

The code, step by step

All of the analysis code is included in this report. Each step below shows the key lines; click Show to see the full step. The pipeline is one script, rpo_project.R.

Settings and packages.

# =============================================================================
# Predicting Run-Pass Options from the Pre-Snap  --  main model
# IS 470 Assignment 2  --  NFL Big Data Bowl 2025 data
#
# Follows the Assignment 2 proposal:
#   1. Input   : one row per frame from lineset to snap, describing the look
#                at that moment (formation, backfield, receivers, defence,
#                motion so far, situation)
#   2. Output  : P(RPO) for every frame from XGBoost, with a play-level
#                logistic regression as the baseline it has to beat
#   3. Linked frames: each play counts once (weights), plays/games stay
#                together in train/test, results are counted per play
#   4. Testing : leave-one-week-out, balanced accuracy, warning time
#                (accuracy 1-4 seconds before the snap)
#   5. SHAP    : importance, beeswarm, dependence and waterfall charts
#   6. Tells   : looks built from the top SHAP features, scored by lift and
#                coverage, with team usage -> tell sheet for coaches
#
#   7. Transformer (optional, last section): a SumerSports-style model that
#                reads the frames of each play in order, compared with
#                XGBoost on the same plays
#
# Packages: data.table, ggplot2, xgboost, shapviz
#           torch (only if run_transformer = TRUE; first time run
#           install.packages("torch"); torch::install_torch())
# Data folder: games.csv, plays.csv, players.csv, player_play.csv,
#              tracking_week_1.csv ... tracking_week_9.csv
# =============================================================================

library(data.table)
library(ggplot2)
library(xgboost)
library(shapviz)

# ---- Settings ---------------------------------------------------------------
data_dir        <- "data"
out_dir         <- "rpo_output"
weeks           <- 1:9
frame_step      <- 2      # one frame every 0.2 s, counted back from the snap
box_margin      <- 3.5    # box = up to this many yards outside the tackles
use_team        <- TRUE   # offensive team as a feature (scouting) - set FALSE
                          # to measure tells that generalise across teams
rebuild_frames  <- FALSE  # TRUE forces re-reading the tracking files
inner_folds     <- 3      # game-grouped folds for choosing the number of trees
shap_sample     <- 20000  # frames used for the SHAP charts
warning_secs    <- 0:4    # seconds before the snap to check accuracy at
tell_top_vars   <- 15     # tells are built from the top-N SHAP variables
tell_max_size   <- 3      # max conditions combined into one look
tell_min_plays  <- 50     # a look needs this many plays to be listed
tell_min_lift   <- 1.5    # ... and at least this lift
tell_n_show     <- 15     # looks on the tell sheet

# transformer (section 10) - slow on a CPU (roughly 10-30 min per week)
run_transformer <- TRUE
tf_test_weeks   <- 1:9    # held-out weeks to run (e.g. 7:9 for a quick run)
t_step          <- 5      # one frame every 0.5 s, counted back from the snap
t_max           <- 16     # frames per play (last 8 s before the snap)
d_model         <- 64
n_heads         <- 4
space_layers    <- 2      # attention between players
time_layers     <- 2      # attention across frames
dropout         <- 0.1
batch_size      <- 64
max_epochs      <- 12
patience        <- 3      # stop when validation loss stops improving
lr              <- 3e-4
rebuild_tensors <- FALSE
set.seed(42)
dir.create(out_dir, showWarnings = FALSE)
cache_file <- file.path(out_dir, "frame_features.csv")

OL_POS <- c("T", "G", "C", "OT", "OG", "OL")
as_flag <- function(x) {
  x <- toupper(as.character(x))
  as.integer(!is.na(x) & x %in% c("TRUE", "1", "T", "Y"))
}
save_plot <- function(p, file, w = 8, h = 5)
  ggsave(file.path(out_dir, file), p, width = w, height = h, dpi = 150)

Step 1: the plays. Filter the plays (no kneels, spikes or penalty-nullified plays) and build the situation and personnel features.

# =============================================================================
# 1. Plays and play-level information
# =============================================================================
games       <- fread(file.path(data_dir, "games.csv"))
plays       <- fread(file.path(data_dir, "plays.csv"))
players     <- fread(file.path(data_dir, "players.csv"))
player_play <- fread(file.path(data_dir, "player_play.csv"),
                     select = c("gameId", "playId", "nflId", "teamAbbr"))

plays <- merge(plays, games[, .(gameId, week, homeTeamAbbr)], by = "gameId")
plays <- plays[
  !is.na(pff_runPassOption) &
  playNullifiedByPenalty != "Y" &
  as_flag(qbKneel) == 0 & as_flag(qbSpike) == 0 &
  !is.na(offenseFormation) & offenseFormation != "" &
  week %in% weeks
]
plays[, rpo := as.integer(pff_runPassOption == 1)]
plays[, yards_to_endzone := fifelse(
  yardlineNumber == 50, 50,
  fifelse(yardlineSide == possessionTeam, 100 - yardlineNumber, yardlineNumber))]
plays[, clock_sec := {
  p <- tstrsplit(gameClock, ":", fixed = TRUE)
  as.numeric(p[[1]]) * 60 + as.numeric(p[[2]])
}]
plays[, game_sec_left := pmax(0, (4 - pmin(quarter, 4)) * 900 + clock_sec)]
plays[, is_home := as.integer(possessionTeam == homeTeamAbbr)]
plays[, score_diff := fifelse(is_home == 1,
                              preSnapHomeScore - preSnapVisitorScore,
                              preSnapVisitorScore - preSnapHomeScore)]
plays[, off_win_prob := fifelse(is_home == 1,
                                preSnapHomeTeamWinProbability,
                                preSnapVisitorTeamWinProbability)]
plays[, formation := offenseFormation]
plays[, alignment := fifelse(is.na(receiverAlignment) |
                               receiverAlignment == "", "unknown",
                             receiverAlignment)]
plays[, team := possessionTeam]

# personnel on the field
pp <- merge(player_play, players[, .(nflId, position)], by = "nflId",
            all.x = TRUE)
pp <- merge(pp, plays[, .(gameId, playId, possessionTeam)],
            by = c("gameId", "playId"))[teamAbbr == possessionTeam]
pers <- pp[, .(n_rb = sum(position %in% c("RB", "FB")),
               n_te = sum(position == "TE"),
               n_wr = sum(position == "WR"),
               n_ol = sum(position %in% OL_POS)), by = .(gameId, playId)]
pers[, extra_blockers := n_te + pmax(n_ol - 5, 0)]
plays <- merge(plays, pers, by = c("gameId", "playId"))

static <- plays[, .(gameId, playId, week, rpo, possessionTeam,
                    down, yardsToGo, yards_to_endzone, game_sec_left,
                    score_diff, off_win_prob, playClockAtSnap,
                    formation, alignment, team,
                    n_rb, n_te, n_wr, extra_blockers)]
fwrite(static, file.path(out_dir, "play_info.csv"))

Step 2: describe every frame. The core of the project: positions from the tracking data are turned into the features in the glossary. For example, the running back relative to the quarterback:

# running back relative to the quarterback (the offence attacks toward +x)
rb_depth <- los - x1[r]              # yards behind the line of scrimmage
rb_lat   <- y1[r] - qb_y             # + = RB on the QB's left
rb_dx    <- x1[r] - qb_x             # negative = RB deeper than the QB
rb_beside <- abs(rb_dx) < 1.5 & abs(rb_lat) >= 0.8 & abs(rb_lat) <= 4.5
strong <- sign(n_left - n_right)     # side with more receivers split wide
rb_to_strength <- sign(rb_lat) * strong   # +1 = RB on the strength side
# =============================================================================
# 2. Input: describe each frame between lineset and snap
# =============================================================================
# Vectors for the players in one play at one frame:
#   x0,y0 = position at lineset; x1,y1,s1 = position/speed now;
#   dist/maxs/minx = distance, top speed and deepest point since lineset.
frame_feats <- function(pos, off, x0, y0, x1, y1, s1, dist, maxs, minx,
                        los, by) {
  los <- los[1]; by <- by[1]
  isol <- pos %in% OL_POS
  o <- off == 1; d <- off == 0

  qbi <- which(o & pos == "QB")
  if (!length(qbi)) qbi <- which(o & !isol & (los - x1) > 0.5)
  if (!length(qbi)) return(NULL)
  qbi  <- qbi[which.min(abs(y1[qbi] - by))]
  qb_x <- x1[qbi]; qb_y <- y1[qbi]

  oli <- which(o & isol)
  if (length(oli) >= 3) { tl <- min(y1[oli]); tr <- max(y1[oli]) } else {
    tl <- by - 4; tr <- by + 4 }
  sk <- setdiff(which(o & !isol & pos != "QB"), qbi)

  # backfield: running back relative to the quarterback
  bk <- sk[pos[sk] %in% c("RB", "FB")]
  if (length(bk)) {
    r <- bk[which.min((x1[bk] - qb_x)^2 + (y1[bk] - qb_y)^2)]
    rb_depth <- los - x1[r]; rb_lat <- y1[r] - qb_y; rb_dx <- x1[r] - qb_x
    rb_beside <- as.numeric(abs(rb_dx) < 1.5 & abs(rb_lat) >= 0.8 &
                              abs(rb_lat) <= 4.5)
    rb_switched <- as.numeric(abs(y0[r] - qb_y) > 0.5 & abs(rb_lat) > 0.5 &
                                sign(y0[r] - qb_y) != sign(rb_lat))
  } else {
    rb_depth <- rb_lat <- rb_dx <- NA_real_; rb_beside <- rb_switched <- 0
  }

  # receivers
  ys <- y1[sk]
  n_left <- sum(ys > tr + 1); n_right <- sum(ys < tl - 1)
  strong <- sign(n_left - n_right)
  rb_to_strength <- if (is.na(rb_lat) || strong == 0) 0 else
    sign(rb_lat) * strong
  splits <- abs(ys - by); wide <- ys > tr + 1 | ys < tl - 1
  n_attached <- sum(((ys >= tl - 2.5 & ys < tl) | (ys <= tr + 2.5 & ys > tr)) &
                      (los - x1[sk]) < 2.5)

  # defence now, and since lineset
  dd <- x1[d] - los; dd0 <- x0[d] - los; dy <- y1[d]
  in_box <- dd >= -1 & dd <= 8 & dy >= tl - box_margin & dy <= tr + box_margin
  deep_sorted <- sort(dd, decreasing = TRUE)

  # offensive motion so far
  mv <- sk[dist[sk] >= 2]
  if (length(mv)) {
    m <- sk[which.max(dist[sk])]
    lat <- abs(y1[m] - y0[m])
    crossed <- as.numeric(abs(y0[m] - by) > 1 & abs(y1[m] - by) > 1 &
                            sign(y0[m] - by) != sign(y1[m] - by))
    behind <- as.numeric(minx[m] < qb_x - 0.5)
    mtype <- if (behind == 1 && maxs[m] >= 2) "orbit" else
             if (maxs[m] >= 3.5 && lat >= 3) "jet" else
             if (crossed == 1) "across" else "short"
    mot <- list(mot_type = mtype, mot_pos = pos[m], mot_dist = dist[m],
                mot_speed_now = s1[m], mot_max_speed = maxs[m],
                mot_lateral = lat,
                mot_inward = abs(y0[m] - by) - abs(y1[m] - by),
                mot_crossed = crossed, mot_behind_qb = behind)
  } else {
    mot <- list(mot_type = "none", mot_pos = "none", mot_dist = 0,
                mot_speed_now = 0, mot_max_speed = 0, mot_lateral = 0,
                mot_inward = 0, mot_crossed = 0, mot_behind_qb = 0)
  }

  out <- c(list(
    qb_depth = los - qb_x, rb_depth = rb_depth, rb_lat_abs = abs(rb_lat),
    rb_dx = rb_dx, rb_beside_qb = rb_beside, rb_switched_side = rb_switched,
    rb_to_strength = rb_to_strength,
    n_wide_strong = max(n_left, n_right), n_wide_weak = min(n_left, n_right),
    max_split = if (length(sk)) max(splits) else NA_real_,
    mean_wide_split = if (any(wide)) mean(splits[wide]) else 0,
    formation_width = diff(range(y1[o])),
    n_attached = n_attached,
    n_backfield = sum((los - x1[sk]) > 2.5 & ys >= tl - 1 & ys <= tr + 1),
    box_count = sum(in_box),
    box_minus_blockers = sum(in_box) - length(oli) - n_attached,
    n_deep = sum(dd >= 10),
    deepest_def = if (length(dd)) max(dd) else NA_real_,
    safety_depth = if (length(dd) >= 2) mean(deep_sorted[1:2]) else NA_real_,
    n_overhang = sum(!in_box & dd >= 2 & dd <= 8),
    n_press = sum(!in_box & dd < 2),
    n_def_on_line = sum(dd <= 1.5),               # possible rushers
    n_def_walked_up = sum(dd0 - dd >= 1.5),       # crept toward the line
    safety_rotation = sum(dd >= 10) - sum(dd0 >= 10),
    deepest_change = if (length(dd)) max(dd) - max(dd0) else NA_real_,
    def_max_lateral = if (length(dd)) max(abs(y1[d] - y0[d])) else NA_real_,
    def_total_move = sum(dist[d]),
    n_skill_moved = length(mv)
  ), mot)
  lapply(out, function(v) if (is.character(v)) v else as.numeric(v))
}

build_week_frames <- function(wk) {
  f <- file.path(data_dir, sprintf("tracking_week_%d.csv", wk))
  cat("Reading", f, "...\n")
  trk <- fread(f, select = c("gameId", "playId", "nflId", "club", "frameId",
                             "frameType", "event", "playDirection",
                             "x", "y", "s", "dis"))
  trk <- trk[frameType != "AFTER_SNAP"]
  trk <- merge(trk, static[, .(gameId, playId, possessionTeam)],
               by = c("gameId", "playId"))
  # offence always moves toward +x
  trk[playDirection == "left", `:=`(x = 120 - x, y = 160 / 3 - y)]

  fr <- trk[, .(
    ls   = suppressWarnings(min(as.numeric(frameId[event %in% "line_set"]))),
    snap = suppressWarnings(min(as.numeric(frameId[frameType == "SNAP" |
                                                     event %in% "ball_snap"])))
  ), by = .(gameId, playId)]
  fr <- fr[is.finite(snap) & is.finite(ls) & ls < snap]

  trk <- merge(trk, fr, by = c("gameId", "playId"))
  trk <- trk[frameId >= ls & frameId <= snap]
  setorder(trk, gameId, playId, nflId, frameId)

  ball <- trk[is.na(nflId) & frameId == ls,
              .(los = x[1], ball_y = y[1]), by = .(gameId, playId)]
  p <- trk[!is.na(nflId)]
  rm(trk); gc(verbose = FALSE)

  # running totals since lineset, per player
  p[, `:=`(x0 = x[1], y0 = y[1],
           dist = cumsum(fifelse(frameId == ls, 0, dis)),
           maxs = cummax(s), minx = cummin(x)),
    by = .(gameId, playId, nflId)]
  # frames counted back from the snap (0, 0.2, 0.4 s ...) plus the lineset
  p <- p[(snap - frameId) %% frame_step == 0 | frameId == ls]

  p <- merge(p, ball, by = c("gameId", "playId"))
  p <- merge(p, players[, .(nflId, pos = position)], by = "nflId",
             all.x = TRUE)
  p[is.na(pos), pos := "UNK"]
  p[, off := as.integer(club == possessionTeam)]

  feats <- p[, frame_feats(pos, off, x0, y0, x, y, s, dist, maxs, minx,
                           los, ball_y),
             by = .(gameId, playId, frameId)]
  feats <- merge(feats, fr, by = c("gameId", "playId"))
  feats[, `:=`(secs_since_ls = (frameId - ls) / 10,
               secs_to_snap  = (snap - frameId) / 10,   # evaluation only
               is_snap_frame = as.integer(frameId == snap),
               is_ls_frame   = as.integer(frameId == ls))]
  feats[, c("ls", "snap") := NULL]
  cat(sprintf("  week %d: %d plays, %d frames\n", wk,
              uniqueN(feats[, .(gameId, playId)]), nrow(feats)))
  feats
}

if (file.exists(cache_file) && !rebuild_frames) {
  cat("Loading cached frame features from", cache_file, "\n")
  frames <- fread(cache_file)
} else {
  frames <- rbindlist(lapply(weeks, build_week_frames), fill = TRUE)
  fwrite(frames, cache_file)
}
frames <- merge(frames, static, by = c("gameId", "playId"))
frames[, play_clock_now := playClockAtSnap + secs_to_snap]   # seen live

Step 3: the feature matrix and one play, one vote. Neighbouring frames are near copies, so each frame is weighted so that every play counts once in total:

frames[, w := 1 / .N, by = .(gameId, playId)]   # every play gets the same total weight
frames[, w := w / mean(w)]                       # rescaled so the average frame weight is 1
# =============================================================================
# 3. Feature matrix
# =============================================================================
num_feats <- c(
  # situation
  "down", "yardsToGo", "yards_to_endzone", "game_sec_left", "score_diff",
  "off_win_prob",
  # personnel
  "n_rb", "n_te", "n_wr", "extra_blockers",
  # tempo
  "secs_since_ls", "play_clock_now",
  # backfield
  "qb_depth", "rb_depth", "rb_lat_abs", "rb_dx", "rb_beside_qb",
  "rb_switched_side", "rb_to_strength",
  # receivers
  "n_wide_strong", "n_wide_weak", "max_split", "mean_wide_split",
  "formation_width", "n_attached", "n_backfield",
  # defence
  "box_count", "box_minus_blockers", "n_deep", "deepest_def",
  "safety_depth", "n_overhang", "n_press", "n_def_on_line",
  "n_def_walked_up", "safety_rotation", "deepest_change",
  "def_max_lateral", "def_total_move",
  # motion
  "n_skill_moved", "mot_dist", "mot_speed_now", "mot_max_speed",
  "mot_lateral", "mot_inward", "mot_crossed", "mot_behind_qb")
cat_feats <- c("formation", "alignment", "mot_type", "mot_pos",
               if (use_team) "team")

feat_group <- c(
  setNames(rep("Situation", 6), num_feats[1:6]),
  setNames(rep("Personnel / formation", 6),
           c("n_rb", "n_te", "n_wr", "extra_blockers", "formation",
             "alignment")),
  setNames(rep("Tempo", 2), num_feats[11:12]),
  setNames(rep("Backfield", 7), num_feats[13:19]),
  setNames(rep("Receivers", 7), num_feats[20:26]),
  setNames(rep("Defence", 13), num_feats[27:39]),
  setNames(rep("Motion", 9), c(num_feats[40:46], "mot_type", "mot_pos")),
  team = "Team")

frames <- frames[complete.cases(frames[, .(down, yardsToGo, yards_to_endzone,
                                           game_sec_left, score_diff,
                                           off_win_prob)])]
lump <- function(f, min_n = 200) {
  f <- as.character(f); f[is.na(f) | f == ""] <- "unknown"
  tab <- table(f); f[f %in% names(tab)[tab < min_n]] <- "other"
  factor(f)
}
for (v in cat_feats) set(frames, j = v, value = lump(frames[[v]]))

# linked frames: every play gets the same total weight
frames[, w := 1 / .N, by = .(gameId, playId)]
frames[, w := w / mean(w)]
setorder(frames, week, gameId, playId, frameId)

form <- as.formula(paste("~", paste(c(num_feats, cat_feats),
                                    collapse = " + "), "- 1"))
X <- model.matrix(form, model.frame(form, frames[, c(num_feats, cat_feats),
                                                 with = FALSE],
                                    na.action = na.pass))
col_var <- c(num_feats, cat_feats)[attr(X, "assign")]
names(col_var) <- colnames(X)
y <- frames$rpo

n_plays <- uniqueN(frames[, .(gameId, playId)])
cat(sprintf("\nFrames: %d | plays: %d | RPO plays: %.1f%%\n", nrow(frames),
            n_plays, 100 * frames[is_snap_frame == 1, mean(rpo)]))

Results

Steps 4 to 7: training and testing. Every week is held out in turn, so every play gets a prediction from a model that never saw its game:

for (wk in 1:9) {
  tr <- which(frames$week != wk); te <- which(frames$week == wk)
  n  <- tune_rounds(tr)                       # number of trees, chosen by game-grouped CV
  fit <- xgb.train(params, xgb.DMatrix(X[tr, ], label = y[tr], weight = frames$w[tr]),
                   nrounds = n)
  frames$p_xgb[te] <- predict(fit, xgb.DMatrix(X[te, ]))
}
# =============================================================================
# 4. Metric helpers (all computed per play)
# =============================================================================
auc_roc <- function(y, p) {
  r <- rank(p); n1 <- sum(y == 1); n0 <- sum(y == 0)
  (sum(r[y == 1]) - n1 * (n1 + 1) / 2) / (n1 * n0)
}
auc_pr <- function(y, p) {
  o <- order(p, decreasing = TRUE); y <- y[o]
  sum((cumsum(y) / seq_along(y))[y == 1]) / sum(y)
}
log_loss <- function(y, p) {
  p <- pmin(pmax(p, 1e-15), 1 - 1e-15)
  -mean(y * log(p) + (1 - y) * log(1 - p))
}
bal_acc <- function(y, p, cut) (mean(p[y == 1] >= cut) + mean(p[y == 0] < cut)) / 2
best_cut <- function(y, p) {
  cuts <- seq(0.02, 0.6, 0.01)
  cuts[which.max(sapply(cuts, function(t) bal_acc(y, p, t)))]
}
top10_hit <- function(y, p) {
  o <- order(-p); n <- ceiling(0.1 * length(y)); mean(y[o][1:n])
}
scores <- function(y, p, cut = best_cut(y, p)) data.table(
  plays = length(y), rpo_rate = round(mean(y), 3),
  roc_auc = round(auc_roc(y, p), 3), pr_auc = round(auc_pr(y, p), 3),
  log_loss = round(log_loss(y, p), 4),
  balanced_acc = round(bal_acc(y, p, cut), 3), cutoff = cut,
  top10_hit_rate = round(top10_hit(y, p), 3))
# =============================================================================
# 5. Baseline: logistic regression, one row per play
# =============================================================================
snap_rows <- which(frames$is_snap_frame == 1)
pl <- frames[snap_rows]
base_form <- ~ factor(down) + yardsToGo + yards_to_endzone + score_diff +
  game_sec_left + formation + alignment + n_rb + n_te + n_wr +
  extra_blockers + I(n_skill_moved > 0) - 1
Xb <- model.matrix(base_form, pl)
pl[, p_logit := NA_real_]
for (wk in sort(unique(pl$week))) {
  tr <- which(pl$week != wk); te <- which(pl$week == wk)
  fit <- suppressWarnings(glm.fit(cbind(1, Xb[tr, ]), pl$rpo[tr],
                                  family = binomial()))
  b <- fit$coefficients; b[is.na(b)] <- 0
  set(pl, i = te, j = "p_logit",
      value = plogis(drop(cbind(1, Xb[te, , drop = FALSE]) %*% b)))
}
# =============================================================================
# 6. XGBoost, leave-one-week-out
# =============================================================================
params <- list(objective = "binary:logistic", eval_metric = "logloss",
               eta = 0.1, max_depth = 5, min_child_weight = 2,
               subsample = 0.8, colsample_bytree = 0.7,
               tree_method = "hist")

best_rounds <- function(cv) {
  n <- cv$best_iteration
  if (is.null(n)) n <- cv$early_stop$best_iteration
  if (is.null(n)) n <- which.min(cv$evaluation_log$test_logloss_mean)
  n
}
tune_rounds <- function(idx) {          # inner CV grouped by game
  g <- frames$gameId[idx]; ug <- unique(g)
  gf <- sample(rep_len(seq_len(inner_folds), length(ug)))
  fold_of <- gf[match(g, ug)]
  folds <- lapply(seq_len(inner_folds), function(k) which(fold_of == k))
  dtr <- xgb.DMatrix(X[idx, , drop = FALSE], label = y[idx],
                     weight = frames$w[idx], missing = NA)
  best_rounds(xgb.cv(params = params, data = dtr, nrounds = 1000,
                     folds = folds, early_stopping_rounds = 30, verbose = 0))
}

frames[, p_xgb := NA_real_]
trees <- c()
for (wk in sort(unique(frames$week))) {
  tr <- which(frames$week != wk); te <- which(frames$week == wk)
  n <- tune_rounds(tr); trees <- c(trees, n)
  fit <- xgb.train(params = params,
                   data = xgb.DMatrix(X[tr, , drop = FALSE], label = y[tr],
                                      weight = frames$w[tr], missing = NA),
                   nrounds = n, verbose = 0)
  set(frames, i = te, j = "p_xgb",
      value = predict(fit, xgb.DMatrix(X[te, , drop = FALSE], missing = NA)))
  cat(sprintf("Week %d held out: %d trees\n", wk, n))
}
pl[, p_xgb := frames$p_xgb[snap_rows]]
# =============================================================================
# 7. Testing: model comparison and warning time
# =============================================================================
# per week, at the snap
by_week <- rbindlist(lapply(sort(unique(pl$week)), function(wk) {
  d <- pl[week == wk]
  rbind(cbind(week = wk, model = "logistic regression",
              scores(d$rpo, d$p_logit)),
        cbind(week = wk, model = "xgboost", scores(d$rpo, d$p_xgb)))
}))
fwrite(by_week, file.path(out_dir, "results_by_week.csv"))

summary_tbl <- by_week[, .(roc_auc = round(mean(roc_auc), 3),
                           roc_auc_sd = round(sd(roc_auc), 3),
                           pr_auc = round(mean(pr_auc), 3),
                           balanced_acc = round(mean(balanced_acc), 3),
                           balanced_acc_sd = round(sd(balanced_acc), 3),
                           top10_hit_rate = round(mean(top10_hit_rate), 3)),
                       by = model]
summary_tbl <- rbind(data.table(model = "base rate (always average)",
                                roc_auc = 0.5, roc_auc_sd = NA,
                                pr_auc = round(mean(pl$rpo), 3),
                                balanced_acc = 0.5, balanced_acc_sd = NA,
                                top10_hit_rate = round(mean(pl$rpo), 3)),
                     summary_tbl)
fwrite(summary_tbl, file.path(out_dir, "model_comparison.csv"))
cat("\nModel comparison at the snap (mean across held-out weeks):\n")
print(summary_tbl)

snap_cut <- best_cut(pl$rpo, pl$p_xgb)   # one cutoff, reused below
calib <- pl[, .(bin = cut(p_xgb, c(0, .05, .1, .2, .3, .5, .7, 1),
                          include.lowest = TRUE), p_xgb, rpo)][
  , .(plays = .N, predicted = round(mean(p_xgb), 3),
      actual = round(mean(rpo), 3)), by = bin][order(bin)]
fwrite(calib, file.path(out_dir, "calibration.csv"))
cat("\nCalibration at the snap:\n"); print(calib)

# warning time: same plays at each time point (plays set for 4+ seconds),
# same cutoff as at the snap
frames[, tts := round(secs_to_snap * 10)]
long_plays <- frames[tts == 10 * max(warning_secs), unique(paste(gameId, playId))]
same_plays <- length(long_plays) >= 100
if (!same_plays) cat("\nFewer than 100 plays are set for", max(warning_secs),
                     "seconds; warning time uses all plays at each point.\n")
warn <- rbindlist(lapply(warning_secs, function(k) {
  d <- frames[tts == 10 * k]
  if (nrow(d) < 50 || length(unique(d$rpo)) < 2) return(NULL)
  dl <- if (same_plays) d[paste(gameId, playId) %in% long_plays] else d
  cbind(secs_before_snap = k,
        scores(dl$rpo, dl$p_xgb, snap_cut)[, .(plays, roc_auc, pr_auc,
                                               balanced_acc, top10_hit_rate)],
        roc_auc_all_plays = round(auc_roc(d$rpo, d$p_xgb), 3),
        plays_all = nrow(d))
}))
fwrite(warn, file.path(out_dir, "warning_time.csv"))
cat("\nWarning time", if (same_plays) paste0("(same plays, all set for ", max(warning_secs), "+ seconds)") else "", ":\n")
print(warn)
save_plot(ggplot(warn, aes(secs_before_snap, balanced_acc)) +
            geom_line(colour = "#D55E00", linewidth = 1) + geom_point() +
            scale_x_reverse(breaks = warn$secs_before_snap,
                            labels = ifelse(warn$secs_before_snap == 0, "snap",
                                            paste0(warn$secs_before_snap, "s"))) +
            labs(x = "Seconds before the snap",
                 y = "Balanced accuracy (held-out weeks)",
                 title = "How early the model can warn a defence"),
          "warning_time.png")

fwrite(frames[, .(gameId, playId, week, frameId, secs_since_ls, secs_to_snap,
                  is_snap_frame, rpo, p_xgb = round(p_xgb, 4))],
       file.path(out_dir, "xgb_oof_frame_predictions.csv"))
fwrite(pl[, .(gameId, playId, week, team, rpo,
              p_logit = round(p_logit, 4), p_xgb = round(p_xgb, 4))][
  order(-p_xgb)], file.path(out_dir, "play_predictions_at_snap.csv"))

XGBoost vs the baseline

kable(cmp[, .(Model = model, `ROC-AUC` = roc_auc, `± sd` = roc_auc_sd,
              `PR-AUC` = pr_auc, `Balanced accuracy` = balanced_acc,
              `Top-10% hit rate` = top10_hit_rate)],
      caption = "Mean across the 9 held-out weeks, at the snap")
Mean across the 9 held-out weeks, at the snap
Model ROC-AUC ± sd PR-AUC Balanced accuracy Top-10% hit rate
base rate (always average) 0.500 NA 0.103 0.500 0.103
logistic regression 0.756 0.020 0.242 0.707 0.277
xgboost 0.868 0.014 0.466 0.795 0.473

How to read this table. Each number is averaged over the 9 weeks the model never trained on.

  • ROC-AUC: pick one random RPO and one random non-RPO. ROC-AUC is how often the model gives the RPO the higher probability. 0.5 is a coin flip; 1.0 is perfect.
  • PR-AUC: how clean the model’s top predictions are. It starts at the base rate (10.3%) for a model that knows nothing, so it is the toughest measure for a rare play like an RPO.
  • Balanced accuracy: the average of the share of RPOs caught and the share of non-RPOs correctly cleared. It is not fooled by RPOs being rare; 50% is a coin flip.
  • Top-10% hit rate: of the 10% of plays the model is most suspicious of, the share that really were RPOs.

XGBoost reaches a ROC-AUC of 0.868 and balanced accuracy of 79.5%, against 0.756 and 70.7% for the logistic regression. Of the 10% of plays it rates most likely, 47% are RPOs, about 4.6 times the base rate. The gap holds in every held-out week:

p <- ggplot(wk, aes(week, roc_auc, colour = model)) +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_x_continuous(breaks = 1:9) +
  scale_colour_manual(values = c(xgboost = "#D55E00",
                                 `logistic regression` = "#0072B2")) +
  labs(x = "Held-out week", y = "ROC-AUC", colour = NULL)
ggplotly(p)

How to read this chart. Each point is one week of games the model never saw while training. The higher the line, the better the model ranks RPOs above other plays. Orange (XGBoost) sits above blue (the baseline) in every week, and both lines are fairly flat, so the result is not driven by one lucky week.

Are the probabilities honest?

When the model says 25%, about a quarter of those plays should be RPOs.

p <- ggplot(cal, aes(predicted, actual)) +
  geom_abline(linetype = 2, colour = "grey50") +
  geom_point(aes(size = plays, text = paste0(bin, "<br>plays: ", plays)),
             colour = "#D55E00") +
  scale_x_continuous(labels = scales::percent, limits = c(0, 0.85)) +
  scale_y_continuous(labels = scales::percent, limits = c(0, 0.85)) +
  labs(x = "Predicted chance of RPO", y = "Actual RPO rate", size = "Plays")
ggplotly(p, tooltip = "text")

How to read this chart. Plays are grouped by the probability the model gave them (left to right), and each point shows how often those plays really were RPOs (bottom to top). Bigger points hold more plays. On the dashed line the model is exactly right; above it the model was too cautious; below it, too confident.

The points sit close to the diagonal. The model is slightly cautious between 20% and 70% (for example, plays rated 59% were RPOs 68% of the time) and slightly over-confident in the top bin, which only holds 81 plays.

How early can a defence be warned?

w <- melt(warn, id.vars = "secs_before_snap",
          measure.vars = c("roc_auc", "balanced_acc"))
w[, variable := fifelse(variable == "roc_auc", "ROC-AUC", "Balanced accuracy")]
p <- ggplot(w, aes(secs_before_snap, value, colour = variable)) +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_x_reverse(breaks = warn$secs_before_snap,
                  labels = ifelse(warn$secs_before_snap == 0, "snap",
                                  paste0(warn$secs_before_snap, "s"))) +
  scale_colour_manual(values = c("#D55E00", "#0072B2")) +
  labs(x = "Seconds before the snap", y = NULL, colour = NULL)
ggplotly(p)

On the same 11,041 plays (all set for at least 4 seconds), ROC-AUC is still 0.847 4 seconds before the snap, against 0.861 at the snap. Almost all of the signal is there as soon as the offence lines up, which gives a defence time to check into a call.

How to read this chart. Moving left means asking the model earlier, with fewer seconds of pre-snap information. Higher is better on both lines. A line that stays flat as you move left means the model already knows most of what it will know at the snap.

What it means for a coach. Once the offence is set, the warning is nearly as good as it will ever get. That leaves several seconds to signal a check, such as keeping the conflict defender home or rotating a safety.

What drives the model (SHAP)

SHAP splits each prediction into how much every feature pushed it toward or away from an RPO:

\[\text{score} = \text{average} + \text{effect}_1 + \text{effect}_2 + \dots\]

SHAP in plain English. Every play starts from the same place: the average play, about a 10% chance of an RPO. Each feature then adds or subtracts a little. A positive SHAP value pushes the play toward an RPO, and a negative one pushes it away. The values are on the model’s internal log-odds scale, which adds up neatly. This table converts them into something easier to picture:

SHAP value Effect on the odds of an RPO
+1.0 about 2.7 × more likely
+0.5 about 1.6 × more likely
+0.25 about 1.3 × more likely
0 no effect
−0.5 about 0.6 × (40% less likely)
−1.0 about 0.37 × (63% less likely)

Step 8: the SHAP values. The final model (trained on all nine weeks) splits each prediction into one contribution per column, and the dummy columns are added back into their variable:

s <- predict(final, xgb.DMatrix(X[rows, ]), predcontrib = TRUE)  # one value per column
# add dummy columns back into their variable, e.g. every formation level -> "formation"
g <- sapply(vars, function(v) rowSums(s[, col_var == v, drop = FALSE]))
# =============================================================================
# 8. Final model on all weeks + SHAP
# =============================================================================
final <- xgb.train(params = params,
                   data = xgb.DMatrix(X, label = y, weight = frames$w,
                                      missing = NA),
                   nrounds = round(mean(trees)), verbose = 0)
invisible(xgb.save(final, file.path(out_dir, "rpo_xgb_model.json")))

vars <- c(num_feats, cat_feats)
shap_for <- function(rows) {
  s <- predict(final, xgb.DMatrix(X[rows, , drop = FALSE], missing = NA),
               predcontrib = TRUE)
  base_col <- setdiff(colnames(s), colnames(X))   # "BIAS" or "(Intercept)"
  if (length(base_col) != 1) base_col <- colnames(s)[ncol(s)]
  baseline <- s[1, base_col]
  s <- s[, colnames(X), drop = FALSE]
  # one SHAP value per original variable (dummy columns summed)
  g <- sapply(vars, function(v)
    rowSums(s[, names(col_var)[col_var == v], drop = FALSE]))
  if (length(rows) == 1) g <- matrix(g, nrow = 1, dimnames = list(NULL, vars))
  list(raw = s, grp = g, baseline = baseline)
}

si <- sample(nrow(X), min(shap_sample, nrow(X)))
sh <- shap_for(si)
X_grp <- as.data.frame(frames[si, ..vars])
sv     <- shapviz(sh$grp, X = X_grp, baseline = sh$baseline)
sv_raw <- shapviz(sh$raw, X = as.data.frame(X[si, , drop = FALSE]),
                  baseline = sh$baseline)

imp <- sort(colMeans(abs(sh$grp)), decreasing = TRUE)
imp_tbl <- data.table(variable = names(imp),
                      group = unname(feat_group[names(imp)]),
                      mean_abs_shap = round(imp, 4))
imp_tbl[is.na(group), group := "Other"]
fwrite(imp_tbl, file.path(out_dir, "shap_importance.csv"))

# importance chart, beeswarm, feature groups
save_plot(sv_importance(sv, kind = "bar", max_display = 20) +
            ggtitle("Which features matter most (mean |SHAP|)"),
          "shap_importance.png", h = 7)
save_plot(sv_importance(sv_raw, kind = "beeswarm", max_display = 20) +
            ggtitle("Do high or low values raise the chance of an RPO?"),
          "shap_beeswarm.png", h = 7)
gt <- imp_tbl[, .(v = sum(mean_abs_shap)), by = group][order(v)]
save_plot(ggplot(gt, aes(v, factor(group, levels = group))) +
            geom_col(fill = "#E69F00") +
            labs(x = "Sum of mean |SHAP| (log-odds)", y = NULL,
                 title = "Which kind of information matters"),
          "shap_feature_groups.png")

# dependence plots: where the risk jumps
for (v in head(intersect(names(imp), num_feats), 6))
  save_plot(sv_dependence(sv, v = v, color_var = "formation") +
              ggtitle(paste("Where the risk changes:", v)),
            paste0("shap_dependence_", v, ".png"), w = 7)

# waterfall charts: why single plays were flagged (frame at the snap)
picks <- list(
  correct_rpo_call = pl[rpo == 1][which.max(p_xgb)],
  false_alarm      = pl[rpo == 0][which.max(p_xgb)],
  missed_rpo       = pl[rpo == 1][which.min(p_xgb)])
for (nm in names(picks)) {
  k <- picks[[nm]]
  r <- which(frames$gameId == k$gameId & frames$playId == k$playId &
               frames$is_snap_frame == 1)
  s1 <- shap_for(r)
  sv1 <- shapviz(s1$grp, X = as.data.frame(frames[r, ..vars]),
                 baseline = s1$baseline)
  save_plot(sv_waterfall(sv1, row_id = 1, max_display = 12) +
              ggtitle(sprintf("%s: game %s, play %s (held-out p = %.2f)",
                              gsub("_", " ", nm), k$gameId, k$playId,
                              k$p_xgb)),
            paste0("shap_waterfall_", nm, ".png"))
}

Which features matter most

How to read this chart. Each bar is the average size of a feature’s push, in either direction, over all frames. A long bar means the feature changes predictions a lot; it does not say whether it pushes toward or away from an RPO (the next chart does that). Dummy columns such as each formation are added together into one bar.

if (has_ex) {
  ib <- data.table(feature = names(sg), v = colMeans(abs(sg)))[order(-v)][1:20]
  ib[, `:=`(label = lab(feature),
            group = glossary$group[match(feature, glossary$feature)])]
  ib[, label := factor(label, levels = rev(label))]
  p <- ggplot(ib, aes(v, label, fill = group,
                      text = paste0(label, "<br>average push: ", round(v, 3)))) +
    geom_col(width = 0.7) +
    scale_fill_manual(values = c(Situation = "#0072B2", Backfield = "#D55E00",
                                 Receivers = "#009E73", `Personnel / formation` = "#CC79A7",
                                 Team = "#E69F00", Defence = "#56B4E9",
                                 Motion = "#F0E442", Tempo = "#999999")) +
    labs(x = "Average size of push (mean |SHAP|, log-odds)", y = NULL, fill = NULL)
  ggplotly(p, tooltip = "text")
} else img(file.path(out, "shap_importance.png"))

The same bars added up by type of information:

Formation is the strongest single feature, followed by offensive team, down, receiver splits and the running back’s position relative to the quarterback. By group, situation and backfield alignment carry the most weight, then receiver spacing and formation. Motion and the defence’s look matter far less: the RPO is given away by how the offence lines up, not by what moves afterwards.

What it means for a coach. Read the formation and the backfield first. Shotgun with the back level with the quarterback on 1st or 2nd down is where most RPOs come from. The defence’s own alignment barely changes what the offence calls.

Do high or low values raise the chance?

How to read this chart. Every dot is one frame. Its left-right position is that feature’s SHAP value for that frame: right of the centre line pushes toward an RPO, left pushes away. The colour is the feature’s value: yellow = high, purple = low. For yes/no rows such as Formation: SHOTGUN or Offence: GB, yellow means “yes”. A row that spreads far to both sides is a feature that can swing a prediction a lot.

if (has_ex) {
  S <- as.matrix(scol); colnames(S) <- lab(names(scol))
  Xv <- as.data.frame(scolx); names(Xv) <- colnames(S)
  sv_importance(shapviz(S, X = Xv), kind = "beeswarm", max_display = 20) +
    labs(x = "SHAP value (right = toward an RPO)")
} else img(file.path(out, "shap_beeswarm.png"))

Reading a few rows:

  • Formation: SHOTGUN: yellow dots (shotgun) sit to the right and purple dots (not shotgun) to the left. Shotgun raises the chance of an RPO; any other formation lowers it.
  • down: purple (1st down) is right and orange/yellow (3rd and 4th down) is far left. Late downs push hard away from an RPO.
  • Avg receiver split: yellow (wide splits) stretches far to the right. Wide receivers lined up far from the ball push toward an RPO.
  • Yards to go: purple (short yardage) is on the right and long yardage on the left.
  • Offence: GB / CLE / LV: the yellow dots show that being Green Bay pushes toward an RPO, while Cleveland and Las Vegas push hard away. That is team habit, not a tell in the look itself.

Where the risk jumps

How to read these charts. The bottom axis is the feature’s value; the side axis is its SHAP value, so its push toward (+) or away from (−) an RPO. Each dot is one frame, with one panel per formation so the formations don’t hide each other. The dashed line is zero: dots above it raise the chance of an RPO, dots below lower it. Look for where the dots cross that line, which is where the feature switches from lowering to raising the chance. Every panel uses the same scale, and the number of frames is shown in each panel title. Panels with few frames (jumbo, wildcat) should not be over-read.

RB depth vs QB

RB depth vs QB is the running back’s depth compared with the quarterback (negative = behind him). The risk peaks when the back is level with or up to about a yard behind the QB, the classic shotgun mesh, and falls sharply once he is beside or ahead of the QB.

RB side vs strength

+1 means the back lines up on the side with more receivers. That raises the chance of an RPO; lining up away from the strength lowers it. A likely reason: the run goes one way while the throw goes to the receiver side.

Receiver splits

The chance climbs steeply as the average split goes from about 10 to 15 yards. Wide splits pull defenders out of the box.

Down

1st down is the most RPO-friendly and 2nd down is still positive. 3rd and 4th down push strongly away, and the push is strongest from shotgun: a shotgun look on 3rd down usually means a pass, not an RPO.

Yards to go

RPOs live on 1st and 2nd down and short yardage, and almost disappear on 3rd and long.

QB depth

Shotgun depth (about 5 yards) pushes toward an RPO; under center pushes away.

Why single plays were flagged

How to read these charts. A waterfall explains one play (the feature names are the code names from the glossary above). It starts at the bottom with E[f(x)], the average play (about −2.2 on the log-odds scale, roughly a 10% chance). Each bar then adds (yellow) or subtracts (red) one feature’s push, biggest first, until it reaches f(x) at the top, the play’s final score. To turn the final score into a probability: 0 is 50%, +1 is about 73%, +2 is about 88%, and −2.6 is about 7%. “Other features” groups the many small pushes. These charts use the final model trained on all weeks, so the top value can differ slightly from the held-out probability in the title.

Correct RPO call

Wide splits, short yardage, the back on the strength side and shotgun all push this play toward an RPO.

False alarm

This play looked exactly like an RPO before the snap: shotgun, wide splits, a back level with the QB, short yardage. That is the nature of an RPO; the same look is used for plain runs and passes.

Missed RPO

An under-center, singleback RPO from a team that rarely runs them. Plays like this are rare, so the model gives them a very low chance.

The tells: what coaches should watch for

Step 9: the tells. Readable conditions such as “Shotgun” or “RB to receiver strength” are combined, up to three at a time, from the features SHAP ranks highest. Each look needs at least 50 plays and a lift of 1.5 or more; near-duplicate looks are merged.

# =============================================================================
# 9. Tells: looks built from the top SHAP features
# =============================================================================
# Readable conditions. Each one belongs to a model variable; only those whose
# variable ranks in the top `tell_top_vars` by SHAP are used.
under_center <- c("I_FORM", "SINGLEBACK", "JUMBO")
conds <- list(
  list("Shotgun",                     "formation",       function(d) d$formation == "SHOTGUN"),
  list("Pistol",                      "formation",       function(d) d$formation == "PISTOL"),
  list("Under center",                "formation",       function(d) d$formation %in% under_center),
  list("2x2 receivers",               "alignment",       function(d) d$alignment == "2x2"),
  list("3x1 receivers",               "alignment",       function(d) d$alignment == "3x1"),
  list("RB beside QB",                "rb_beside_qb",    function(d) d$rb_beside_qb == 1),
  list("RB level with QB (within 1.5 yd)", "rb_dx",      function(d) !is.na(d$rb_dx) & abs(d$rb_dx) <= 1.5),
  list("RB directly behind QB",       "rb_lat_abs",      function(d) !is.na(d$rb_lat_abs) & d$rb_lat_abs < 1 & d$rb_dx < -1.5),
  list("RB to receiver strength",     "rb_to_strength",  function(d) d$rb_to_strength == 1),
  list("RB away from strength",       "rb_to_strength",  function(d) d$rb_to_strength == -1),
  list("Wide splits (avg 12+ yd)",    "mean_wide_split", function(d) d$mean_wide_split >= 12),
  list("Tight splits (avg < 9 yd)",   "mean_wide_split", function(d) d$mean_wide_split > 0 & d$mean_wide_split < 9),
  list("Widest receiver 15+ yd out",  "max_split",       function(d) !is.na(d$max_split) & d$max_split >= 15),
  list("Formation 30+ yd wide",       "formation_width", function(d) d$formation_width >= 30),
  list("TE attached to the line",     "n_attached",      function(d) d$n_attached >= 1),
  list("No TE attached",              "n_attached",      function(d) d$n_attached == 0),
  list("11 personnel",                "n_te",            function(d) d$n_rb == 1 & d$n_te == 1),
  list("1st or 2nd down",             "down",            function(d) d$down <= 2),
  list("3rd or 4th down",             "down",            function(d) d$down >= 3),
  list("Short yardage (3 or less)",   "yardsToGo",       function(d) d$yardsToGo <= 3),
  list("4-7 yards to go",             "yardsToGo",       function(d) d$yardsToGo >= 4 & d$yardsToGo <= 7),
  list("6 or fewer in the box",       "box_count",       function(d) d$box_count <= 6),
  list("7+ in the box",               "box_count",       function(d) d$box_count >= 7),
  list("Two-high safeties",           "n_deep",          function(d) d$n_deep >= 2),
  list("Single-high safety",          "n_deep",          function(d) d$n_deep == 1),
  list("Jet motion",                  "mot_type",        function(d) d$mot_type == "jet"),
  list("Any motion",                  "n_skill_moved",   function(d) d$n_skill_moved >= 1),
  list("No motion",                   "n_skill_moved",   function(d) d$n_skill_moved == 0),
  list("Quick snap (< 3 s after set)","secs_since_ls",   function(d) d$secs_since_ls < 3)
)
top_vars <- names(imp)[seq_len(min(tell_top_vars, length(imp)))]
conds <- Filter(function(cd) cd[[2]] %in% top_vars, conds)
cat(sprintf("\nBuilding tells from %d conditions on the top %d SHAP variables\n",
            length(conds), length(top_vars)))

snap_d <- frames[is_snap_frame == 1]
ls_d   <- frames[is_ls_frame == 1][match(paste(snap_d$gameId, snap_d$playId),
                                         paste(gameId, playId))]
eval_conds <- function(d) {
  m <- sapply(conds, function(cd) { v <- cd[[3]](d); v[is.na(v)] <- FALSE; v })
  if (is.null(dim(m))) m <- matrix(m, nrow = nrow(d))
  colnames(m) <- sapply(conds, `[[`, 1); m
}
M_snap <- eval_conds(snap_d)
M_ls   <- eval_conds(ls_d)
yv <- snap_d$rpo; base_rate <- mean(yv); tot_rpo <- sum(yv)
cond_var <- sapply(conds, `[[`, 2)

cands <- list()
for (k in seq_len(min(tell_max_size, length(conds)))) {
  cmb <- combn(length(conds), k)
  for (j in seq_len(ncol(cmb))) {
    ids <- cmb[, j]
    if (anyDuplicated(cond_var[ids])) next   # one condition per variable
    m <- rowSums(M_snap[, ids, drop = FALSE]) == k
    n <- sum(m); if (n < tell_min_plays) next
    r <- sum(yv[m]); lift <- (r / n) / base_rate
    if (lift < tell_min_lift) next
    m_ls <- rowSums(M_ls[, ids, drop = FALSE]) == k
    cands[[length(cands) + 1]] <- data.table(
      ids = list(ids), look = paste(colnames(M_snap)[ids], collapse = " + "),
      plays = n, share_of_plays = n / length(yv),
      rpo_rate = r / n, lift = lift,
      coverage = r / tot_rpo,                       # share of all RPOs
      extra_rpos = (r - n * base_rate) / tot_rpo,   # above what's expected
      visible_at_lineset = mean(m_ls[m]))
  }
}
tells <- rbindlist(cands)
if (nrow(tells)) {
  setorder(tells, -extra_rpos)
  # drop a look that is a near-copy of one already listed: a simpler look
  # about as strong, or one that picks out almost the same plays
  look_rows <- function(ids) which(rowSums(M_snap[, ids, drop = FALSE]) == length(ids))
  keep <- c()
  for (i in seq_len(nrow(tells))) {
    ri <- look_rows(tells$ids[[i]])
    redundant <- any(sapply(keep, function(k) {
      rk <- look_rows(tells$ids[[k]])
      overlap <- length(intersect(ri, rk)) / length(union(ri, rk))
      (all(tells$ids[[k]] %in% tells$ids[[i]]) &&
         tells$lift[k] >= 0.9 * tells$lift[i]) || overlap >= 0.85
    }))
    if (!redundant) keep <- c(keep, i)
    if (length(keep) == tell_n_show) break
  }
  sheet <- tells[keep]

  # which teams use each look most (by RPOs from it)
  sheet[, top_teams := sapply(ids, function(ids) {
    m <- rowSums(M_snap[, ids, drop = FALSE]) == length(ids)
    t <- snap_d[m, .(rpos = sum(rpo), plays = .N), by = team][order(-rpos)]
    paste(sprintf("%s (%d of %d)", t$team, t$rpos, t$plays)[1:min(3, nrow(t))],
          collapse = ", ")
  })]
  sheet[, rank := .I]
  tell_sheet <- sheet[, .(rank, look, plays,
                          share_of_plays = round(share_of_plays, 3),
                          rpo_rate = round(rpo_rate, 3),
                          lift = round(lift, 2),
                          coverage = round(coverage, 3),
                          visible_at_lineset = round(visible_at_lineset, 2),
                          top_teams)]
  fwrite(tell_sheet, file.path(out_dir, "tell_sheet.csv"))
  cat(sprintf("\nTell sheet (overall RPO rate %.1f%%):\n", 100 * base_rate))
  print(tell_sheet[, .(rank, look, plays, rpo_rate, lift, coverage)])

  # team-by-team use of the listed looks
  team_use <- rbindlist(lapply(seq_len(nrow(sheet)), function(i) {
    ids <- sheet$ids[[i]]
    m <- rowSums(M_snap[, ids, drop = FALSE]) == length(ids)
    snap_d[, .(plays_in_look = sum(m[.I]), plays = .N,
               rpo_rate_in_look = round(mean(rpo[m[.I]]), 3)), by = team][
      , `:=`(rank = i, look = sheet$look[i],
             share_in_look = round(plays_in_look / plays, 3))]
  }))
  team_use <- team_use[, .(rank, look, team, plays_in_look, share_in_look,
                           rpo_rate_in_look)][order(rank, -plays_in_look)]
  fwrite(team_use, file.path(out_dir, "tell_team_usage.csv"))

  ts <- copy(tell_sheet)[order(lift)]
  ts[, look := factor(look, levels = look)]
  save_plot(ggplot(ts, aes(lift, look)) +
              geom_col(fill = "#0072B2", width = 0.7) +
              geom_vline(xintercept = 1, linetype = 2, colour = "grey40") +
              geom_text(aes(label = sprintf("%.0f%% of RPOs", 100 * coverage)),
                        hjust = -0.1, size = 3) +
              scale_x_continuous(expand = expansion(mult = c(0, 0.25))) +
              labs(x = "Lift (how many times more likely an RPO)", y = NULL,
                   title = "RPO tells: strength and how often they show up",
                   subtitle = sprintf("Overall RPO rate %.1f%%; label = share of all RPOs from that look",
                                      100 * base_rate)),
            "tell_sheet.png", w = 10, h = 6)
} else {
  cat("\nNo look passed the tell filters; lower tell_min_lift or tell_min_plays.\n")
}

Each look combines the top SHAP features. It is scored two ways:

\[\text{Lift} = \frac{\text{RPO rate when the look appears}}{\text{RPO rate overall}} \qquad \text{Coverage} = \text{share of all RPOs that show the look}\]

How to read this chart. Each bar is one look. Bar length is the lift: how many times more often an RPO happens from that look than on an average play. The dashed line at 1 is “no different from average”. The label at the end is the coverage: the share of all RPOs that came from that look. The most useful tells have both a long bar (strong) and a big label (common).

datatable(tells[, .(Rank = rank, Look = look, Plays = plays,
                    `RPO rate` = rpo_rate, Lift = lift,
                    `Share of all RPOs` = coverage,
                    `Already visible at lineset` = visible_at_lineset,
                    `Teams using it most (RPOs of plays)` = top_teams)],
          rownames = FALSE, options = list(pageLength = 15, dom = "t",
                                           scrollX = TRUE)) |>
  formatPercentage(c("RPO rate", "Share of all RPOs",
                     "Already visible at lineset"), 0)

Table columns. Plays: how often the look appeared. RPO rate: how often it was an RPO. Lift: RPO rate divided by the overall rate. Share of all RPOs: coverage. Already visible at lineset: how often the look was already in place the moment the offence set, so how early a defence can see it. Teams using it most: the three teams with the most RPOs from the look.

Reading the tell sheet:

Which teams use each look

How to read this chart. Each square is one team (columns) and one of the top six looks (rows). Darker orange means that team runs an RPO more often when it shows that look. Teams are sorted from fewest RPOs (left) to most (right). Grey squares have fewer than 20 plays, too few to trust. Hover for the exact numbers. Use the box above the chart to pick two or more teams to compare side by side; clear it to see every team again.

top_looks <- head(tells[order(rank), look], 6)
h <- use[look %in% top_looks]
team_order <- h[, .(r = weighted.mean(rpo_rate_in_look, plays_in_look)),
                by = team][order(r), team]
wrap <- function(x) vapply(x, function(s) paste(strwrap(s, 34), collapse = "<br>"), "")
h[, `:=`(look_w = factor(wrap(look), levels = rev(wrap(top_looks))),
         team = factor(team, levels = team_order))]
h[, hover := paste0("<b>", team, "</b><br>", look, "<br>RPO rate: ",
                    fifelse(plays_in_look < 20, "too few plays",
                            pct(rpo_rate_in_look, 0)),
                    "<br>plays: ", plays_in_look)]
setorder(h, team)
# two layers (enough plays / too few) share one team filter
sd_ok    <- SharedData$new(h[plays_in_look >= 20], key = ~team, group = "teams")
sd_small <- SharedData$new(h[plays_in_look < 20],  key = ~team, group = "teams")
heat <- plot_ly(height = 430) |>
  add_markers(data = sd_ok, x = ~team, y = ~look_w, text = ~hover, hoverinfo = "text",
              marker = list(symbol = "square", size = 24,
                            color = ~rpo_rate_in_look, cmin = 0,
                            cmax = max(h$rpo_rate_in_look),
                            colorscale = list(c(0, "#F2F2F2"), c(1, "#D55E00")),
                            colorbar = list(title = "RPO rate", tickformat = ".0%")),
              showlegend = FALSE) |>
  add_markers(data = sd_small, x = ~team, y = ~look_w, text = ~hover,
              hoverinfo = "text",
              marker = list(symbol = "square", size = 24, color = "#CCCCCC"),
              showlegend = FALSE) |>
  layout(xaxis = list(title = "", tickangle = -90, type = "category",
                      categoryorder = "array", categoryarray = team_order),
         yaxis = list(title = "", type = "category"),
         margin = list(l = 10)) |>
  config(displayModeBar = FALSE)
htmltools::tagList(
  filter_select("team_pick", "Compare teams (pick two or more; leave empty to show all):",
                sd_ok, ~team, multiple = TRUE),
  heat)

The same look means very different things by opponent (grey cells have fewer than 20 plays). GB, PHI, KC, BUF and NYG run RPOs from these looks far more than anyone else, while TB, CLE, LV and NO almost never do. A scouting report should pair each tell with that week’s opponent.

The table below ranks the looks within each team: rank 1 is the look after which that team runs RPOs most often. Sort or filter by team to get an opponent’s own tell list. Lift for team compares the look with that team’s overall RPO rate, so 2.0 means twice as often as the team usually runs RPOs. Looks with at least 20 plays for that team are ranked first; looks with fewer plays are ranked after them and marked Small sample in the last column, because a rate from a handful of plays can be misleading.

pinfo <- fread(file.path(out, "play_info.csv"))
team_rate <- pinfo[, .(team_rpo_rate = mean(rpo)), by = .(team = possessionTeam)]
tu <- merge(use, team_rate, by = "team")
tu[, team_lift := rpo_rate_in_look / team_rpo_rate]
tu[, reliable := plays_in_look >= 20]
setorder(tu, team, -reliable, -rpo_rate_in_look, -plays_in_look)
tu[, team_rank := seq_len(.N), by = team]
tu[, sample := fifelse(reliable, "20+ plays", "Small sample (< 20 plays)")]
datatable(tu[, .(Team = team, `Rank for team` = team_rank, Look = look,
                 `Plays in look` = plays_in_look,
                 `Share of team's plays` = share_in_look,
                 `RPO rate in look` = rpo_rate_in_look,
                 `Team's overall RPO rate` = team_rpo_rate,
                 `Lift for team` = round(team_lift, 2),
                 `League-wide rank` = rank, `Sample size` = sample)],
          rownames = FALSE, filter = "top",
          options = list(pageLength = 15, scrollX = TRUE,
                         order = list(list(0, "asc"), list(1, "asc")))) |>
  formatPercentage(c("Share of team's plays", "RPO rate in look",
                     "Team's overall RPO rate"), 0) |>
  formatStyle("Look", `min-width` = "300px")

Live pre-snap demo

Press a ▶ button to run the play at 0.25×, 0.5×, 1× (real time) or 2× speed, and ❚❚ to pause; any speed button continues from where you paused, so you can also change speed mid-play. Or drag the slider. On the left, players move from lineset to snap, with the offence attacking to the right and the motion player highlighted. On the right is the model’s probability that the play is an RPO, using the held-out prediction from a model that never saw that week. Hover over the line for the top three reasons behind the probability at that moment.

How to read the demo. Left: the field from above at that moment. The line of scrimmage is the dotted line, the offence (orange) attacks to the right, the defence is blue, and the player who goes in motion is green. Right: the model’s probability that this play is an RPO, drawn as the play unfolds. Grey dotted lines mark line set and the moment each offensive player starts moving, detected from the tracking itself rather than the data’s motion tags, which are often recorded once the motion has already finished. Watch for the moments where the orange line jumps: they line up with something changing on the field, and hovering over the dot tells you which features caused the change.

The demo plays are picked and prepared by a second script, rpo_live_demo.R (click Show):

# =============================================================================
# Live pre-snap RPO demo  --  data prep for the RPubs report
# Run once AFTER rpo_project.R (no retraining; about 1-2 minutes).
#
# Picks example plays and saves small files for the animated demo:
#   * RPO plays where the held-out probability climbs most after lineset
#     (with motion or a shift during the pre-snap)
#   * a non-RPO play from a similar look where the probability falls
# For each play it saves every tracking frame from lineset to snap, the
# held-out XGBoost probability, and the top SHAP reasons at each moment.
#
# Packages: data.table, xgboost
# =============================================================================

library(data.table)
library(xgboost)

data_dir <- "data"
out_dir  <- "rpo_output"
use_team <- TRUE        # must match the setting used in rpo_project.R
n_rise   <- 2           # RPO plays where the probability climbs
n_fall   <- 1           # non-RPO plays where it falls
min_secs <- 3           # pre-snap phase must be at least this long
max_secs <- 10          # ... and no longer than this (keeps the demo short)
demo_dir <- file.path(out_dir, "live_demo")
dir.create(demo_dir, showWarnings = FALSE)

# ---- 1. Rebuild the feature matrix exactly as in rpo_project.R --------------
frames <- fread(file.path(out_dir, "frame_features.csv"))
static <- fread(file.path(out_dir, "play_info.csv"))
frames <- merge(frames, static, by = c("gameId", "playId"))
frames[, play_clock_now := playClockAtSnap + secs_to_snap]

num_feats <- c(
  "down", "yardsToGo", "yards_to_endzone", "game_sec_left", "score_diff",
  "off_win_prob", "n_rb", "n_te", "n_wr", "extra_blockers",
  "secs_since_ls", "play_clock_now",
  "qb_depth", "rb_depth", "rb_lat_abs", "rb_dx", "rb_beside_qb",
  "rb_switched_side", "rb_to_strength",
  "n_wide_strong", "n_wide_weak", "max_split", "mean_wide_split",
  "formation_width", "n_attached", "n_backfield",
  "box_count", "box_minus_blockers", "n_deep", "deepest_def",
  "safety_depth", "n_overhang", "n_press", "n_def_on_line",
  "n_def_walked_up", "safety_rotation", "deepest_change",
  "def_max_lateral", "def_total_move",
  "n_skill_moved", "mot_dist", "mot_speed_now", "mot_max_speed",
  "mot_lateral", "mot_inward", "mot_crossed", "mot_behind_qb")
cat_feats <- c("formation", "alignment", "mot_type", "mot_pos",
               if (use_team) "team")
vars <- c(num_feats, cat_feats)

frames <- frames[complete.cases(frames[, .(down, yardsToGo, yards_to_endzone,
                                           game_sec_left, score_diff,
                                           off_win_prob)])]
lump <- function(f, min_n = 200) {
  f <- as.character(f); f[is.na(f) | f == ""] <- "unknown"
  tab <- table(f); f[f %in% names(tab)[tab < min_n]] <- "other"
  factor(f)
}
for (v in cat_feats) set(frames, j = v, value = lump(frames[[v]]))

oof <- fread(file.path(out_dir, "xgb_oof_frame_predictions.csv"))
frames <- merge(frames, oof[, .(gameId, playId, frameId, p_xgb)],
                by = c("gameId", "playId", "frameId"))

# ---- 2. Pick the demo plays --------------------------------------------------
pp <- frames[, .(rpo = rpo[1], week = week[1], team = as.character(team[1]),
                 formation = as.character(formation[1]),
                 secs = max(secs_since_ls),
                 p_ls = p_xgb[which.min(frameId)],
                 p_snap = p_xgb[is_snap_frame == 1][1],
                 moved = max(n_skill_moved)),
             by = .(gameId, playId)]
cand <- pp[secs >= min_secs & secs <= max_secs & moved >= 1 & !is.na(p_snap)]
rise <- cand[rpo == 1 & p_snap >= 0.5][order(-(p_snap - p_ls))][seq_len(n_rise)]
fall <- cand[rpo == 0 & p_ls >= 0.3 &
               formation %in% rise$formation][order(p_snap - p_ls)][seq_len(n_fall)]
demo <- rbind(rise[, type := "RPO - probability climbs"],
              fall[, type := "Not an RPO - probability falls"])
demo <- demo[!is.na(gameId)]
plays_raw <- fread(file.path(data_dir, "plays.csv"),
                   select = c("gameId", "playId", "playDescription", "quarter",
                              "down", "yardsToGo", "possessionTeam",
                              "defensiveTeam", "offenseFormation",
                              "receiverAlignment"))
demo <- merge(demo, plays_raw, by = c("gameId", "playId"), sort = FALSE)
demo[, demo_id := .I]
cat("Demo plays:\n"); print(demo[, .(demo_id, type, gameId, playId, team,
                                     p_ls = round(p_ls, 2),
                                     p_snap = round(p_snap, 2))])

# ---- 3. SHAP reasons at every predicted frame ---------------------------------
model <- xgb.load(file.path(out_dir, "rpo_xgb_model.json"))
d <- frames[demo[, .(gameId, playId)], on = c("gameId", "playId")]
setorder(d, gameId, playId, frameId)
form <- as.formula(paste("~", paste(vars, collapse = " + "), "- 1"))
X <- model.matrix(form, model.frame(form, d[, ..vars], na.action = na.pass))
fn <- tryCatch(xgb.feature_names(model), error = function(e) NULL)
if (!is.null(fn) && !identical(fn, colnames(X)))
  stop("Feature columns differ from the saved model - check use_team matches rpo_project.R")
s <- predict(model, xgb.DMatrix(X, missing = NA), predcontrib = TRUE)
s <- s[, colnames(X), drop = FALSE]
col_var <- vars[attr(X, "assign")]
shap <- sapply(vars, function(v) rowSums(s[, col_var == v, drop = FALSE]))

pretty <- c(
  formation = "Formation", alignment = "Receiver alignment", team = "Offence",
  down = "Down", yardsToGo = "Yards to go", yards_to_endzone = "Yards to end zone",
  game_sec_left = "Time left", score_diff = "Score margin",
  off_win_prob = "Win probability", play_clock_now = "Play clock",
  secs_since_ls = "Time since set", qb_depth = "QB depth",
  rb_depth = "RB depth", rb_dx = "RB depth vs QB", rb_lat_abs = "RB width from QB",
  rb_beside_qb = "RB beside QB", rb_to_strength = "RB side vs strength",
  rb_switched_side = "RB switched sides",
  mean_wide_split = "Avg receiver split", max_split = "Widest split",
  formation_width = "Formation width", n_attached = "TEs attached",
  n_wide_strong = "Receivers to strength", n_wide_weak = "Receivers to weak side",
  box_count = "Defenders in box", n_deep = "Deep safeties",
  safety_depth = "Safety depth", n_def_on_line = "Defenders on line",
  mot_type = "Motion type", mot_pos = "Motion player", mot_dist = "Motion distance",
  n_skill_moved = "Players in motion", mot_inward = "Motion toward ball",
  mot_max_speed = "Motion top speed", n_wr = "WRs", n_te = "TEs", n_rb = "RBs")
lab <- function(v) ifelse(v %in% names(pretty), pretty[v], v)
fmt <- function(x) if (is.numeric(x)) format(round(x, 1), nsmall = 0) else as.character(x)

d[, reasons := sapply(seq_len(.N), function(i) {
  o <- order(-abs(shap[i, ]))[1:3]
  paste(sprintf("%s = %s (%+.2f)", lab(vars[o]),
                sapply(vars[o], function(v) fmt(d[[v]][i])), shap[i, o]),
        collapse = "<br>")
})]
probs <- d[, .(gameId, playId, frameId, secs_since_ls, secs_to_snap,
               p = round(p_xgb, 4), reasons)]
probs <- merge(probs, demo[, .(gameId, playId, demo_id)], by = c("gameId", "playId"))

# ---- 4. Tracking for the demo plays (every frame, lineset to snap) -----------
players <- fread(file.path(data_dir, "players.csv"))[, .(nflId, position)]
trk <- rbindlist(lapply(unique(demo$week), function(wk) {
  t <- fread(file.path(data_dir, sprintf("tracking_week_%d.csv", wk)),
             select = c("gameId", "playId", "nflId", "displayName",
                        "jerseyNumber", "club", "frameId", "frameType",
                        "event", "playDirection", "x", "y", "s", "dis"))
  t[demo[, .(gameId, playId)], on = c("gameId", "playId"), nomatch = NULL]
}))
trk[playDirection == "left", `:=`(x = 120 - x, y = 160 / 3 - y)]
fr <- trk[, .(ls = min(frameId[event %in% "line_set"]),
              snap = min(frameId[frameType == "SNAP" | event %in% "ball_snap"])),
          by = .(gameId, playId)]
trk <- merge(trk, fr, by = c("gameId", "playId"))
trk <- trk[frameId >= ls & frameId <= snap]
los <- trk[is.na(nflId) & frameId == ls, .(gameId, playId, los = x, ball_y = y)]
trk <- merge(trk, los, by = c("gameId", "playId"))
trk <- merge(trk, players, by = "nflId", all.x = TRUE)
trk <- merge(trk, demo[, .(gameId, playId, demo_id, possessionTeam)],
             by = c("gameId", "playId"))
setorder(trk, demo_id, nflId, frameId)
trk[!is.na(nflId), moved := sum(dis[frameId > ls]), by = .(demo_id, nflId)]
mover <- trk[!is.na(nflId) & club == possessionTeam &
               !(position %in% c("QB", "T", "G", "C")),
             .(moved = moved[1]), by = .(demo_id, nflId)][
  order(-moved)][, .SD[1], by = demo_id][moved >= 2]
trk[, side := fifelse(is.na(nflId), "Football",
                      fifelse(club == possessionTeam, "Offence", "Defence"))]
trk[mover, on = c("demo_id", "nflId"), side := "Offence (motion)"]
trk[, `:=`(x_rel = round(x - los, 2), y = round(y, 2),
           secs_since_ls = (frameId - ls) / 10,
           label = fifelse(is.na(position), "", position))]
tracking <- trk[, .(demo_id, gameId, playId, frameId, secs_since_ls, nflId,
                    displayName, jerseyNumber, position = label, side,
                    x_rel, y)]
events <- unique(trk[!is.na(event) & event != "" & frameType != "AFTER_SNAP",
                     .(demo_id, frameId, secs_since_ls, event)])

fwrite(demo[, .(demo_id, type, gameId, playId, week, team, defensiveTeam,
                quarter, down, yardsToGo, offenseFormation, receiverAlignment,
                p_lineset = round(p_ls, 3), p_snap = round(p_snap, 3), rpo,
                playDescription)],
       file.path(demo_dir, "demo_plays.csv"))
fwrite(probs, file.path(demo_dir, "demo_probabilities.csv"))
fwrite(tracking, file.path(demo_dir, "demo_tracking.csv"))
fwrite(events, file.path(demo_dir, "demo_events.csv"))
cat("\nSaved demo files to", normalizePath(demo_dir), "\n")
dplays <- fread(file.path(demo, "demo_plays.csv"))
dprob  <- fread(file.path(demo, "demo_probabilities.csv"))
dtrk   <- fread(file.path(demo, "demo_tracking.csv"))
devt   <- fread(file.path(demo, "demo_events.csv"))

move_speed     <- 1.0   # yards/second that counts as "moving"
move_min_yards <- 2     # ignore players who shuffle less than this in total
side_cols <- c(Offence = "#D55E00", `Offence (motion)` = "#009E73",
               Defence = "#0072B2", Football = "#6B3E26")

make_demo <- function(id) {
  tr <- dtrk[demo_id == id]
  pr <- dprob[demo_id == id][order(frameId)]
  # Event labels: "line set" from the data, then the moment each offensive
  # player actually STARTS moving, found from the tracking itself (the data's
  # man_in_motion / shift tags are often placed when the motion is finished)
  ev <- devt[demo_id == id & event == "line_set", .(frameId, label = "line set")]
  mv <- dtrk[demo_id == id & side %in% c("Offence", "Offence (motion)") &
               !(position %in% c("T", "G", "C", "QB"))][order(nflId, frameId)]
  mv[, speed := sqrt((x_rel - shift(x_rel))^2 + (y - shift(y))^2) * 10, by = nflId]
  mv[, moving := frollapply(speed >= move_speed, 3, all, align = "left"), by = nflId]
  mv[, total := sum(sqrt(diff(x_rel)^2 + diff(y)^2)), by = nflId]
  starts <- mv[total >= move_min_yards & moving == TRUE,
               .(frameId = min(frameId)), by = .(nflId, position)][order(frameId)]
  if (nrow(starts)) {
    # players starting within 0.3 s of each other share one label (a shift)
    starts[, grp := cumsum(c(1, diff(frameId) > 3))]
    starts <- starts[, .(frameId = min(frameId),
                         label = paste(paste(unique(position), collapse = ", "),
                                       if (.N > 1) "start moving" else "starts moving")),
                     by = grp]
    ev <- rbind(ev, starts[, .(frameId, label)])
  }
  # carry the latest prediction forward to every tracking frame
  setkey(pr, frameId)
  fr <- data.table(frameId = sort(unique(tr$frameId)))
  fr <- pr[, .(frameId, p, reasons)][fr, roll = TRUE, on = "frameId"]
  fr[, t := round((frameId - min(frameId)) / 10, 1)]
  tr <- merge(tr, fr[, .(frameId, t)], by = "frameId")
  tr[, hover := fifelse(side == "Football", "Football",
                        paste0(displayName, " (", position, ")"))]
  # growing probability line: each animation frame holds the path so far
  acc <- rbindlist(lapply(fr$t, function(s) fr[t <= s][, step := s]))
  cur <- fr[, .(t, p, reasons, step = t)]

  field <- plot_ly(tr, x = ~x_rel, y = ~y, frame = ~t, ids = ~as.character(nflId),
                   color = ~side, colors = side_cols, type = "scatter",
                   mode = "markers+text", text = ~position,
                   textposition = "top center", textfont = list(size = 9),
                   hovertext = ~hover, hoverinfo = "text",
                   marker = list(size = 11, line = list(width = 1, color = "white"))) |>
    add_segments(x = 0, xend = 0, y = 0, yend = 53.3, inherit = FALSE,
                 line = list(color = "grey", dash = "dot"), showlegend = FALSE,
                 hoverinfo = "none")
  prob <- plot_ly() |>
    add_lines(data = fr, x = ~t, y = ~p, line = list(color = "#DDDDDD", width = 2),
              hoverinfo = "none", showlegend = FALSE) |>
    add_lines(data = acc, x = ~t, y = ~p, frame = ~step,
              line = list(color = "#D55E00", width = 3), showlegend = FALSE,
              hoverinfo = "none") |>
    add_markers(data = cur, x = ~t, y = ~p, frame = ~step,
                marker = list(color = "#D55E00", size = 12), showlegend = FALSE,
                hovertext = ~paste0("<b>", round(100 * p), "% RPO</b><br>", reasons),
                hoverinfo = "text")
  if (nrow(ev)) {
    ev[, t := round((frameId - min(tr$frameId)) / 10, 1)]
    setorder(ev, t)
    ev[, ylab := 0.99 - 0.06 * ((seq_len(.N) - 1) %% 3)]   # stagger labels
    for (k in seq_len(nrow(ev)))
      prob <- prob |> add_segments(x = ev$t[k], xend = ev$t[k], y = 0, yend = 1,
                                   inherit = FALSE, color = I("grey60"),
                                   line = list(color = "grey60", dash = "dot", width = 1),
                                   showlegend = FALSE, hoverinfo = "none")
    prob <- prob |> add_text(data = ev, x = ~t, y = ~ylab, text = ~label,
                             textposition = "bottom right",
                             textfont = list(size = 10, color = "grey30"),
                             showlegend = FALSE, hoverinfo = "none")
  }
  info <- dplays[demo_id == id]
  subplot(field, prob, nrows = 1, widths = c(0.5, 0.5), margin = 0.06,
          titleX = TRUE, titleY = TRUE) |>
    layout(xaxis = list(title = "Yards from the line", range = c(-12, 18),
                        zeroline = FALSE),
           yaxis = list(title = "", range = c(0, 53.3), showticklabels = FALSE),
           xaxis2 = list(title = "Seconds since the offence set",
                         range = c(0, max(fr$t) + 0.2)),
           yaxis2 = list(title = "Chance of RPO", range = c(0, 1),
                         tickformat = ".0%"),
           legend = list(orientation = "h", x = 0, y = 1.02, yanchor = "bottom"),
           margin = list(t = 40)) |>
    animation_opts(frame = 100, transition = 0, redraw = FALSE) |>
    animation_slider(currentvalue = list(prefix = "Seconds since set: "),
                     font = list(color = "rgba(0,0,0,0)")) ->
    widget
  # our own Play buttons at four speeds, plus Pause (plotly's default button
  # cannot pause or change speed). 1x = real time: one frame every 0.1 s.
  play_at <- function(label, ms) list(
    label = label, method = "animate",
    args = list(NULL, list(fromcurrent = TRUE, mode = "immediate",
                           frame = list(duration = ms, redraw = FALSE),
                           transition = list(duration = 0))))
  speeds <- list(play_at("\u25B6 0.25\u00D7", 400), play_at("\u25B6 0.5\u00D7", 200),
                 play_at("\u25B6 1\u00D7", 100), play_at("\u25B6 2\u00D7", 50))
  pause <- list(label = "\u275A\u275A Pause", method = "animate",
                args = list(list(NULL), list(mode = "immediate",
                                             frame = list(duration = 0, redraw = FALSE),
                                             transition = list(duration = 0))))
  # plotly writes its own Play-only menu when the plot is built, so build
  # first and then swap in the Play + Pause pair
  widget <- plotly_build(widget)
  menu <- widget$x$layout$updatemenus[[1]]
  menu$buttons <- c(speeds, list(pause))
  menu$direction <- "left"
  menu$xanchor <- "left"
  menu$pad <- list(t = 60, r = 10)
  widget$x$layout$updatemenus <- list(menu)
  # move the slider right so it does not sit under the buttons
  widget$x$layout$sliders[[1]]$x <- 0.33
  widget$x$layout$sliders[[1]]$len <- 0.67
  widget$height <- 620    # room for the slider and legend
  widget
}

Example 1: RPO - probability climbs

CAR vs SF | Q1, 2nd & 2 | SHOTGUN, 3x1 receivers

Held-out probability 33% at lineset → 86% at the snap. What happened: (6:35) (Shotgun) D.Foreman up the middle to SF 43 for 5 yards (O.Burks).


Example 2: RPO - probability climbs

ARI vs SEA | Q3, 2nd & 10 | SHOTGUN, 3x1 receivers

Held-out probability 10% at lineset → 63% at the snap. What happened: (2:08) (Shotgun) E.Benjamin up the middle to ARZ 32 for 2 yards (C.Barton).


Example 3: Not an RPO - probability falls

HOU vs DEN | Q3, 2nd & 8 | SHOTGUN, 3x1 receivers

Held-out probability 69% at lineset → 21% at the snap. What happened: (2:22) (No Huddle, Shotgun) D.Mills up the middle to HST 13 for 2 yards (C.Sterns).


What pre-snap motion does to the prediction

The live demos raise a natural question: how much does pre-snap motion help or hurt the prediction? The answer has two parts.

mt[, motion := factor(motion, levels = mt[order(rpo_rate), motion])]
p <- ggplot(mt, aes(rpo_rate, motion,
                    text = paste0(motion, "<br>plays: ", format(plays, big.mark = ","),
                                  "<br>RPO rate: ", pct(rpo_rate)))) +
  geom_col(fill = "#0072B2", width = 0.6) +
  geom_vline(xintercept = base_rate, linetype = 2, colour = "grey40") +
  scale_x_continuous(labels = scales::percent) +
  labs(x = "RPO rate (dashed line = all plays)", y = "Motion before the snap")
ggplotly(p, tooltip = "text")

How to read this chart. Each bar is the share of plays that were RPOs, grouped by the type of motion seen before the snap (“none” = no player moved 2 or more yards after the set). Bars past the dashed line are motions that come with RPOs more often than average.

1. The type of motion matters a little. Some motions come with RPOs more often than others (above), but motion features as a group account for only 2% of the model’s total SHAP weight. On its own, the fact that someone moved says little.

ml <- melt(mcs, id.vars = c("play", "plays"), measure.vars = c("rose", "same", "fell"))
ml[, variable := factor(variable, levels = c("fell", "same", "rose"),
                        labels = c("Probability fell", "Stayed about the same",
                                   "Probability rose"))]
ml[, play_lab := paste0(play, " (", format(plays, big.mark = ",", trim = TRUE), " plays)")]
ml[, play := factor(play_lab, levels = unique(play_lab[order(play == "RPO")]))]  # RPO on top
p <- ggplot(ml, aes(value, play, fill = variable,
                    text = paste0(variable, ": ", pct(value, 0)))) +
  geom_col(width = 0.6) +
  geom_text(aes(label = ifelse(value >= 0.06, pct(value, 0), "")),
            position = position_stack(vjust = 0.5), colour = "white", size = 4) +
  scale_fill_manual(values = c(`Probability fell` = "#0072B2",
                               `Stayed about the same` = "#BBBBBB",
                               `Probability rose` = "#D55E00")) +
  scale_x_continuous(labels = scales::percent) +
  labs(x = "Share of plays with motion", y = NULL, fill = NULL) +
  theme(legend.position = "top")
ggplotly(p, tooltip = "text") |> layout(legend = list(orientation = "h", y = 1.25))

How to read this chart. Every play with pre-snap motion is counted once. The bar shows how the model’s probability changed between just before the motion (before any player had moved 2 yards) and 1 second later (or the snap, if sooner): orange = rose, blue = fell, grey = changed by less than 2 points. If motion helps the model, RPOs should be mostly orange and other plays mostly blue.

2. Motion matters through where it puts players. After motion, the probability rose on 39% of RPOs and fell on 14% of other plays. On average, RPOs went from 27% before the motion to 29% after it; other plays went from 8% to 8%. The gap between real RPOs and other plays goes from 19 points before the motion to 21 points after it, so on average motion helps the model tell them apart.

The movement itself carries little weight, but motion changes the alignment: which side is strong, where the running back ends up relative to it, and how wide the receivers are split. Those alignment features are among the model’s strongest, so the probability tends to move when the motion lands, as in the live demos. In short, motion matters to the extent that it reveals the final look.

The motion analysis, the readable SHAP charts, the timing and tell checks and the attention data come from a second short script, rpo_report_extras.R, which retrains nothing (click Show):

# =============================================================================
# Extra results for the RPubs report  --  run once AFTER rpo_project.R
# (and rpo_live_demo.R). No retraining; a few minutes.
#
# Saves to rpo_output/report_extras/:
#   1. shap_sample_*.csv   SHAP values for a sample of frames, so the report
#                          can redraw the SHAP charts with readable labels and
#                          per-formation panels
#   2. motion_*.csv        what pre-snap motion does to the prediction
#   3. timing_*.csv        how much of the warning comes after the coach-to-
#                          player radio cuts out (15 s on the play clock)
#   4. tell_stability.csv  do the tells hold up from early to late weeks?
#   5. attention_*.csv     transformer attention for the wider attention chart
#                          (needs torch and the saved transformer; skipped if
#                          either is missing)
#
# Packages: data.table, xgboost (and torch for part 5)
# =============================================================================

library(data.table)
library(xgboost)

data_dir     <- "data"
out_dir      <- "rpo_output"
use_team     <- TRUE      # must match rpo_project.R
t_step       <- 5         # must match rpo_project.R (transformer section)
shap_n       <- 20000     # frames sampled for the SHAP charts
radio_cutoff <- 15        # coach-to-player radio cuts out at 15 s on the play clock
set.seed(42)
ex_dir <- file.path(out_dir, "report_extras")
dir.create(ex_dir, showWarnings = FALSE)

# ---- Rebuild the feature matrix exactly as in rpo_project.R ------------------
frames <- fread(file.path(out_dir, "frame_features.csv"))
static <- fread(file.path(out_dir, "play_info.csv"))
frames <- merge(frames, static, by = c("gameId", "playId"))
frames[, play_clock_now := playClockAtSnap + secs_to_snap]

num_feats <- c(
  "down", "yardsToGo", "yards_to_endzone", "game_sec_left", "score_diff",
  "off_win_prob", "n_rb", "n_te", "n_wr", "extra_blockers",
  "secs_since_ls", "play_clock_now",
  "qb_depth", "rb_depth", "rb_lat_abs", "rb_dx", "rb_beside_qb",
  "rb_switched_side", "rb_to_strength",
  "n_wide_strong", "n_wide_weak", "max_split", "mean_wide_split",
  "formation_width", "n_attached", "n_backfield",
  "box_count", "box_minus_blockers", "n_deep", "deepest_def",
  "safety_depth", "n_overhang", "n_press", "n_def_on_line",
  "n_def_walked_up", "safety_rotation", "deepest_change",
  "def_max_lateral", "def_total_move",
  "n_skill_moved", "mot_dist", "mot_speed_now", "mot_max_speed",
  "mot_lateral", "mot_inward", "mot_crossed", "mot_behind_qb")
cat_feats <- c("formation", "alignment", "mot_type", "mot_pos",
               if (use_team) "team")
vars <- c(num_feats, cat_feats)

frames <- frames[complete.cases(frames[, .(down, yardsToGo, yards_to_endzone,
                                           game_sec_left, score_diff,
                                           off_win_prob)])]
lump <- function(f, min_n = 200) {
  f <- as.character(f); f[is.na(f) | f == ""] <- "unknown"
  tab <- table(f); f[f %in% names(tab)[tab < min_n]] <- "other"
  factor(f)
}
for (v in cat_feats) set(frames, j = v, value = lump(frames[[v]]))
oof <- fread(file.path(out_dir, "xgb_oof_frame_predictions.csv"))
frames <- merge(frames, oof[, .(gameId, playId, frameId, p_xgb)],
                by = c("gameId", "playId", "frameId"))
setorder(frames, gameId, playId, frameId)

# =============================================================================
# 1. SHAP sample for redrawn charts
# =============================================================================
cat("1. SHAP sample ...\n")
model <- xgb.load(file.path(out_dir, "rpo_xgb_model.json"))
si <- sort(sample(nrow(frames), min(shap_n, nrow(frames))))
d <- frames[si]
form <- as.formula(paste("~", paste(vars, collapse = " + "), "- 1"))
X <- model.matrix(form, model.frame(form, d[, ..vars], na.action = na.pass))
fn <- tryCatch(xgb.feature_names(model), error = function(e) NULL)
if (!is.null(fn) && !identical(fn, colnames(X)))
  stop("Feature columns differ from the saved model - check use_team matches rpo_project.R")
s <- predict(model, xgb.DMatrix(X, missing = NA), predcontrib = TRUE)
base_col <- setdiff(colnames(s), colnames(X))
if (length(base_col) != 1) base_col <- colnames(s)[ncol(s)]
baseline <- s[1, base_col]
s <- s[, colnames(X), drop = FALSE]
col_var <- vars[attr(X, "assign")]

# one SHAP value per original variable (dummy columns summed)
grp <- sapply(vars, function(v) rowSums(s[, col_var == v, drop = FALSE]))
fwrite(as.data.table(grp), file.path(ex_dir, "shap_sample_grouped.csv"))
fwrite(d[, c("gameId", "playId", "frameId", vars), with = FALSE],
       file.path(ex_dir, "shap_sample_values.csv"))

# column-level SHAP (e.g. formationSHOTGUN, teamGB) for the beeswarm
top_cols <- names(sort(colMeans(abs(s)), decreasing = TRUE))[1:min(30, ncol(s))]
fwrite(as.data.table(s[, top_cols, drop = FALSE]),
       file.path(ex_dir, "shap_sample_columns.csv"))
fwrite(as.data.table(X[, top_cols, drop = FALSE]),
       file.path(ex_dir, "shap_sample_column_values.csv"))
fwrite(data.table(baseline = baseline), file.path(ex_dir, "shap_baseline.csv"))

# =============================================================================
# 2. Pre-snap motion
# =============================================================================
cat("2. Motion ...\n")
# motion "starts" at the first frame where a skill player has moved 2+ yards
# since the offence set (n_skill_moved goes from 0 to 1 or more)
mstart <- frames[n_skill_moved >= 1, .(start = min(frameId)), by = .(gameId, playId)]
mf <- merge(frames[, .(gameId, playId, frameId, rpo, p_xgb, is_snap_frame)],
            mstart, by = c("gameId", "playId"))
motion_change <- mf[, {
  before <- p_xgb[frameId < start]
  after  <- p_xgb[frameId >= start + 10 | is_snap_frame == 1]   # 1 s later or snap
  if (length(before) && length(after))
    .(p_before = tail(before, 1), p_after = after[1]) else NULL
}, by = .(gameId, playId, rpo)]
fwrite(motion_change, file.path(ex_dir, "motion_change.csv"))

snap <- frames[is_snap_frame == 1]
motion_type <- snap[, .(plays = .N, rpo_rate = mean(rpo),
                        avg_predicted = mean(p_xgb)),
                    by = .(motion = fifelse(n_skill_moved == 0, "none",
                                            as.character(mot_type)))][order(-rpo_rate)]
fwrite(motion_type, file.path(ex_dir, "motion_by_type.csv"))

# =============================================================================
# 3. Timing: warning window vs the radio cut-off
# =============================================================================
cat("3. Timing ...\n")
tm <- snap[!is.na(playClockAtSnap),
           .(gameId, playId, rpo, set_secs = secs_since_ls,
             clock_at_snap = playClockAtSnap,
             clock_at_set = playClockAtSnap + secs_since_ls)]
# seconds of the set-to-snap window that come after the radio cuts out
tm[, after_cutoff := pmin(set_secs, pmax(0, radio_cutoff - clock_at_snap))]
fwrite(tm, file.path(ex_dir, "timing_plays.csv"))
fwrite(tm[, .(plays = .N,
              median_set_secs = median(set_secs),
              share_set_after_cutoff = mean(clock_at_set <= radio_cutoff),
              share_window_after_cutoff = sum(after_cutoff) / sum(set_secs),
              median_clock_at_snap = median(clock_at_snap))],
       file.path(ex_dir, "timing_summary.csv"))

# =============================================================================
# 4. Tell stability: weeks 1-3 vs 4-6 vs 7-9
# =============================================================================
cat("4. Tell stability ...\n")
under_center <- c("I_FORM", "SINGLEBACK", "JUMBO")
conds <- list(
  "Shotgun"                          = function(d) d$formation == "SHOTGUN",
  "Pistol"                           = function(d) d$formation == "PISTOL",
  "Under center"                     = function(d) d$formation %in% under_center,
  "2x2 receivers"                    = function(d) d$alignment == "2x2",
  "3x1 receivers"                    = function(d) d$alignment == "3x1",
  "RB beside QB"                     = function(d) d$rb_beside_qb == 1,
  "RB level with QB (within 1.5 yd)" = function(d) !is.na(d$rb_dx) & abs(d$rb_dx) <= 1.5,
  "RB directly behind QB"            = function(d) !is.na(d$rb_lat_abs) & d$rb_lat_abs < 1 & d$rb_dx < -1.5,
  "RB to receiver strength"          = function(d) d$rb_to_strength == 1,
  "RB away from strength"            = function(d) d$rb_to_strength == -1,
  "Wide splits (avg 12+ yd)"         = function(d) d$mean_wide_split >= 12,
  "Tight splits (avg < 9 yd)"        = function(d) d$mean_wide_split > 0 & d$mean_wide_split < 9,
  "Widest receiver 15+ yd out"       = function(d) !is.na(d$max_split) & d$max_split >= 15,
  "Formation 30+ yd wide"            = function(d) d$formation_width >= 30,
  "TE attached to the line"          = function(d) d$n_attached >= 1,
  "No TE attached"                   = function(d) d$n_attached == 0,
  "11 personnel"                     = function(d) d$n_rb == 1 & d$n_te == 1,
  "1st or 2nd down"                  = function(d) d$down <= 2,
  "3rd or 4th down"                  = function(d) d$down >= 3,
  "Short yardage (3 or less)"        = function(d) d$yardsToGo <= 3,
  "4-7 yards to go"                  = function(d) d$yardsToGo >= 4 & d$yardsToGo <= 7,
  "6 or fewer in the box"            = function(d) d$box_count <= 6,
  "7+ in the box"                    = function(d) d$box_count >= 7,
  "Two-high safeties"                = function(d) d$n_deep >= 2,
  "Single-high safety"               = function(d) d$n_deep == 1,
  "Jet motion"                       = function(d) d$mot_type == "jet",
  "Any motion"                       = function(d) d$n_skill_moved >= 1,
  "No motion"                        = function(d) d$n_skill_moved == 0,
  "Quick snap (< 3 s after set)"     = function(d) d$secs_since_ls < 3)

tells <- fread(file.path(out_dir, "tell_sheet.csv"))
snap[, period := fcase(week <= 3, "Weeks 1-3", week <= 6, "Weeks 4-6",
                       default = "Weeks 7-9")]
stab <- rbindlist(lapply(seq_len(nrow(tells)), function(i) {
  parts <- strsplit(tells$look[i], " + ", fixed = TRUE)[[1]]
  if (!all(parts %in% names(conds))) return(NULL)
  m <- Reduce(`&`, lapply(parts, function(nm) { v <- conds[[nm]](snap); v[is.na(v)] <- FALSE; v }))
  snap[, .(plays = sum(m[.I]), rpo_rate = mean(rpo[m[.I]]),
           base = mean(rpo)), by = period][
    , `:=`(rank = tells$rank[i], look = tells$look[i], lift = rpo_rate / base)]
}))
fwrite(stab[order(rank, period)], file.path(ex_dir, "tell_stability.csv"))

# =============================================================================
# 5. Transformer attention (optional)
# =============================================================================
tf_dir <- file.path(out_dir, "transformer")
model_file <- file.path(tf_dir, "rpo_transformer_last_fold.pt")
if (requireNamespace("torch", quietly = TRUE) && file.exists(model_file) &&
    file.exists(file.path(tf_dir, "tensor_X.pt"))) {
  cat("5. Transformer attention ...\n")
  library(torch)
  POS_GROUPS <- c("QB", "RB", "WR", "TE", "OL", "DL", "LB", "DB")
  tm_model <- torch_load(model_file)
  tm_model$eval()
  TX  <- torch_load(file.path(tf_dir, "tensor_X.pt"))
  TPM <- torch_load(file.path(tf_dir, "tensor_PM.pt"))
  TFM <- torch_load(file.path(tf_dir, "tensor_FM.pt"))
  TTS <- torch_load(file.path(tf_dir, "tensor_TS.pt"))
  TCX <- torch_load(file.path(tf_dir, "tensor_ctx.pt"))
  keys <- fread(file.path(tf_dir, "tensor_keys.csv"))
  t_max <- TX$size(2)
  tf_oof <- fread(file.path(tf_dir, "transformer_oof_frame_predictions.csv"))
  last_wk <- max(tf_oof$week)
  ex <- tf_oof[week == last_wk & secs_to_snap == 0 & rpo == 1][order(-p_tf)][1:min(3, .N)]
  n_sp <- length(tm_model$space); n_tm <- length(tm_model$time)
  tm_model$space[[n_sp]]$keep_attn <- TRUE
  tm_model$time[[n_tm]]$keep_attn <- TRUE
  dev <- tm_model$parameters[[1]]$device
  players_att <- list(); frames_att <- list()
  for (r in seq_len(nrow(ex))) {
    i <- which(keys$gameId == ex$gameId[r] & keys$playId == ex$playId[r])
    ii <- torch_tensor(i, dtype = torch_long())
    with_no_grad(tm_model(TX[ii, , , ]$to(device = dev), TPM[ii, , ]$to(device = dev),
                          TFM[ii, ]$to(device = dev), TTS[ii, ]$to(device = dev),
                          TCX[ii, ]$to(device = dev)))
    xs  <- as.array(TX[i, t_max, , ])
    pmk <- as.array(TPM[i, t_max, ])
    a_sp <- as.array(tm_model$space[[n_sp]]$attn)[t_max, , pmk, , drop = FALSE]
    players_att[[r]] <- data.table(
      example = r, gameId = ex$gameId[r], playId = ex$playId[r], p = ex$p_tf[r],
      yards_from_line = xs[, 1] * 10, yards_across = xs[, 2] * 10,
      side = fifelse(xs[, 10] == 1, "Offence", "Defence"),
      position = POS_GROUPS[max.col(xs[, 11:18], ties.method = "first")],
      attention = apply(a_sp, 4, mean))[pmk]
    a_t <- as.array(tm_model$time[[n_tm]]$attn)[1, , t_max, , drop = TRUE]
    frames_att[[r]] <- data.table(
      example = r, gameId = ex$gameId[r], playId = ex$playId[r],
      secs_before_snap = (t_max - seq_len(t_max)) * t_step / 10,
      attention = colMeans(matrix(a_t, ncol = t_max)))[as.vector(as.array(TFM[i, ]))]
  }
  fwrite(rbindlist(players_att), file.path(ex_dir, "attention_players.csv"))
  fwrite(rbindlist(frames_att), file.path(ex_dir, "attention_frames.csv"))
} else {
  cat("5. Skipped transformer attention (torch or the saved transformer not found);",
      "the report will use the saved attention image instead.\n")
}

cat("\nSaved report extras to", normalizePath(ex_dir), "\n")

The transformer: does reading frames in order help?

Why include a transformer?

XGBoost only sees what we chose to measure, such as the running back’s depth or the average receiver split. Those features carry decades of football knowledge, but they can miss things nobody thought to measure. A transformer is the type of model behind modern language AI, and SumerSports released one for this Big Data Bowl that learns straight from player tracking. It was worth testing for three reasons:

  • It learns its own features. It reads every player’s position, speed and direction directly, so it could find tells we never wrote down, such as how one receiver lines up relative to his defender.
  • It reads the play in order. XGBoost sees the history of a play only through summaries like “motion so far”. A transformer sees the sequence itself, so the timing and order of a shift or a motion can matter.
  • It explains itself differently. Its attention shows which players and which moments it focused on, a second view of the play alongside SHAP.

How it works

  1. Players become tokens. At every frame (every 0.5 s), each of the 22 players is described by position relative to the ball, speed, acceleration, direction, body orientation, distance moved since lineset, offence or defence, and position group.
  2. Attention between players. Every player “looks at” every other player and learns which relationships matter, such as running back to quarterback, or receiver to the defender across from him.
  3. A summary of the frame. The 22 players are combined into one description of the frame, weighted toward the players that matter most.
  4. Attention across frames. Each frame looks back at the earlier frames (never ahead), so the model follows how the look develops while staying live.
  5. A probability at every frame. The same leave-one-week-out testing and one-play-one-vote weighting as XGBoost, so the two are compared on equal terms.

Step 10: the transformer code (click Show), built with R’s torch and following the same idea as SumerSports’ SportsTrackingTransformer:

# =============================================================================
# 10. Transformer (second model)
# =============================================================================
# Reads the frames of each play in order. Each frame = 22 player tokens
# (position, speed, direction, role). Attention BETWEEN PLAYERS learns how
# they sit relative to each other; attention ACROSS FRAMES (causal, so only
# the current and earlier frames) learns how the look develops, keeping the
# prediction live. Same linked-frame handling and leave-one-week-out testing
# as XGBoost, then compared on the same plays. Kept only if it beats XGBoost.
if (run_transformer) {
  library(torch)
  tf_dir <- file.path(out_dir, "transformer")
  dir.create(tf_dir, showWarnings = FALSE)
  torch_manual_seed(42)
  device <- if (cuda_is_available()) torch_device("cuda") else torch_device("cpu")
  cat("\nTransformer: training on", device$type, "\n")

  POS_GROUPS <- c("QB", "RB", "WR", "TE", "OL", "DL", "LB", "DB")
  pos_group <- function(p) fcase(
    p == "QB", "QB", p %in% c("RB", "FB"), "RB", p == "WR", "WR", p == "TE", "TE",
    p %in% c("T", "G", "C", "OT", "OG", "OL"), "OL",
    p %in% c("DE", "DT", "NT", "DL"), "DL",
    p %in% c("ILB", "OLB", "MLB", "LB"), "LB",
    p %in% c("CB", "SS", "FS", "S", "DB"), "DB", default = "WR")
  PLAYER_FEATS <- c("x_rel", "y_rel", "s", "a", "dir_sin", "dir_cos",
                    "o_sin", "o_cos", "dist", "is_off", paste0("pos_", POS_GROUPS))
  CTX_FEATS <- c("down", "yardsToGo", "yards_to_endzone", "score_diff",
                 "game_sec_left", "off_win_prob")
  N_P <- 22

  # =============================================================================
  # 10.1 Build player tensors: play x frame x player x feature
  # =============================================================================
  info    <- fread(file.path(out_dir, "play_info.csv"))
  players_tf <- players[, .(nflId, position)]

  build_week <- function(wk) {
    f <- file.path(data_dir, sprintf("tracking_week_%d.csv", wk))
    cat("Reading", f, "...\n")
    trk <- fread(f, select = c("gameId", "playId", "nflId", "club", "frameId",
                               "frameType", "event", "playDirection",
                               "x", "y", "s", "a", "dis", "o", "dir"))
    trk <- trk[frameType != "AFTER_SNAP"]
    trk <- merge(trk, info[week == wk, .(gameId, playId, possessionTeam)],
                 by = c("gameId", "playId"))
    left <- trk$playDirection == "left"
    trk[left, `:=`(x = 120 - x, y = 160 / 3 - y,
                   o = (o + 180) %% 360, dir = (dir + 180) %% 360)]

    fr <- trk[, .(
      ls   = suppressWarnings(min(as.numeric(frameId[event %in% "line_set"]))),
      snap = suppressWarnings(min(as.numeric(frameId[frameType == "SNAP" |
                                                       event %in% "ball_snap"])))
    ), by = .(gameId, playId)]
    fr <- fr[is.finite(snap) & is.finite(ls) & ls < snap]
    trk <- merge(trk, fr, by = c("gameId", "playId"))
    trk <- trk[frameId >= ls & frameId <= snap]
    setorder(trk, gameId, playId, nflId, frameId)
    trk[!is.na(nflId), dist := cumsum(fifelse(frameId == ls, 0, dis)),
        by = .(gameId, playId, nflId)]
    # keep frames every t_step back from the snap, last t_max of them
    trk <- trk[(snap - frameId) %% t_step == 0 &
                 (snap - frameId) / t_step < t_max]
    ball <- trk[is.na(nflId) & frameId == snap,
                .(los = x[1], ball_y = y[1]), by = .(gameId, playId)]
    p <- merge(trk[!is.na(nflId)], ball, by = c("gameId", "playId"))
    rm(trk); gc(verbose = FALSE)

    p <- merge(p, players_tf, by = "nflId", all.x = TRUE)
    p[, grp := pos_group(position)]
    p[, `:=`(is_off = as.numeric(club == possessionTeam),
             x_rel = (x - los) / 10, y_rel = (y - ball_y) / 10,
             s = s / 5, a = a / 5, dist = dist / 10,
             dir_sin = sin(dir * pi / 180), dir_cos = cos(dir * pi / 180),
             o_sin = sin(o * pi / 180), o_cos = cos(o * pi / 180))]
    for (g in POS_GROUPS) set(p, j = paste0("pos_", g),
                              value = as.numeric(p$grp == g))
    for (cc in PLAYER_FEATS) set(p, which(is.na(p[[cc]])), cc, 0)

    # index: play, frame slot (right-aligned so slot t_max = snap), player slot
    keys <- unique(p[, .(gameId, playId, ls, snap)])
    keys[, pi := .I]
    p <- merge(p, keys[, .(gameId, playId, pi)], by = c("gameId", "playId"))
    p[, ti := t_max - (snap - frameId) / t_step]
    setorder(p, pi, ti, -is_off, grp, y)
    p[, pj := seq_len(.N), by = .(pi, ti)]
    p <- p[pj <= N_P]

    n <- nrow(keys); nf <- length(PLAYER_FEATS)
    X  <- array(0, c(n, t_max, N_P, nf))
    PM <- array(FALSE, c(n, t_max, N_P))
    idx <- cbind(p$pi, p$ti, p$pj)
    for (k in seq_len(nf)) X[cbind(idx, k)] <- p[[PLAYER_FEATS[k]]]
    PM[idx] <- TRUE
    FM <- apply(PM, c(1, 2), any)                             # frame present
    TS <- matrix(rep(seq_len(t_max), each = n), n)            # secs since lineset
    TS <- ((keys$snap - keys$ls)[row(TS)] / 10 - (t_max - TS) * t_step / 10) / 5

    keys <- merge(keys, info[, c("gameId", "playId", "rpo", "week", "team",
                                 CTX_FEATS), with = FALSE],
                  by = c("gameId", "playId"), sort = FALSE)
    setorder(keys, pi)
    ctx <- as.matrix(keys[, .(down / 4, yardsToGo / 10, yards_to_endzone / 100,
                              score_diff / 14, game_sec_left / 3600,
                              off_win_prob)])
    ctx[is.na(ctx)] <- 0
    cat(sprintf("  week %d: %d plays\n", wk, n))
    list(X = torch_tensor(X, dtype = torch_float()),
         PM = torch_tensor(PM, dtype = torch_bool()),
         FM = torch_tensor(FM, dtype = torch_bool()),
         TS = torch_tensor(TS, dtype = torch_float()),
         ctx = torch_tensor(ctx, dtype = torch_float()),
         keys = keys[, .(gameId, playId, week, team, rpo)])
  }

  tensor_names <- c("X", "PM", "FM", "TS", "ctx")
  tensor_files <- file.path(tf_dir, paste0("tensor_", tensor_names, ".pt"))
  keys_file <- file.path(tf_dir, "tensor_keys.csv")
  if (all(file.exists(c(tensor_files, keys_file))) && !rebuild_tensors) {
    cat("Loading cached tensors from", out_dir, "\n")
    Tn_ <- setNames(lapply(tensor_files, torch_load), tensor_names)
    keys <- fread(keys_file)
  } else {
    parts <- lapply(weeks, function(wk) { r <- build_week(wk); gc(verbose = FALSE); r })
    Tn_ <- setNames(lapply(tensor_names, function(nm)
      torch_cat(lapply(parts, `[[`, nm), dim = 1)), tensor_names)
    keys <- rbindlist(lapply(parts, `[[`, "keys"))
    rm(parts); gc(verbose = FALSE)
    for (k in seq_along(tensor_names)) torch_save(Tn_[[k]], tensor_files[k])
    fwrite(keys, keys_file)
  }
  TX <- Tn_$X; TPM <- Tn_$PM; TFM <- Tn_$FM; TTS <- Tn_$TS; TCX <- Tn_$ctx
  TY <- torch_tensor(keys$rpo, dtype = torch_float())
  FMr <- as.array(TFM)
  rm(Tn_); gc(verbose = FALSE)
  N <- nrow(keys)
  cat(sprintf("Plays: %d | RPO: %.1f%% | tensor %s\n", N, 100 * mean(keys$rpo),
              paste(dim(TX), collapse = " x ")))

  # =============================================================================
  # 10.2 Model
  # =============================================================================
  # One attention block: x [N, L, d]; allowed [N, L, L] (TRUE = may attend)
  attn_block <- nn_module(
    initialize = function(d, heads, dropout) {
      self$h <- heads; self$dk <- d %/% heads
      self$q <- nn_linear(d, d); self$k <- nn_linear(d, d)
      self$v <- nn_linear(d, d); self$o <- nn_linear(d, d)
      self$ln1 <- nn_layer_norm(d); self$ln2 <- nn_layer_norm(d)
      self$ff <- nn_sequential(nn_linear(d, 2 * d), nn_gelu(),
                               nn_linear(2 * d, d))
      self$drop <- nn_dropout(dropout)
      self$keep_attn <- FALSE
    },
    forward = function(x, allowed) {
      n <- x$size(1); L <- x$size(2); d <- x$size(3)
      z <- self$ln1(x)
      split <- function(t) t$reshape(c(n, L, self$h, self$dk))$transpose(2, 3)
      q <- split(self$q(z)); k <- split(self$k(z)); v <- split(self$v(z))
      s <- torch_matmul(q, k$transpose(3, 4)) / sqrt(self$dk)    # [n,h,L,L]
      s <- s$masked_fill(torch_logical_not(allowed$unsqueeze(2)), -1e9)
      a <- nnf_softmax(s, dim = 4)
      if (self$keep_attn) self$attn <- a$detach()$cpu()
      out <- torch_matmul(self$drop(a), v)$transpose(2, 3)$reshape(c(n, L, d))
      x <- x + self$drop(self$o(out))
      x + self$drop(self$ff(self$ln2(x)))
    }
  )

  rpo_transformer <- nn_module(
    initialize = function(n_feat, n_ctx, d, heads, n_space, n_time, dropout) {
      self$embed <- nn_sequential(nn_linear(n_feat, d), nn_gelu(),
                                  nn_linear(d, d))
      self$space <- nn_module_list(lapply(seq_len(n_space), function(i)
        attn_block(d, heads, dropout)))
      self$pool  <- nn_linear(d, 1)
      self$tpos  <- nn_linear(1, d)            # seconds since lineset
      self$ctx   <- nn_linear(n_ctx, d)        # down, distance, score ...
      self$time  <- nn_module_list(lapply(seq_len(n_time), function(i)
        attn_block(d, heads, dropout)))
      self$head  <- nn_sequential(nn_layer_norm(d), nn_linear(d, d), nn_gelu(),
                                  nn_linear(d, 1))
    },
    # x [B,T,P,F]; pm [B,T,P]; fm [B,T]; ts [B,T]; cx [B,C]  ->  logits [B,T]
    forward = function(x, pm, fm, ts, cx) {
      B <- x$size(1); Tn <- x$size(2); P <- x$size(3)
      h <- self$embed(x)
      d <- h$size(4)
      h <- h$reshape(c(B * Tn, P, d))
      keep <- pm$reshape(c(B * Tn, P))
      empty <- keep$sum(dim = 2) == 0                       # padded frames
      keep <- torch_logical_or(keep, empty$unsqueeze(2))
      allowed <- keep$unsqueeze(2)$expand(c(B * Tn, P, P))  # attend to real players
      for (i in seq_along(self$space)) h <- self$space[[i]](h, allowed)
      w <- self$pool(h)$squeeze(3)$masked_fill(torch_logical_not(keep), -1e9)
      w <- nnf_softmax(w, dim = 2)
      f <- (w$unsqueeze(3) * h)$sum(dim = 2)$reshape(c(B, Tn, d))
      f <- f + self$tpos(ts$unsqueeze(3)) + self$ctx(cx)$unsqueeze(2)
      # causal: a frame sees itself and earlier real frames only
      causal <- torch_tril(torch_ones(Tn, Tn, device = x$device))$to(dtype = torch_bool())
      allowed_t <- torch_logical_and(causal$unsqueeze(1), fm$unsqueeze(2))
      allowed_t <- torch_logical_or(allowed_t,
                                    torch_eye(Tn, device = x$device)$to(dtype = torch_bool())$unsqueeze(1))
      for (i in seq_along(self$time)) f <- self$time[[i]](f, allowed_t)
      self$head(f)$squeeze(3)
    }
  )

  new_model <- function() rpo_transformer(
    n_feat = length(PLAYER_FEATS), n_ctx = length(CTX_FEATS), d = d_model,
    heads = n_heads, n_space = space_layers, n_time = time_layers,
    dropout = dropout)$to(device = device)

  batch <- function(i) {
    ii <- torch_tensor(i, dtype = torch_long())
    list(x = TX[ii, , , ]$to(device = device), pm = TPM[ii, , ]$to(device = device),
         fm = TFM[ii, ]$to(device = device), ts = TTS[ii, ]$to(device = device),
         cx = TCX[ii, ]$to(device = device), y = TY[ii]$to(device = device))
  }
  # linked frames: each play's frames share a total weight of 1
  play_loss <- function(logits, b) {
    fmf <- b$fm$to(dtype = torch_float())
    w <- fmf / fmf$sum(dim = 2, keepdim = TRUE)$clamp(min = 1)
    yy <- b$y$unsqueeze(2)$expand_as(logits)
    l <- nnf_binary_cross_entropy_with_logits(logits, yy, reduction = "none")
    (l * w)$sum() / w$sum()
  }
  predict_probs <- function(model, idx) {
    model$eval(); out <- list()
    with_no_grad({
      for (s in seq(1, length(idx), by = 256)) {
        i <- idx[s:min(s + 255, length(idx))]
        b <- batch(i)
        out[[length(out) + 1]] <- as.matrix(torch_sigmoid(
          model(b$x, b$pm, b$fm, b$ts, b$cx))$cpu())
      }
    })
    do.call(rbind, out)
  }
  eval_loss <- function(model, idx) {
    model$eval(); tot <- 0; n <- 0
    with_no_grad({
      for (s in seq(1, length(idx), by = 256)) {
        i <- idx[s:min(s + 255, length(idx))]
        b <- batch(i)
        tot <- tot + play_loss(model(b$x, b$pm, b$fm, b$ts, b$cx), b)$item() * length(i)
        n <- n + length(i)
      }
    })
    tot / n
  }

  train_model <- function(tr, va) {
    model <- new_model()
    opt <- optim_adamw(model$parameters, lr = lr, weight_decay = 1e-4)
    best <- Inf; best_state <- NULL; bad <- 0
    for (ep in seq_len(max_epochs)) {
      model$train()
      perm <- sample(tr)
      for (s in seq(1, length(perm), by = batch_size)) {
        i <- perm[s:min(s + batch_size - 1, length(perm))]
        b <- batch(i)
        opt$zero_grad()
        loss <- play_loss(model(b$x, b$pm, b$fm, b$ts, b$cx), b)
        loss$backward()
        nn_utils_clip_grad_norm_(model$parameters, 1)
        opt$step()
      }
      vl <- eval_loss(model, va)
      cat(sprintf("    epoch %2d  validation loss %.4f\n", ep, vl))
      if (vl < best - 1e-4) {
        best <- vl; bad <- 0
        best_state <- lapply(model$state_dict(), function(t) t$clone())
      } else if ((bad <- bad + 1) >= patience) break
    }
    model$load_state_dict(best_state)
    model
  }

  # =============================================================================
  # 10.3 Leave-one-week-out training
  # =============================================================================
  oof <- list(); model <- NULL
  for (wk in tf_test_weeks) {
    te <- which(keys$week == wk)
    other <- setdiff(weeks, wk)
    va_wk <- if ((wk - 1) %in% other) wk - 1 else max(other)  # for early stopping
    va <- which(keys$week == va_wk)
    tr <- which(keys$week != wk & keys$week != va_wk)
    cat(sprintf("\nWeek %d held out (validation week %d): %d train / %d val / %d test plays\n",
                wk, va_wk, length(tr), length(va), length(te)))
    model <- train_model(tr, va)
    P <- predict_probs(model, te)
    fm <- FMr[te, , drop = FALSE]
    slot <- col(P)
    oof[[length(oof) + 1]] <- data.table(
      gameId = keys$gameId[te][row(P)[fm]], playId = keys$playId[te][row(P)[fm]],
      week = wk, rpo = keys$rpo[te][row(P)[fm]],
      secs_to_snap = (t_max - slot[fm]) * t_step / 10, p_tf = P[fm])
  }
  oof <- rbindlist(oof)
  fwrite(oof, file.path(tf_dir, "transformer_oof_frame_predictions.csv"))
  torch_save(model, file.path(tf_dir, "rpo_transformer_last_fold.pt"))

  # =============================================================================
  # 10.4 Compare with XGBoost on the same plays and time points
  # =============================================================================
  xgb_file <- file.path(out_dir, "xgb_oof_frame_predictions.csv")
  if (file.exists(xgb_file)) {
    xgb <- fread(xgb_file)[, .(gameId, playId, tts = round(secs_to_snap * 10), p_xgb)]
    cmp <- merge(oof[, .(gameId, playId, week, rpo, tts = round(secs_to_snap * 10), p_tf)],
                 xgb, by = c("gameId", "playId", "tts"))
    cut_tf  <- cmp[tts == 0, best_cut(rpo, p_tf)]
    cut_xgb <- cmp[tts == 0, best_cut(rpo, p_xgb)]
    res <- rbindlist(lapply(c(0, 10, 20, 30, 40), function(k) {
      d <- cmp[tts == k]
      if (nrow(d) < 50 || length(unique(d$rpo)) < 2) return(NULL)
      rbind(data.table(secs_before_snap = k / 10, model = "xgboost", plays = nrow(d),
                       roc_auc = auc_roc(d$rpo, d$p_xgb), pr_auc = auc_pr(d$rpo, d$p_xgb),
                       balanced_acc = bal_acc(d$rpo, d$p_xgb, cut_xgb)),
            data.table(secs_before_snap = k / 10, model = "transformer", plays = nrow(d),
                       roc_auc = auc_roc(d$rpo, d$p_tf), pr_auc = auc_pr(d$rpo, d$p_tf),
                       balanced_acc = bal_acc(d$rpo, d$p_tf, cut_tf)))
    }))
    res[, (c("roc_auc", "pr_auc", "balanced_acc")) :=
          lapply(.SD, round, 3), .SDcols = c("roc_auc", "pr_auc", "balanced_acc")]
    fwrite(res, file.path(tf_dir, "transformer_vs_xgboost.csv"))
    cat("\nTransformer vs XGBoost (same plays, held-out weeks):\n"); print(res)
    snap_res <- res[secs_before_snap == 0]
    better <- snap_res[model == "transformer", roc_auc] >
      snap_res[model == "xgboost", roc_auc]
    cat(if (better) "\n-> The transformer beats XGBoost at the snap: keep it.\n" else
          "\n-> The transformer does not beat XGBoost at the snap: keep XGBoost.\n")
    ggsave(file.path(tf_dir, "transformer_vs_xgboost.png"), width = 8,
           height = 5, dpi = 150, plot = ggplot(res, aes(secs_before_snap, roc_auc, colour = model)) +
                geom_line(linewidth = 1) + geom_point() +
                scale_x_reverse() +
                scale_colour_manual(values = c(xgboost = "#0072B2",
                                               transformer = "#D55E00")) +
                labs(x = "Seconds before the snap", y = "ROC-AUC (held-out weeks)",
                     colour = NULL, title = "Transformer vs XGBoost"))
  }

  # =============================================================================
  # 10.5 Attention: which players and moments the model focused on
  # =============================================================================
  # Uses the last fold's model on its held-out week: the 3 most confident
  # correct RPO calls at the snap.
  last_te <- which(keys$week == tail(tf_test_weeks, 1))
  snap_p <- oof[week == tail(tf_test_weeks, 1) & secs_to_snap == 0]
  ex <- snap_p[rpo == 1][order(-p_tf)][seq_len(min(3, .N))]
  for (blk in list(model$space[[space_layers]], model$time[[time_layers]]))
    blk$keep_attn <- TRUE
  model$eval()
  for (r in seq_len(nrow(ex))) {
    i <- which(keys$gameId == ex$gameId[r] & keys$playId == ex$playId[r])
    b <- batch(i)
    with_no_grad(model(b$x, b$pm, b$fm, b$ts, b$cx))
    # players: attention received at the snap frame, averaged over heads/queries
    xs <- as.array(TX[i, t_max, , ])
    pmk <- as.array(TPM[i, t_max, ])
    a_sp <- as.array(model$space[[space_layers]]$attn)[t_max, , pmk, , drop = FALSE]
    recv <- apply(a_sp, 4, mean)      # attention each player received
    pdat <- data.table(x = xs[, 1] * 10, y = xs[, 2] * 10,
                       side = fifelse(xs[, 10] == 1, "offence", "defence"),
                       pos = POS_GROUPS[max.col(xs[, 11:18], ties.method = "first")],
                       attention = recv)[pmk]
    # frames: how much the snap frame attended to each earlier frame
    a_t <- as.array(model$time[[time_layers]]$attn)[1, , t_max, ]
    tdat <- data.table(secs_before_snap = (t_max - seq_len(t_max)) * t_step / 10,
                       attention = colMeans(matrix(a_t, nrow = n_heads)))[
      as.vector(as.array(TFM[i, ]))]
    tag <- sprintf("game %s, play %s (p = %.2f)", ex$gameId[r], ex$playId[r],
                   ex$p_tf[r])
    p1 <- ggplot(pdat, aes(x, y)) +
      geom_vline(xintercept = 0, colour = "grey60") +
      geom_point(aes(size = attention, colour = side), alpha = 0.8) +
      geom_text(aes(label = pos), size = 2.6, vjust = -1.4) +
      scale_colour_manual(values = c(offence = "#D55E00", defence = "#0072B2")) +
      scale_size(range = c(1.5, 9)) + coord_fixed() +
      labs(x = "Yards from the line (offence attacks to the right)",
           y = "Yards across the field", colour = NULL,
           title = paste("Which players the model focused on at the snap:", tag))
    p2 <- ggplot(tdat, aes(secs_before_snap, attention)) +
      geom_col(fill = "#E69F00") + scale_x_reverse() +
      labs(x = "Seconds before the snap", y = "Attention from the snap frame",
           title = paste("Which moments the model looked back to:", tag))
    ggsave(file.path(tf_dir, sprintf("attention_players_%d.png", r)), p1,
           width = 9, height = 5, dpi = 150)
    ggsave(file.path(tf_dir, sprintf("attention_frames_%d.png", r)), p2,
           width = 8, height = 4, dpi = 150)
  }

  cat("\nDone. Outputs written to", normalizePath(out_dir), "\n")
}

cat("\nDone. Outputs written to", normalizePath(out_dir), "\n")

What we found

p <- ggplot(tfc, aes(secs_before_snap, roc_auc, colour = model)) +
  geom_line(linewidth = 1) + geom_point(size = 2) +
  scale_x_reverse(breaks = 0:4, labels = c("snap", paste0(1:4, "s"))) +
  scale_colour_manual(values = c(xgboost = "#D55E00", transformer = "#0072B2")) +
  labs(x = "Seconds before the snap", y = "ROC-AUC (held-out weeks)", colour = NULL)
ggplotly(p)

How to read this chart. Both models are scored on the same held-out plays at each moment before the snap; higher is better. The line that stays higher further to the left gives the more useful early warning.

XGBoost is the better model. The transformer only edges ahead on the snap frame itself (0.880 vs 0.867). One second earlier it falls to 0.770, against XGBoost’s 0.860, and it stays behind at every earlier point.

Why it did not beat XGBoost

  • The snap frame gives it a peek at the play. A genuine advantage would not appear on the last frame only. At the snap frame the play has already started: the ball moves and linemen fire out. The transformer reads raw speed and acceleration, so that one frame partly shows what happens after the snap. XGBoost, built on alignment features, barely changes between one second out and the snap.
  • Not enough data for a model that starts from scratch. About 15,800 plays, of which only about 1,600 are RPOs, is small for a transformer. XGBoost starts with football knowledge built into its features; the transformer has to discover it all from raw positions.
  • It was not told who the offence is. The transformer received down, distance, field position, score and time, but not the team or the formation label. Team is XGBoost’s second-strongest feature, so part of the gap is simply missing information.
  • Limited training. It was trained on a regular computer’s CPU, which limited its size and how long it could train.

So XGBoost is kept: before the snap, which is the only moment a defence can use, the transformer does not beat it.

Why it is still worth keeping in the project

  • Fixable weaknesses. Ending its frames half a second before the snap, adding the team and formation as inputs, and training on more seasons (or on a GPU) address every reason above.
  • The two models can be combined. Averaging the two models’ probabilities often beats either one on its own, because they make different kinds of mistakes.
  • New features to build. Where the transformer’s attention points to players or moments that XGBoost has no feature for, those can be measured and added to XGBoost.

What the transformer looked at

How to read these charts. The top chart is one held-out RPO at the snap, seen from above and turned sideways so the whole width of the field fits: the offence is below the dashed line of scrimmage, attacking up the page. Each circle is a player (orange offence, blue defence), and the bigger the circle, the more attention the other players paid to him when the model made its prediction. The bar chart underneath shows which earlier moments the snap frame looked back to.

The attention lands where a coach would look: on the running back and quarterback (the mesh point of the RPO), and on the widest receivers and the defenders covering them, who make up the throwing half of the option. These are the same areas SHAP ranks highly for XGBoost, which suggests both models picked up the same football logic.

Where the model misses RPOs

pred <- fread(file.path(out, "play_predictions_at_snap.csv"))
pred <- merge(pred, pinfo[, .(gameId, playId, formation, alignment, down,
                              yardsToGo)], by = c("gameId", "playId"))
best_cut <- function(y, p) {
  cuts <- seq(0.02, 0.6, 0.01)
  ba <- sapply(cuts, function(t) (mean(p[y == 1] >= t) + mean(p[y == 0] < t)) / 2)
  cuts[which.max(ba)]
}
cut0 <- best_cut(pred$rpo, pred$p_xgb)
pred[, flagged := p_xgb >= cut0]

# snap-frame alignment and motion, if the cached features are available
ff_file <- file.path(out, "frame_features.csv")
if (file.exists(ff_file)) {
  ff <- fread(ff_file, select = c("gameId", "playId", "is_snap_frame",
                                  "rb_beside_qb", "rb_dx", "rb_lat_abs",
                                  "n_skill_moved", "secs_since_ls"))[is_snap_frame == 1]
  pred <- merge(pred, ff, by = c("gameId", "playId"), all.x = TRUE)
}

team_tier <- team_rate[, .(team, tier = fcase(
  team_rpo_rate < 0.05, "Rarely runs RPOs (< 5%)",
  team_rpo_rate < 0.15, "Average RPO team (5-15%)",
  default = "RPO-heavy team (15%+)"))]
pred <- merge(pred, team_tier, by = "team")
pred[, `:=`(
  Formation = fcase(formation == "SHOTGUN", "Shotgun", formation == "PISTOL", "Pistol",
                    formation %in% c("SINGLEBACK", "I_FORM", "JUMBO"), "Under center",
                    default = "Other (empty, wildcat)"),
  Down = fifelse(down <= 2, "1st or 2nd down", "3rd or 4th down"),
  Distance = fcase(yardsToGo <= 3, "1-3 yards to go", yardsToGo <= 6, "4-6 yards to go",
                   yardsToGo <= 10, "7-10 yards to go", default = "11+ yards to go"),
  `Offence's RPO habits` = tier)]
groups <- c("Formation", "Down", "Distance", "Offence's RPO habits")
if ("rb_beside_qb" %in% names(pred)) {
  pred[, `:=`(
    Backfield = fcase(rb_beside_qb == 1, "RB beside QB",
                      !is.na(rb_dx) & rb_dx < -1.5 & rb_lat_abs < 1, "RB directly behind QB",
                      is.na(rb_dx), "No running back", default = "RB elsewhere"),
    Motion = fifelse(n_skill_moved >= 1, "Motion before the snap", "No motion"),
    `Time set before snap` = fcase(secs_since_ls < 2, "Under 2 s (quick snap)",
                                   secs_since_ls <= 5, "2-5 s", default = "Over 5 s"))]
  groups <- c(groups, "Backfield", "Motion", "Time set before snap")
}

rp <- pred[rpo == 1]
recall_all <- mean(rp$flagged)
seg <- rbindlist(lapply(groups, function(g)
  rp[, .(RPOs = .N, caught = mean(flagged), avg_p = mean(p_xgb)),
     by = .(situation = get(g))][, group := g]))
seg <- seg[RPOs >= 30 & !is.na(situation)]
seg[, gap := caught - recall_all]
weak <- seg[order(caught)][1:min(4, .N)]
gun_share <- mean(rp$Formation %in% c("Shotgun", "Pistol"))

The model flags a play when its probability is at least 11%, the cutoff that gives the best balanced accuracy. At that cutoff it catches 79% of all RPOs. The chart shows how that catch rate changes by situation. Bars to the left of the dashed line are situations where it misses more RPOs than usual.

How to read this chart. Each bar is a type of situation, and its length is the share of RPOs in that situation that the model flagged. The dashed line is the overall catch rate. Orange bars fall below it, so those are the situations where the model misses more RPOs than usual. The number in brackets is how many RPOs that situation had.

seg[, label := paste0(group, ": ", situation, " (", RPOs, " RPOs)")]
seg[, group := factor(group, levels = groups)]
seg[, label := factor(label, levels = rev(seg[order(group, -caught), label]))]
p <- ggplot(seg, aes(caught, label, fill = gap < 0,
                     text = paste0(situation, "<br>RPOs: ", RPOs,
                                   "<br>caught: ", pct(caught, 0),
                                   "<br>average predicted: ", pct(avg_p, 0)))) +
  geom_col(width = 0.7) +
  geom_vline(xintercept = recall_all, linetype = 2, colour = "grey40") +
  scale_x_continuous(labels = scales::percent, limits = c(0, 1)) +
  scale_fill_manual(values = c(`TRUE` = "#D55E00", `FALSE` = "#0072B2"),
                    guide = "none") +
  labs(x = "Share of RPOs the model caught", y = NULL)
ggplotly(p, tooltip = "text")

The weakest situations in this data are:

cat(paste0("* **", weak$situation, "** (", weak$group, "): caught ",
           pct(weak$caught, 0), " of ", weak$RPOs, " RPOs, with an average predicted chance of ",
           pct(weak$avg_p, 0), ".\n"), sep = "")

Why these RPOs are missed

  • They don’t look like RPOs. 88% of RPOs come from shotgun or pistol, so RPOs from under center, with the back directly behind the QB, or on 3rd down and long are rare. The model has few examples of them and learns to treat those looks as “almost never an RPO”. The missed-RPO waterfall above is this case: a singleback RPO where the formation and the offence’s history both pushed the probability down.
  • Team history pulls predictions down. Team is the second-strongest feature. When an offence that rarely runs RPOs (TB, CLE, LV, NO) does call one, its history pushes the probability toward zero even if the look is right. The same thing happens when a team changes its tendencies mid-season.
  • Some RPOs are decided after the snap. The pre-snap look for many RPOs is identical to a plain inside run or a quick pass. Before the snap there is simply nothing that separates them, which caps how many any pre-snap model can catch and produces false alarms on the same looks.
  • Quick snaps can leave little to see. When the offence snaps soon after setting, there is less time for motion or alignment details to show (check the Time set before snap rows above).
  • Label noise. The RPO label is PFF’s judgment; some “misses” may be plays charted differently from how they were designed.

How to address them

  1. Give rare looks more weight in training. Up-weight RPOs from under center, 3rd down and non-shotgun looks, or train a small separate model for under-center plays, so the model does not write them off.
  2. Make the team effect smarter. Replace the fixed team label with each team’s RPO rate up to that week (a rolling tendency). The model then adapts when a team changes, and can be shrunk toward the league average for teams with few RPOs.
  3. Add features that separate RPOs from look-alike runs. For example, the position of the defender the quarterback would read (the overhang or apex linebacker), the box count relative to blockers using a better box definition, and receiver stance or alignment depth.
  4. More data. Add more seasons so rare situations have enough examples, and check missed plays on film to find mislabelled ones.
  5. Use the probability as a range, not a yes/no. For coaches, a low-but-rising probability on a rare look is still useful. A “watch” tier just below the cutoff would catch more of these plays, at the cost of some extra alarms.

How a defence could use this

A fair challenge is that once a defence reacts to a tell, the offence will adjust, so any advantage is temporary. Three points, kept short:

st5[, look_w := vapply(look, function(s) paste(strwrap(s, 40), collapse = "<br>"), "")]
p <- ggplot(st5, aes(week, lift, colour = look_w, group = look_w,
                     text = paste0(look, "<br>week ", week, ": lift ", round(lift, 2),
                                   " (", plays, " plays)"))) +
  geom_hline(yintercept = 1, linetype = 2, colour = "grey50") +
  geom_line(linewidth = 0.9) + geom_point(size = 2) +
  scale_x_continuous(breaks = 1:9) +
  scale_colour_manual(values = c("#D55E00", "#0072B2", "#009E73", "#CC79A7", "#E69F00")) +
  labs(x = "Week", y = "Lift (1 = average)", colour = NULL)
ggplotly(p, tooltip = "text") |> layout(legend = list(orientation = "h", y = -0.3))

Limitations and next steps

Running the code

This page includes all of the code, but not the data or the saved results, so reproducing it means running the pipeline yourself:

  1. Get the scripts. Download them here (the same code is shown throughout this report):

Download rpo_project.R

Download rpo_live_demo.R

Download rpo_report_extras.R

  1. Get the data. Download the NFL Big Data Bowl 2025 data from Kaggle (free Kaggle account; you must accept the competition rules, which is also why the data is not shared here) and unzip it into a folder called data next to the scripts.
  2. Run in order: rpo_project.R, then rpo_live_demo.R, then rpo_report_extras.R, then knit this report with project_dir set to that folder.

Rough run times on an 8-core computer with 32 GB of RAM: