Here’s a worked example of how you might build a simple Bayesian regression in PyMC4 to predict “case end time” from a set of intra‐operative events. We’ll:
- Assume you have N surgeries
- For each surgery i, you’ve recorded K event–features (e.g. time‐to‐event-A, count of event-B, binary indicator that event-C occurred, …), possibly with missing values.
- Your target yᵢ is the total case length (in minutes).
We’ll do a log-normal regression so that yᵢ>0 naturally, and we’ll impute any missing X’s with simple normal priors (you can substitute more informed priors if you like).
import pandas as pd
import numpy as np
import pymc as pm
import arviz as az
# -----------------------------------------------------------------------------
# 1) Load / preprocess your data
# -----------------------------------------------------------------------------
# Suppose df has columns:
# - 'case_id', 'case_end_time'
# - event features: 't_event1', 't_event2', 'count_event3', 'had_event4', ...
df = pd.read_csv("your_surgical_data.csv")
# Target
y = df["case_end_time"].values
# Feature matrix
feature_cols = ["t_event1", "t_event2", "count_event3", "had_event4"]
X_raw = df[feature_cols]
# Standardize continuous features; leave binaries alone
X = X_raw.copy()
for c in ["t_event1", "t_event2", "count_event3"]:
mu, sd = X[c].mean(), X[c].std()
X[c] = (X[c] - mu) / sd
# Convert to numpy array (mask missing as np.nan)
Xmat = X.values
N, K = Xmat.shape
# -----------------------------------------------------------------------------
# 2) Specify the PyMC model
# -----------------------------------------------------------------------------
with pm.Model() as surgical_model:
# 2a) Priors on regression coefficients
α = pm.Normal("α", mu=0.0, sigma=10.0)
β = pm.Normal("β", mu=0.0, sigma=5.0, shape=K)
# 2b) Handle missing X via simple imputation priors
# For each feature column, any np.nan gets its own latent prior
# (More advanced: hierarchical, or use pm.MutableData + pm.MaskedVariable)
X_imputed = pm.MutableData("X_imputed", Xmat)
for j in range(K):
mask = np.isnan(Xmat[:, j])
if mask.any():
# Impute these entries from a normal – you could center at column mean
mu_j = Xmat[~mask, j].mean()
sigma_j = Xmat[~mask, j].std()
imputed_vals = pm.Normal(f"x_imp_{j}",
mu=mu_j,
sigma=sigma_j,
shape=mask.sum())
# plug in
X_imputed.set_value(np.where(mask[:, None] & (np.arange(K)==j), imputed_vals, X_imputed.get_value()))
# 2c) Likelihood for positive time: log-normal regression
σ = pm.HalfNormal("σ", sigma=5.0)
mu = α + pm.math.dot(X_imputed, β)
y_obs = pm.LogNormal("y_obs", mu=mu, sigma=σ, observed=y)
# 2d) Inference
trace = pm.sample(
tune=1000,
draws=1000,
target_accept=0.9,
return_inferencedata=True
)
# -----------------------------------------------------------------------------
# 3) Posterior checks
# -----------------------------------------------------------------------------
az.plot_trace(trace, var_names=["α", "β", "σ"])
az.summary(trace, var_names=["α", "β", "σ"])
Explanation of key pieces:
- We standardize continuous X’s so our Normal(0,5) priors on β are sensible.
- Any missing X’s are “imputed” in the model by additional Normal latent variables (you can swap in more realistic priors or hierarchical structure).
- We regress on log (time) by using a LogNormal likelihood. This guarantees positive predictions.
- The posterior on α, β, σ tells you how each event‐feature shifts the expected case length.
— You can extend this to
• Hierarchical models (by surgeon, by procedure type)
• More advanced survival likelihoods (Weibull, Cox‐proportional, piecewise hazards)
• Time‐varying event effects (splines, Gaussian processes)
… but the above gives you a minimal working PyMC example. Let me know if you want to dig deeper on any of those! 😊