A Bayesian Item Response Model of NFL Placekicker Skill
This post is the second in a series (first post) building Bayesian models of NFL field goal success. This post extends the work in the prior one, becoming a true item-response theory (IRT) model adding kicker-specific skills. We will also explore how field goal success changes with kicker experience and address survivorship bias due to the fact that only sufficiently successful kickers are allowed to continue kicking (and therefore gain experience).
Before we begin analyzing the data, we make the necessary Python imports and do some light configuration.
import logging
from functools import partial
from html import escape
from pathlib import Path
from fastprogress.fastprogress import progress_bar
from toolz import compose
import arviz as az
import matplotlib.pyplot as plt
import nflreadpy as nfl
import numpy as np
import nutpie
import polars as pl
import preliz as pz
import pymc as pm
import seaborn as sns
import xarray as xr
from IPython.display import HTML
from matplotlib import ticker
from pymc_extras.utils.spline import numpy_bspline_basis
from scipy.special import expit, logit
from scipy.stats import beta
from seaborn import objects as so
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer, MinMaxScaler
sns.set(color_codes=True)
logging.getLogger("pytensor.graph.rewriting.basic").setLevel(logging.CRITICAL)
nfl.config.update_config(cache_mode="filesystem")
Load the data¶
Previous post data¶
First we load data from the previous post, see there for a more detailed discussion and exploration of this data.
pbp_df = nfl.load_pbp(seasons=True).filter(pl.col("season") <= 2025)
FG_COLS = [
"play_id",
"game_id",
"game_date",
"field_goal_result",
"kick_distance",
"season",
"roof",
"surface",
"game_stadium",
"kicker_player_id",
"kicker_player_name",
]
fg_df = (
pbp_df.filter(pl.col("field_goal_attempt") == 1)
.with_columns(pl.col("game_date").str.to_date())
.select(FG_COLS)
)
fg_df = fg_df.filter(pl.col("field_goal_result") != "blocked").with_columns(
made=pl.col("field_goal_result") == "made"
)
fg_df = fg_df.with_columns(is_exposed=pl.col("roof").is_in(["open", "outdoors"]))
fg_df = (
fg_df.with_columns(
surface=pl.col("surface").str.strip_chars().replace("", None),
)
.drop_nulls("surface")
.with_columns(is_turf=~pl.col("surface").is_in(["grass", "dessograss"]))
)
STADIUM_DATA_PATH = "https://austinrochford.com/resources/fg_irt/stadiums.csv"
stadium_df = pl.read_csv(
STADIUM_DATA_PATH, columns=["game_stadium", "building"]
).rename({"building": "stadium"})
fg_df = fg_df.join(stadium_df, on="game_stadium", how="left").drop("game_stadium")
assert fg_df["stadium"].null_count() == 0
fg_df = fg_df.join(
pbp_df.sort(["game_id", "qtr", "play_id"])
.with_columns(
prev_timeout_team=pl.col("timeout_team").shift(1).over("game_id", "qtr")
)
.filter(pl.col("field_goal_attempt") == 1)
.with_columns(iced=pl.col("prev_timeout_team").eq_missing(pl.col("defteam")))
.select("play_id", "game_id", "iced"),
on=["play_id", "game_id"],
)
Player data¶
In addition to the data from the previous post, we load biographical information about each kicker.
KICKER_COLS = ["gsis_id", "birth_date", "rookie_season"]
kicker_df = nfl.load_players()[KICKER_COLS].with_columns(
pl.col("birth_date").str.to_date()
)
fg_df = fg_df.join(
kicker_df,
left_on="kicker_player_id",
right_on="gsis_id",
how="left",
).drop_nulls(["birth_date", "rookie_season"])
We see that there are two names that each have two distinct kickers associated with them.
fg_df.group_by("kicker_player_name").agg(
pl.col("kicker_player_id").n_unique().alias("kicker_ct")
).filter(pl.col("kicker_ct") > 1)
We disambiguate these by adding the range of seasons in which they played.
kicker_df = (
fg_df.group_by("kicker_player_id")
.agg(
pl.col("kicker_player_name").mode().sort().first(),
kick_ct=pl.len(),
first_season=pl.col("season").min(),
last_season=pl.col("season").max(),
)
.with_columns(
season_range=pl.when(pl.col("first_season") == pl.col("last_season"))
.then(pl.col("first_season").cast(pl.String))
.otherwise(
pl.col("first_season").cast(pl.String)
+ "-"
+ pl.col("last_season").cast(pl.String)
)
)
.with_columns(
kicker_player_name=pl.when(pl.col("kicker_player_name").is_duplicated())
.then(pl.col("kicker_player_name") + " (" + pl.col("season_range") + ")")
.otherwise(pl.col("kicker_player_name"))
)
.drop("first_season", "last_season", "season_range")
)
We see that there are no longer name collisions.
kicker_df.group_by("kicker_player_name").agg(
pl.col("kicker_player_id").n_unique().alias("kicker_ct")
)["kicker_ct"].max()
Creating enums¶
We turn appropriate columns into Polars enums.
ENUM_COL_MAP = {
"season": ["season"],
"stadium": ["stadium"],
"kicker": ["kicker_player_id"],
}
enums = {}
for enum, names in ENUM_COL_MAP.items():
categories = set()
for name in names:
categories |= set(fg_df[name].drop_nulls().cast(pl.String).unique())
enums[enum] = pl.Enum(sorted(categories))
for name in names:
fg_df = fg_df.with_columns(pl.col(name).cast(pl.String).cast(enums[enum]))
if name in kicker_df:
kicker_df = kicker_df.with_columns(pl.col(name).cast(enums[enum]))
Exploratory data analysis¶
The prior post contains EDA of many environmental (non-player) factors that impact field goal success, which we will not repeat here.
Player experience¶
We are interested in understanding how field goal success varies with the player's age and years of experience, so we add those quantities to our data.
fg_df = fg_df.with_columns(
age=(pl.col("game_date") - pl.col("birth_date")).dt.total_days(fractional=True)
/ 365.25,
yrs_exp=pl.col("season").cast(pl.String).str.to_integer() - pl.col("rookie_season"),
)
We now visualize the relationship between years of NFL kicking experience, age, and field goal success rate.
PCT_FORMATTER = partial(ticker.PercentFormatter, xmax=1, decimals=1)
AGE_LABEL = "Age"
EXP_LABEL = "Experience (years)"
MADE_LABEL = "Field goals made"
def plot_axis_ticks(
plot, *, x_locator=None, x_formatter=None, y_locator=None, y_formatter=None
):
"""Apply real matplotlib locators/formatters post-render.
Works around a seaborn bug where so.Est()-based layers leave the y-axis
PseudoAxis incompletely initialized if a matplotlib Locator/Formatter is
passed through .scale() instead of applied directly to the rendered axes
See https://github.com/mwaskom/seaborn/issues/3585 for details
"""
plotter = plot.plot()
for ax in plotter._figure.axes:
if x_locator is not None:
ax.xaxis.set_major_locator(x_locator)
if x_formatter is not None:
ax.xaxis.set_major_formatter(x_formatter)
if y_locator is not None:
ax.yaxis.set_major_locator(y_locator)
if y_formatter is not None:
ax.yaxis.set_major_formatter(y_formatter)
return plotter
plotter = plot_axis_ticks(
so.Plot(fg_df.with_columns(pl.col("age").floor(), pl.col("made").cast(pl.Float64)))
.pair(x=["yrs_exp", "age"], y=["made"])
.add(so.Dot(), so.Agg())
.label(x0=EXP_LABEL, x1=AGE_LABEL, y=MADE_LABEL)
.layout(size=(10, 4)),
y_formatter=PCT_FORMATTER(),
)
plotter._figure.tight_layout()
plotter
There appears to be an increase in success rate in the first few years of a kicker's career, which then levels off. We will model this effect later in this post.
The following plot shows that age and experience are highly correlated, which is not surprising. In light of this correlation, we will only use years of NFL kicking experience in our model.
(
so.Plot(fg_df, x="yrs_exp", y="age")
.add(so.Dot(), so.Agg())
.add(so.Range(), so.Est(errorbar=("pi", 95)))
.label(x=EXP_LABEL, y=AGE_LABEL)
)
Modeling¶
We begin by recreating the final model from the previous post. We skip the model helpers and feature engineering that are repeated from that post, but they remain available for the reader to expand and review as desired.
Model helpers¶
Show code
make_2d_col = compose(np.transpose, np.atleast_2d, np.asarray)
def make_1d_transform(x, transform):
return make_pipeline(
FunctionTransformer(make_2d_col, np.squeeze),
transform(),
FunctionTransformer(partial(np.squeeze, axis=-1), make_2d_col),
).fit(x)
def unpack_value_dims(value_dims):
match value_dims:
case (value, dims):
pass
case value:
dims = "obs"
return value, dims
def make_data(**data):
"""
Keyword args should be either:
* name=value (for dims="obs")
* name=(value, dims)
"""
containers = {}
for name, value_dims in data.items():
value, dims = unpack_value_dims(value_dims)
containers[name] = pm.Data(name, value, dims=dims)
return containers
def make_coefs(*names):
return {name: pm.Normal(name, 0, 2.5) for name in names}
def zero_mean(x, *, axis):
return x - x.mean(axis=axis, keepdims=True)
def spline_coef(name, *, dims="dist_basis"):
σ = pm.HalfNormal(f"σ_{name}", 2.5)
coef_unid = pm.GaussianRandomWalk(
f"{name}_unid", 0, σ, init_dist=pm.Normal.dist(0, 2.5), dims=dims
)
return pm.Deterministic(name, zero_mean(coef_unid, axis=0), dims=dims)
φ_prior = pz.maxent(pz.Beta(), np.sqrt(0.25), np.sqrt(0.9), 0.95, plot=False)
def ar_deviation(name, *, dims, coef_name=None):
coef_name = coef_name or name
η = pm.HalfNormal(f"η_{name}", 0.5)
φ = φ_prior.to_pymc(f"φ_{name}")
σ = pm.Deterministic(f"σ_{name}", η * pm.math.sqrt(1 - φ**2))
model = pm.modelcontext(None)
n_steps = len(model.coords[dims[-1]])
coef_unid = pm.AR(
f"{coef_name}_unid",
φ,
σ,
init_dist=pm.Normal.dist(0, η),
steps=n_steps - 1,
dims=dims,
)
return pm.Deterministic(
coef_name, zero_mean(coef_unid, axis=len(dims) - 1), dims=dims
)
def deviation_coef(name, basis, *, basis_dim="dist_basis"):
coef = ar_deviation(name, dims=(f"{name}_basis", name), coef_name=f"α_{name}")
return pm.Deterministic(f"w_{name}", (basis @ coef).T, dims=(name, basis_dim))
def hierarchical_normal(name, *, μ=None, dims):
if μ is None:
μ = pm.Normal(f"μ_{name}", 0, 2.5)
Δ = pm.Normal(f"Δ_{name}", 0, 1, dims=dims)
σ = pm.HalfNormal(f"σ_{name}", 2.5)
return pm.Deterministic(name, μ + Δ * σ, dims=dims)
SEED = 123456789
COMPILE_KWARGS = {"backend": "jax", "gradient_backend": "jax"}
traces = {}
loos = {}
def sample(model, seed=SEED, **sample_kwargs):
compiled = nutpie.compile_pymc_model(model, **COMPILE_KWARGS)
trace = nutpie.sample(compiled, seed=seed, **sample_kwargs)
pm.compute_log_likelihood(trace, model=model, progressbar=False)
loo = az.loo(trace, pointwise=True, var_name="made_obs")
return trace, loo
def plot_ax(plotter):
(ax,) = plotter._figure.axes
return ax
# match strings that don't end in "_unid" and are not exactly "p_made"
RHAT_VAR_REGEX = r"^(?!p_made$).*(?<!_unid)$"
RHAT_KWARGS = {"var_names": RHAT_VAR_REGEX, "filter_vars": "regex"}
def plot_rhat(trace, *, max_=1.03):
rhat_df = (
az.rhat(trace, **RHAT_KWARGS)
.max()
.to_dataset()
.to_dataarray(dim="variable")
.to_dataframe(name="rhat")
.reset_index()
.pipe(pl.from_pandas)
)
plotter = (
so.Plot(rhat_df, x="rhat", y="variable")
.add(so.Bar())
.scale(x=so.Continuous().tick(every=0.01))
.limit(x=(0.999, max_))
.label(x=r"$\hat{R}$", y=None)
.plot()
)
plot_ax(plotter).axvline(1.01, c="k", ls="--")
return plotter
def to_polars(da):
mesh = np.meshgrid(*(da.coords[dim].to_numpy() for dim in da.dims), indexing="ij")
columns = dict(zip(da.dims, (m.ravel() for m in mesh)))
columns[da.name] = da.to_numpy().ravel()
return pl.DataFrame(columns)
Model data¶
Show code
dist_scaler = make_1d_transform(fg_df["kick_distance"].to_numpy(), MinMaxScaler)
DATA = {"dist_std": dist_scaler.transform(fg_df["kick_distance"].to_numpy())}
DATA["made"] = fg_df["made"].to_numpy()
K_BASIS = 12
DATA["dist_basis_val"] = (
numpy_bspline_basis(DATA["dist_std"], K_BASIS, degree=3),
("obs", "dist_basis"),
)
COORDS = {"dist_basis": np.arange(K_BASIS)}
DATA["exposed"] = fg_df["is_exposed"].to_numpy()
DATA["turf"] = fg_df["is_turf"].to_numpy()
COORDS["season"] = enums["season"].categories.to_list()
DATA["season_val"] = fg_df["season"].to_physical().to_numpy()
K_SEASON_BASIS = 6
season_to_dist_basis = numpy_bspline_basis(
np.linspace(0, 1, K_BASIS), K_SEASON_BASIS, degree=3
)
COORDS["season_basis"] = np.arange(K_SEASON_BASIS)
COORDS["stadium"] = enums["stadium"].categories.to_list()
DATA["stadium_val"] = fg_df["stadium"].to_physical().to_numpy()
DATA["iced"] = fg_df["iced"].to_numpy()
DATA["use_stadium"] = np.full(len(fg_df), True)
Previous post model¶
We now rebuild the final model from the previous post.
with pm.Model(coords=COORDS) as base_model:
data = make_data(**DATA)
coefs = make_coefs("β0", "β_exposed", "β_turf", "β_iced")
coefs["β_stadium"] = hierarchical_normal("β_stadium", μ=0, dims="stadium")
w0 = spline_coef("w0")
w_season = deviation_coef("season", season_to_dist_basis)
w = pm.Deterministic("w", w0 + w_season, dims=("season", "dist_basis"))
f_dist = (data["dist_basis_val"] * w[data["season_val"]]).sum(axis=1)
# fmt: off
η = sum([
coefs["β0"],
coefs["β_exposed"] * data["exposed"],
coefs["β_iced"] * data["iced"],
coefs["β_turf"] * data["turf"],
data["use_stadium"] * coefs["β_stadium"][data["stadium_val"]],
f_dist
])
# fmt: on
p_made = pm.Deterministic("p_made", pm.math.sigmoid(η), dims="obs")
pm.Bernoulli("made_obs", p_made, observed=data["made"], dims="obs")
We now sample from this model's posterior distribution. Throughout this post, we will use nutpie's experimental normalizing flow adaptation functionality while sampling from our models' posterior distributions. As evidenced by the elevated $\hat{R}$ statistic in the final model of the previous post, we are starting from a model with rather complex posterior geometry. Adding kicker skill and other related quantities will only increase the complexity of the posterior geometry. Per the nutpie documentation,
Normalizing flow adaptation through Fisher HMC is a new sampling algorithm that automatically reparameterizes a model. It adds some computational cost outside model log-density evaluations, but allows sampling from much more difficult posterior distributions. For models with expensive log-density evaluations, the normalizing flow adaptation can also be much faster, if it can reduce the number of log-density evaluations needed to reach a given effective sample size.
While preparing this post, we found that the extra computational cost of normalizing flow adaptation is well worth the improved sample quality for the models we will build.
FLOW_KWARGS = {"adaptation": "flow", "chains": 6}
traces["base"], loos["base"] = sample(base_model, **FLOW_KWARGS)
We see indeed that the $\hat{R}$ statistics are quite good.
plot_rhat(traces["base"])
Player IRT model¶
We now extend the above model from the previous post to include player-specific skill levels, making this our first true item-response model.
In the previous post, the probability a kick is made is solely a function of its difficulty, as determined by distance and other environmental conditions. In this model, we add a per-kicker skill term, and the probability a kick is made becomes a function of the difference between the kicker's skill and the kick's difficulty.
In this IRT model, kickers correspond to test-takers and kicks to questions. Unlike in standard IRT models, no kick is shared across kickers, so the kick's difficulty is not a latent parameter, but rather inferred from its distance and other environmental factors.
Before specifying the model, we add indices corresponding to kickers to our data, along with the appropriate coordinates to facilitate interpretable visualization of our models.
DATA["kicker_val"] = fg_df["kicker_player_id"].to_physical().to_numpy()
kicker_coord_df = (
enums["kicker"]
.categories.cast(enums["kicker"])
.to_frame("kicker_player_id")
.join(kicker_df, on="kicker_player_id", how="left", maintain_order="left")
)
assert (kicker_coord_df["kicker_player_id"] == enums["kicker"].categories).all()
COORDS["kicker"] = kicker_coord_df["kicker_player_name"].to_list()
We also add a boolean flag indicating whether or not the per-kicker skill term should be used. This flag will allow us to sample from the posterior predictive distribution of the average kicker, who has skill zero.
DATA["use_θ0"] = np.full(len(fg_df), True)
The model for the kick's difficulty is the same as in the previous model, although here $\eta_i$ is replaced by $-\beta_i$.
with pm.Model(coords=COORDS) as player_model:
data = make_data(**DATA)
coefs = make_coefs("β0", "β_exposed", "β_turf", "β_iced")
coefs["β_stadium"] = hierarchical_normal("β_stadium", μ=0, dims="stadium")
w0 = spline_coef("w0")
w_season = deviation_coef("season", season_to_dist_basis)
w = pm.Deterministic("w", w0 + w_season, dims=("season", "dist_basis"))
f_dist = (data["dist_basis_val"] * w[data["season_val"]]).sum(axis=1)
# fmt: off
β = sum([
coefs["β0"],
coefs["β_exposed"] * data["exposed"],
coefs["β_iced"] * data["iced"],
coefs["β_turf"] * data["turf"],
data["use_stadium"] * coefs["β_stadium"][data["stadium_val"]],
f_dist
])
# fmt: on
We model kicker skill as a zero-mean hierarchical normal distribution, where the $j$-th kicker has skill $\theta_{0, j}$, given by
$$ \begin{align} \sigma_{\theta_0} & \sim \text{Half-}N(0, 2.5^2), \\ \theta_{0, j} & \sim N(0, \sigma_{\theta_0}^2). \end{align} $$
As with our other hierarchical normal components, we actually implement a noncentered parameterization of this distribution.
with player_model:
θ0 = hierarchical_normal("θ0", μ=0, dims="kicker")
θ = data["use_θ0"] * θ0[data["kicker_val"]]
We now define the probability that the $i$-th kick is made as
$$p_i = \text{sigm}(\theta_{0, j(i)} - \beta_i),$$
and add the likelihood of the observed kick data. Here $j(i)$ is the index of the kicker of the $i$-th kick.
with player_model:
η = θ - β
p_made = pm.Deterministic("p_made", pm.math.sigmoid(η), dims="obs")
pm.Bernoulli("made_obs", p_made, observed=data["made"], dims="obs")
We now sample from this model's posterior distribution.
traces["player"], loos["player"] = sample(player_model, **FLOW_KWARGS)
Once again we see no cause for concern with the $\hat{R}$ statistics.
plot_rhat(traces["player"])
Model comparison¶
We see that the player model is a significant improvement in terms of leave-one-out cross-validation (LOO-CV) score.
az.plot_compare(az.compare(loos, round_to="None"));
This improvement is not unexpected. In fact, it would be quite surprising if kicker skill did not play a significant role in field goal success.
Interpretation¶
We now visualize the latent skill parameters of the top and bottom ten kickers in our data set, restricted to those with at least 50 kicks.
MIN_KICKS = 50
N_TOP_BOT = 10
qual_kickers = kicker_df.filter(pl.col("kick_ct") >= MIN_KICKS)[
"kicker_player_name"
].to_list()
CI_WIDTH = 95
P_CLEAR = 1 - (1 - CI_WIDTH / 100) / 2
def rank_kickers(skill, *, kickers=None):
if kickers is not None:
skill = skill.sel(kicker=kickers)
return skill.sortby(skill.mean(("chain", "draw")), ascending=False)
def ext_kickers(trace, var_name, *, n=N_TOP_BOT, kickers=None):
ranked = rank_kickers(trace.posterior[var_name], kickers=kickers)
return ranked.isel(kicker=np.r_[0:n, -n:0]).assign_coords(
group=("kicker", [f"Top {n}"] * n + [f"Bottom {n}"] * n)
)
P_REF = fg_df["made"].mean()
LOGIT_P_REF = logit(P_REF)
def plot_kickers(skill, *, ci=CI_WIDTH):
kickers = skill["kicker"].to_numpy().tolist()
df = skill.pipe(to_polars)
color = {}
if "group" in skill.coords:
groups = dict(zip(kickers, skill["group"].to_numpy().tolist()))
df = df.with_columns(group=pl.col("kicker").replace_strict(groups))
color = {"color": "group"}
avg_df = pl.DataFrame({skill.name: [0.0, 0.0], "kicker": [kickers[0], kickers[-1]]})
plotter = (
so.Plot(df, x=skill.name, y="kicker")
.add(so.Range(linewidth=1), so.Est(errorbar=("pi", ci)), **color)
.add(so.Dot(), so.Agg(), **color)
.add(so.Path(color="k", linestyle="--"), data=avg_df, label="Average kicker")
.scale(y=so.Nominal(order=kickers))
.label(x="Make probability on a typical kick", y=None, color="")
.layout(size=(7, 1 + 0.25 * len(kickers)))
.plot()
)
ax = plot_ax(plotter)
ax.xaxis.set_major_formatter(
ticker.FuncFormatter(lambda x, _: f"{expit(LOGIT_P_REF + x):.0%}")
)
return plotter
plot_kickers(ext_kickers(traces["player"], "θ0", kickers=qual_kickers))
We will resist the urge to interpret this plot from a football perspective at this point, and instead defer most such analysis to our final model. However, from a statistical perspective, it is interesting to note that only a few players' 95% credible intervals are clearly separated from the average kicker's performance. Of the few that are clearly separated, more overperform than underperform. It is likely that only sufficiently successful kickers get the chance to take many kicks, with truly bad kickers exited from the league early in their careers. The final model of this post will address that survivorship bias before we draw any football conclusions.
Per-kicker distance model¶
In the previous post, we saw, unsurprisingly, that field goal success varied with distance. In this model, we will explore whether or not per-kicker skill varies with distance.
The kick ($\beta$) and baseline kicker ($\theta_0$) components of this model are the same as before.
with pm.Model(coords=COORDS) as player_dist_model:
data = make_data(**DATA)
coefs = make_coefs("β0", "β_exposed", "β_turf", "β_iced")
coefs["β_stadium"] = hierarchical_normal("β_stadium", μ=0, dims="stadium")
w0 = spline_coef("w0")
w_season = deviation_coef("season", season_to_dist_basis)
w = pm.Deterministic("w", w0 + w_season, dims=("season", "dist_basis"))
f_dist = (data["dist_basis_val"] * w[data["season_val"]]).sum(axis=1)
# fmt: off
β = sum([
coefs["β0"],
coefs["β_exposed"] * data["exposed"],
coefs["β_iced"] * data["iced"],
coefs["β_turf"] * data["turf"],
data["use_stadium"] * coefs["β_stadium"][data["stadium_val"]],
f_dist
])
# fmt: on
θ0 = hierarchical_normal("θ0", μ=0, dims="kicker")
We will model the per-kicker distance effects as quadratic polynomials. While we do use more flexible splines to model the global relationship between distance and success, adding a per-kicker distance spline would greatly increase the number of parameters in our model. We will consider doing so if this coarser model shows signs of promise.
The per-kicker coefficients for (rescaled) distance and (rescaled) distance squared are drawn from the same type of zero-mean hierarchical normal distribution as $\theta_0$.
with player_dist_model:
θ_dist = hierarchical_normal("θ_dist", μ=0, dims="kicker")
θ_dist_sq = hierarchical_normal("θ_dist_sq", μ=0, dims="kicker")
We now introduce a combined per-kick player component
$$\theta_i = \theta_{0, j(i)} + \theta_{\text{dist}, j(i)} \cdot x_{\text{dist}, i} + \theta_{\text{dist}^2, j(i)} \cdot x_{\text{dist}, i}^2,$$
where $x_{\text{dist}, i}$ is the rescaled distance of the $i$-th kick.
with player_dist_model:
# fmt: off
θ = data["use_θ0"] * sum([
θ0[data["kicker_val"]],
θ_dist[data["kicker_val"]] * data["dist_std"],
θ_dist_sq[data["kicker_val"]] * data["dist_std"]**2
])
# fmt: on
With this definition, we have
$$\eta_i = \theta_i - \beta_i,$$
and the same likelihood as in prior models, given $\eta_i$.
with player_dist_model:
η = θ - β
p_made = pm.Deterministic("p_made", pm.math.sigmoid(η), dims="obs")
pm.Bernoulli("made_obs", p_made, observed=data["made"], dims="obs")
We now sample from this model's posterior distribution.
traces["player_dist"], loos["player_dist"] = sample(player_dist_model, **FLOW_KWARGS)
Once again we see no cause for concern with the $\hat{R}$ statistics.
plot_rhat(traces["player_dist"])
Model comparison¶
Interestingly, we see that this model is marginally worse than the previous one in terms of LOO-CV.
az.plot_compare(az.compare(loos, round_to="None"));
Interpretation¶
The above model comparison should make us skeptical of further developing per-kicker distance effects. Here we visualize the posterior distributions of the scales of each per-kicker parameter.
pc = az.plot_dist(
traces["player_dist"],
var_names=["σ_θ0", "σ_θ_dist", "σ_θ_dist_sq"],
aes={"color": ["__variable__"]},
cols=[],
visuals={
"credible_interval": False,
"point_estimate": False,
"point_estimate_text": False,
"title": False,
},
)
pc.viz["plot"].item().set_xlim(left=0)
pc.add_legend("__variable__")
We see that while the posterior scale of $\theta_0$ is well-separated from zero, that is not the case for either of the scales of the per-kicker distance coefficients. In addition, the scale of $\theta_{\text{dist}^2}$ looks to be only weakly identified. Due to these posterior distributions and the model comparison above, it doesn't look like we can produce useful per-kicker estimates of the distance effect. We will leave these terms out of subsequent models and will not pursue more flexible per-kicker spline models.
Experience¶
We now turn to modeling the impact of the kicker's experience (number of years in the league) on success rate. Note that we defined yrs_exp above as the number of years between the kicker's rookie season and the one in which they are taking the kick in question. Some kickers had their rookie season before the data starts in 1999.
First we do some light feature engineering, rescaling years of experience in the league to be on a zero-one scale.
exp_scaler = make_1d_transform(fg_df["yrs_exp"].to_numpy(), MinMaxScaler)
DATA["exp_std"] = exp_scaler.transform(fg_df["yrs_exp"].to_numpy())
We will model experience using a spline, just like we did for the baseline (average-season) distance relationship. To do so, we build the basis data and coordinates.
K_EXP_BASIS = 6
DATA["exp_basis_val"] = (
numpy_bspline_basis(DATA["exp_std"], K_EXP_BASIS, degree=3),
("obs", "exp_basis"),
)
COORDS["exp_basis"] = np.arange(K_EXP_BASIS)
The kick ($\beta$) and baseline kicker ($\theta_0$) components of this model are the same as before.
with pm.Model(coords=COORDS) as exp_model:
data = make_data(**DATA)
coefs = make_coefs("β0", "β_exposed", "β_turf", "β_iced")
coefs["β_stadium"] = hierarchical_normal("β_stadium", μ=0, dims="stadium")
w0 = spline_coef("w0")
w_season = deviation_coef("season", season_to_dist_basis)
w = pm.Deterministic("w", w0 + w_season, dims=("season", "dist_basis"))
f_dist = (data["dist_basis_val"] * w[data["season_val"]]).sum(axis=1)
# fmt: off
β = sum([
coefs["β0"],
coefs["β_exposed"] * data["exposed"],
coefs["β_iced"] * data["iced"],
coefs["β_turf"] * data["turf"],
data["use_stadium"] * coefs["β_stadium"][data["stadium_val"]],
f_dist
])
# fmt: on
θ0 = hierarchical_normal("θ0", μ=0, dims="kicker")
We let $f_{\text{exp}}(t)$ be the spline modeling the impact of experience on the make rate for a kicker with $t$ (rescaled) years of experience.
We then define
$$\theta_i = \theta_{0, j(i)} + f_{\text{exp}}(t_i),$$
where $t_i$ is the (rescaled) number of years of experience of the kicker of the $i$-th kick (during the season in which it occurred).
with exp_model:
w_exp = spline_coef("w_exp", dims="exp_basis")
f_exp = data["exp_basis_val"] @ w_exp
θ = data["use_θ0"] * θ0[data["kicker_val"]] + f_exp
With $\theta_i$ defined, the rest of the model is the same as before.
with exp_model:
η = θ - β
p_made = pm.Deterministic("p_made", pm.math.sigmoid(η), dims="obs")
pm.Bernoulli("made_obs", p_made, observed=data["made"], dims="obs")
We now sample from this model's posterior distribution.
traces["exp"], loos["exp"] = sample(exp_model, **FLOW_KWARGS)
Once again we see no cause for concern with the $\hat{R}$ statistics.
plot_rhat(traces["exp"])
Model comparison¶
We see that the experience model is a marginal improvement in terms of leave-one-out cross-validation (LOO-CV) score.
az.plot_compare(az.compare(loos, round_to="None"));
Interpretation¶
We now sample from the model's posterior predictive distribution to visualize the experience curve.
As above, we redefine some of the prior post's some posterior predictive sampling helpers, hiding them by default.
Show code
def reindex_array(da, *, obs_dim="obs", **coords):
da = da.assign_coords({name: (obs_dim, values) for name, values in coords.items()})
coord_names = list(coords)
if len(coord_names) == 1:
return da.swap_dims({obs_dim: coord_names[0]})
else:
return da.set_index({obs_dim: coord_names}).unstack(obs_dim)
def sample_posterior_predictive(trace, *, seed=SEED, coords=None):
pm.sample_posterior_predictive(
trace,
var_names=["p_made"],
predictions=True,
random_seed=seed,
extend_inferencedata=True,
)
if coords:
trace["predictions"]["p_made"] = reindex_array(
trace["predictions"]["p_made"], **coords
)
def make_pp_df(*pp_data):
fst, *rest = pp_data
df = pl.DataFrame(fst)
for data in rest:
df = df.join(pl.DataFrame(data), how="cross")
return df
def enum_cols(enum, name, values):
s = pl.Series(values, dtype=enum)
return {f"{name}_val": s.to_physical(), name: s}
def set_data(df):
data = {}
model = pm.modelcontext(None)
for var in model.data_vars:
if var.name in df:
data[var.name] = df[var.name].to_numpy()
else:
value, _ = unpack_value_dims(DATA[var.name])
data[var.name] = np.empty(df.shape[0], dtype=value.dtype)
pm.set_data(data)
def restore_data():
model = pm.modelcontext(None)
pm.set_data(
{var.name: unpack_value_dims(DATA[var.name])[0] for var in model.data_vars}
)
def add_posterior_ev(
plot,
*,
data=None,
ci=True,
color=None,
color_by=None,
label=None,
):
color_kwargs = {} if color is None else {"color": color}
variables = {}
if color_by is not None:
variables["color"] = color_by
plot = plot.add(
so.Line(**color_kwargs), so.Agg(), data=data, label=label, **variables
)
if ci:
plot = plot.add(
so.Band(**color_kwargs), so.Est(errorbar=("pi", 95)), data=data, **variables
)
return plot
We now define the posterior predictive grid that we want to sample along.
PP_EXP = np.linspace(fg_df["yrs_exp"].min(), fg_df["yrs_exp"].max(), 100)
PP_EXP_STD = exp_scaler.transform(PP_EXP)
PP_EXP_DATA = {
"exp_std": PP_EXP_STD,
"exp_basis_val": numpy_bspline_basis(PP_EXP_STD, K_EXP_BASIS, degree=3),
"exp": PP_EXP,
}
REF_DIST = 40.0
REF_DIST_STD = dist_scaler.transform([REF_DIST])
REF_KICKER = enums["kicker"].categories[0]
pp_df = make_pp_df(
PP_EXP_DATA,
{
"dist_std": REF_DIST_STD,
"dist_basis_val": numpy_bspline_basis(REF_DIST_STD, K_BASIS, degree=3),
},
{"exposed": [True]},
{"turf": [False]},
{"iced": [False]},
enum_cols(enums["season"], "season", [enums["season"].categories[-1]]),
{"use_stadium": [False]},
enum_cols(enums["stadium"], "stadium", [enums["stadium"].categories[0]]),
{"use_θ0": [False]},
enum_cols(enums["kicker"], "kicker", [REF_KICKER]),
)
With this grid defined, we sample from the model's posterior predictive distribution.
with exp_model:
set_data(pp_df)
sample_posterior_predictive(
traces["exp"], coords=pp_df[["exp"]].to_dict(as_series=False)
)
restore_data()
We now visualize the experience curve for a reference kick (40 yards, outdoors, on grass, no prior icing timeout).
plot = (
add_posterior_ev(
so.Plot(
traces["exp"].predictions["p_made"].pipe(to_polars), x="exp", y="p_made"
)
)
.limit(x=(0, PP_EXP.max()))
.label(x="Years of experience", y=MADE_LABEL)
)
plotter = plot_axis_ticks(
plot,
y_formatter=PCT_FORMATTER(),
)
plot_ax(plotter).axhline(
traces["exp"].predictions["p_made"].sel(exp=0, method="nearest").mean().item(),
c="k",
ls="--",
)
plotter
We see a posterior expected value that increases steadily from about zero to five years of experience and then levels out, with a slight decline after about ten years of experience. Curiously, the 95% credible interval never cleanly separates from the rookie season (no experience) make probability.
This estimate, however, includes quite a bit of uncertainty from $\beta$ that is unrelated to experience. We can sidestep this uncertainty by plotting the difference in success rates between a rookie and a more experienced kicker (under our reference conditions).
def rise_df(trace):
p = trace.predictions["p_made"]
return (p - p.sel(exp=0, method="nearest")).rename("rise").pipe(to_polars)
plot = add_posterior_ev(so.Plot(rise_df(traces["exp"]), x="exp", y="rise")).limit(
x=(0, PP_EXP.max())
)
plotter = plot_axis_ticks(
plot.label(x="Years of experience", y="Change in make\nprobability vs. rookie"),
y_formatter=PCT_FORMATTER(),
)
plot_ax(plotter).axhline(0, c="k", ls="--")
plotter
We see that this quantity has credible intervals well-separated from zero throughout common career lengths (most kickers do not kick for 20+ years). This model provides clear evidence for an experience effect, although we will wait until our next, final model to interpret this effect more.
Joint longitudinal and survival model¶
For our final model, we will address the survivorship bias we mentioned when interpreting the initial player IRT model. Fortunately, there is a well-established literature on joint models for longitudinal and survival outcomes. In fact, I have previously written a post implementing such a model in PyMC. In our context, the longitudinal outcome is whether or not a given kick is made, and the survival outcome is whether or not a kicker plays for another season.
The model for the longitudinal outcome is the same as it was in the last model.
with pm.Model(coords=COORDS) as joint_model:
data = make_data(**DATA)
coefs = make_coefs("β0", "β_exposed", "β_turf", "β_iced")
coefs["β_stadium"] = hierarchical_normal("β_stadium", μ=0, dims="stadium")
w0 = spline_coef("w0")
w_season = deviation_coef("season", season_to_dist_basis)
w = pm.Deterministic("w", w0 + w_season, dims=("season", "dist_basis"))
f_dist = (data["dist_basis_val"] * w[data["season_val"]]).sum(axis=1)
# fmt: off
β = sum([
coefs["β0"],
coefs["β_exposed"] * data["exposed"],
coefs["β_iced"] * data["iced"],
coefs["β_turf"] * data["turf"],
data["use_stadium"] * coefs["β_stadium"][data["stadium_val"]],
f_dist
])
# fmt: on
w_exp = spline_coef("w_exp", dims="exp_basis")
f_exp = data["exp_basis_val"] @ w_exp
θ0 = hierarchical_normal("θ0", μ=0, dims="kicker")
θ = data["use_θ0"] * θ0[data["kicker_val"]] + f_exp
η = θ - β
p_made = pm.Deterministic("p_made", pm.math.sigmoid(η), dims="obs")
pm.Bernoulli("made_obs", p_made, observed=data["made"], dims="obs")
The survival component of the model requires more data than we have used so far. First, we produce a dataframe with one row per kicker and columns
-
kicker_player_id, the kicker's player id, -
total_yrs_exp, the total years of experience the kicker has through the last season they appear in our data (the length of their career in seasons minus one), -
rookie_season, the season in which the kicker entered the league, and -
censored, whether or not the kicker was still playing during the last season present in our play by play data.
surv_df = (
enums["kicker"]
.categories.cast(enums["kicker"])
.to_frame("kicker_player_id")
.join(
fg_df.group_by("kicker_player_id").agg(
pl.col("yrs_exp").max().alias("total_yrs_exp"),
pl.col("rookie_season").first(),
censored=pl.col("season").max() == enums["season"].categories.max(),
),
on="kicker_player_id",
how="left",
maintain_order="left",
)
)
# ensure that the kickers are in the dataframe in the correct order
assert (
surv_df["kicker_player_id"].to_physical().to_numpy()
== np.arange(len(enums["kicker"].categories))
).all()
surv_df
We then transform this dataframe into another that contains one row for each season each kicker attempted a field goal, with columns
-
kicker_val, the index of the kicker, corresponding tosurv_df["kicker_player_id"].to_physical(), -
kicker_player_id, the kicker's player id, -
censored, as above, -
exp, the kicker's years of experience during the season represented by that row, and -
exited, whether or not the row corresponds to the kicker's final season in the league.
hazard_df = (
surv_df.with_row_index("kicker_val")
.with_columns(pl.col("kicker_val").cast(pl.Int64))
.join(
fg_df.select("kicker_player_id", exp="yrs_exp").unique(), on="kicker_player_id"
)
.with_columns(
exited=(pl.col("exp") == pl.col("total_yrs_exp")) & ~pl.col("censored")
)
.drop("rookie_season", "total_yrs_exp")
)
hazard_df
We use this data to construct a Cox proportional hazard model, performing inference on this model using the Poisson likelihood approximation that I have posted about previously.
We model the log baseline hazard for each year of experience, $t$, $\log \lambda_0(t)$, as a hierarchical normal distribution.
joint_model.add_coords(
{
"exp_hazard": np.arange(hazard_df["exp"].max() + 1),
"hazard_obs": np.arange(hazard_df.height),
}
)
with joint_model:
log_λ0 = hierarchical_normal("log_λ0", dims="exp_hazard")
λ0 = pm.math.exp(log_λ0)
The log kicker-specific hazard ratio of the $j$-th kicker is given by $-\nu \cdot \theta_{0, j}$, where $\nu \sim N(0, 2.5^2).$ This use of $\theta_0$ in both the longitudinal and survival models helps mitigate the survivorship bias previously discussed. The hazard for the $j$-th kicker at $t$ years of experience is then
$$\lambda_j(t) = \lambda_0(t) \cdot \exp(-\nu \cdot \theta_{0, j}).$$
The negative sign in the exponential here means that if kicker skill (as measured through $\theta_0$) is positively correlated with career length, which it should be, the posterior distribution of $\nu$ will be concentrated above zero.
with joint_model:
ν = pm.Normal("ν", 0, 2.5)
λ = λ0[hazard_df["exp"].to_numpy()] * pm.math.exp(
-ν * θ0[hazard_df["kicker_val"].to_numpy()]
)
We approximate this model's likelihood using a Poisson distribution as follows.
with joint_model:
pm.Poisson("exited", λ, observed=hazard_df["exited"].to_numpy(), dims="hazard_obs")
We now sample from this model's posterior distribution.
traces["joint"], loos["joint"] = sample(joint_model, target_accept=0.95, **FLOW_KWARGS)
Once again we see no cause for concern with the $\hat{R}$ statistics.
plot_rhat(traces["joint"])
Model comparison¶
We see that the joint model is a significant improvement in terms of leave-one-out cross-validation (LOO-CV) score.
az.plot_compare(az.compare(loos, round_to="None"));
Interpretation¶
First we visualize the posterior distribution of $\nu$ to understand the influence of the survival model.
az.plot_dist(traces["joint"], var_names="ν");
We see that $\nu$'s posterior distribution is concentrated well to the right of zero, confirming a positive correlation between kicker skill, as measured in $\theta_0$, and career duration.
We now sample from this model's posterior predictive distribution, using the same reference kick as in the previous model.
with joint_model:
set_data(pp_df)
sample_posterior_predictive(
traces["joint"], coords=pp_df[["exp"]].to_dict(as_series=False)
)
restore_data()
We now compare the experience curves of the final two models.
rise_all = pl.concat(
[
rise_df(traces["exp"]).with_columns(model=pl.lit("Naive")),
rise_df(traces["joint"]).with_columns(model=pl.lit("Joint")),
]
)
plot = add_posterior_ev(so.Plot(rise_all, x="exp", y="rise"), color_by="model").limit(
x=(0, PP_EXP.max())
)
plotter = plot_axis_ticks(
plot.label(
x="Years of experience",
y="Change in make\nprobability vs. rookie",
color="Model",
),
y_formatter=PCT_FORMATTER(),
)
plot_ax(plotter).axhline(0, c="k", ls="--")
plotter
We see that although the posterior expected improvement over a rookie is somewhat smaller, the joint model's curve and credible interval still shows separation from zero in the mid-career (approximately four to fifteen years of experience).
Even after mitigating survivorship bias, we conclude that there is a small experience effect among NFL kickers, with the average kicker with ten years of experience having approximately a 2 percentage point higher chance of making our reference kick than an average rookie.
To better understand the survival model's impact, we plot each kicker's posterior expected $\theta_0$ value for each of the final two models, colored by that kicker's number of kicks.
θ0_df = kicker_coord_df.with_columns(
exp=traces["exp"].posterior["θ0"].mean(dim=("chain", "draw")).to_numpy(),
joint=traces["joint"].posterior["θ0"].mean(dim=("chain", "draw")).to_numpy(),
)
θ0 = θ0_df.select("exp", "joint").to_numpy()
pad = 0.05 * np.ptp(θ0)
lo, hi = θ0.min() - pad, θ0.max() + pad
plotter = (
so.Plot(θ0_df, x="exp", y="joint", color="kick_ct")
.add(so.Dot(alpha=0.7))
.scale(
color=so.Continuous("flare_r", trans="log")
.tick(at=[5, 25, 100, 400])
.label(like="{x:.0f}")
)
.limit(x=(lo, hi), y=(lo, hi))
.label(x="Experience model", y="Joint model", color="Kicks", title=r"$\theta_0$")
.plot()
)
ax = plot_ax(plotter)
ax.axline((0, 0), (1, 1), c="k", ls="--")
ax.set_box_aspect(1)
legend = plotter._figure.legends[0]
legend.set_loc("center left")
legend.set_bbox_to_anchor((1.02, 0.5), transform=ax.transAxes)
plotter
We see that kickers with many kicks tend to have a higher $\theta_0$ under the joint model than under the experience model, whereas most kickers with fewer kicks have a lower $\theta_0$. We also see that kick count is highly correlated with $\theta_0$. This correlation is natural, as better kickers have their contracts renewed and earn the right to take more kicks, while bad kickers are cut early in their careers. The experience model only indirectly takes advantage of kicker longevity through its weak proxy, number of kicks, which controls how much each kicker's skill estimate is shrunk towards the global mean of zero. It therefore concentrates $\theta_0$ for kickers with few attempts near zero, considering them average. By explicitly sharing the skill parameter, $\theta_0$, with the survival model, the joint model has enough evidence to pull short-lived kickers away from zero into more negative values of $\theta_0$. An analogous mechanism tends to increase the $\theta_0$ values of long-lived kickers.
With the joint model in hand, we are now ready for some football analysis. We begin by revisiting the top- and bottom-ten kicker visualization from the initial player IRT model.
plot_kickers(ext_kickers(traces["joint"], "θ0", kickers=qual_kickers))
Immediately, we see more of the top kickers have 95% credible intervals clearly separated from the average kicker.
plot_axis_ticks(
so.Plot(
pl.DataFrame(
{
"Player": (traces["player"].posterior["θ0"] > 0)
.mean(dim=("chain", "draw"))
.to_numpy(),
"Experience": (traces["exp"].posterior["θ0"] > 0)
.mean(dim=("chain", "draw"))
.to_numpy(),
"Joint": (traces["joint"].posterior["θ0"] > 0)
.mean(dim=("chain", "draw"))
.to_numpy(),
}
)
.select(pl.all() > P_CLEAR)
.sum()
.unpivot(variable_name="model", value_name="kickers"),
x="model",
y="kickers",
)
.add(so.Bar())
.label(x="Model", y="Kickers whose 95% CI\n is above average"),
y_locator=ticker.MaxNLocator(integer=True),
)
In fact, we see that the joint model has many more kickers clearly better than average than the player and experience models. Below we plot all the kickers whose 95% credible intervals lie entirely above the average kicker's performance.
p_above = (traces["joint"].posterior["θ0"] > 0).mean(("chain", "draw"))
plot_kickers(
rank_kickers(
traces["joint"].posterior["θ0"].isel(kicker=(p_above > P_CLEAR).to_numpy())
)
)
Unsurprisingly, we see a number of notable kickers of the last 25 years in this list.
There are, however, a number of notable kickers not present on the above list as well.
NAMES = [
"M.Crosby",
"D.Akers",
"Y.Koo",
"G.Zuerlein",
"J.Elam",
]
plot_kickers(rank_kickers(traces["joint"].posterior["θ0"], kickers=NAMES))
We see that many of these kickers have expected values significantly above average, but credible intervals that are not quite cleanly separated.
The following plots focus on a single kicker, comparing them to an average kicker on the same kicks and also to an average kicker on the same kicks across all seasons. These plots will give us a sense of whether these ratings are due to the combination of the time period during which the kicker played and their kick selection.
def makes_above_expected(trace, kicker):
kicker_id = kicker_coord_df.filter(pl.col("kicker_player_name") == kicker)[
"kicker_player_id"
].item()
kicks = (
fg_df.with_row_index("obs")
.filter(pl.col("kicker_player_id") == kicker_id)
.sort("game_date", "play_id")
)
p = trace.posterior["p_made"].isel(obs=kicks["obs"].to_numpy())
p_avg = expit(logit(p) - trace.posterior["θ0"].sel(kicker=kicker))
made = xr.DataArray(kicks["made"].to_numpy().astype(float), dims="obs")
lo, mid, hi = (
(made - p_avg)
.cumsum("obs")
.quantile([0.025, 0.5, 0.975], dim=("chain", "draw"))
)
n_made, n_kicks = fg_df["made"].sum(), fg_df.height
p_lo, p_hi = beta.ppf([0.025, 0.975], 1 + n_made, 1 + n_kicks - n_made)
k = np.arange(1, kicks.height + 1)
cum_made = made.to_numpy().cumsum()
return kicks.select("season").with_columns(
kick=pl.int_range(1, kicks.height + 1),
lo=lo.to_numpy(),
mid=mid.to_numpy(),
hi=hi.to_numpy(),
naive=cum_made - k * P_REF,
naive_lo=cum_made - k * p_hi,
naive_hi=cum_made - k * p_lo,
)
def plot_makes_above_expected(trace, kicker):
df = makes_above_expected(trace, kicker)
plotter = (
so.Plot(df, x="kick")
.add(so.Band(), ymin="lo", ymax="hi")
.add(so.Line(), y="mid", label="Above an average kicker, same kicks")
.add(so.Band(color="k", alpha=0.15), ymin="naive_lo", ymax="naive_hi")
.add(
so.Line(color="k", linestyle="--"),
y="naive",
label="Above the all-years league rate",
)
.limit(x=(df["kick"].min(), df["kick"].max()))
.label(x="Season", y="Cumulative makes above expected", title=kicker)
.plot()
)
ax = plot_ax(plotter)
ax.axhline(0, c="k", lw=0.8)
starts = (
df.group_by("season", maintain_order=True)
.agg(pl.col("kick").min())
.with_columns(
span=pl.col("kick").shift(-1, fill_value=df["kick"].max() + 1)
- pl.col("kick")
)
.filter(pl.col("span") >= 10)
)
ax.set_xticks(
starts["kick"].to_list(),
labels=starts["season"].cast(pl.String).to_list(),
rotation=45,
ha="right",
rotation_mode="anchor",
)
return plotter
We see that a hometown favorite of my Philadelphia Eagles, David Akers, generally outperformed an average contemporary, but that his era featured relatively weaker kicking.
plot_makes_above_expected(traces["joint"], "D.Akers")
Unfortunately even such an analysis does not redeem Billy Cundiff.
plot_makes_above_expected(traces["joint"], "B.Cundiff")
The following widget allows the reader to see this chart for any kicker with more than fifty attempts in our data.
KICKER_PLOT_DIR = Path("kicker_plots")
KICKER_PLOT_DIR.mkdir(exist_ok=True)
plot_kickers_df = kicker_coord_df.filter(pl.col("kick_ct") >= MIN_KICKS)
for kicker_id, name in progress_bar(
plot_kickers_df.select("kicker_player_id", "kicker_player_name").iter_rows(),
total=plot_kickers_df.height,
):
plotter = plot_makes_above_expected(traces["joint"], name)
plotter.save(KICKER_PLOT_DIR / f"{kicker_id}.png", dpi=100, bbox_inches="tight")
plt.close(plotter._figure)
IMG_BASE = "https://austinrochford.com/resources/fg_irt/kickers"
INITIAL_KICKER = "D.Akers"
selector_df = plot_kickers_df.sort("kicker_player_name")
initial_id = selector_df.filter(pl.col("kicker_player_name") == INITIAL_KICKER)[
"kicker_player_id"
].item()
options = "\n".join(
f'<option value="{kicker_id}"{" selected" if kicker_id == initial_id else ""}>'
f"{escape(name)}</option>"
for kicker_id, name in selector_df.select(
"kicker_player_id", "kicker_player_name"
).iter_rows()
)
HTML(
f"""
<select onchange="document.getElementById('kicker-plot').src = '{IMG_BASE}/' + this.value + '.png'">
{options}
</select>
<img id="kicker-plot" src="{IMG_BASE}/{initial_id}.png" alt="Cumulative makes above expected" style="max-width: 100%">
"""
)
Introducing kicker skill to the previous post's model has proven an interesting challenge. While it's unsurprising that kicker skill matters, it is somewhat surprising that we found no evidence for per-kicker distance effects. What we did find, however, is a significant survivorship effect, shown by the fact that our joint model has the highest ELPD.
This post is available as a Jupyter notebook here.
%load_ext watermark
%watermark -n -u -v -iv