youkad's picture
State the dugong reference fit with lam's prior folded onto lam > 0, and each score's Monte Carlo standard error
452f0eb verified
Raw History Blame Contribute Delete
30.6 kB
task,program_id,role,outcome,failure,heldout_log_score,source
dugongs,01-reference,Reference,scored,,-4.5586,"import numpy as np
import pymc as pm
def model(data):
""""""Dugong length against age: the growth curve and priors of BoxingGym's
dugongs environment, with a Normal likelihood and a fixed noise scale.
""""""
age = np.asarray(data[""age""], dtype=float)
y = np.asarray(data[""length""], dtype=float)
with pm.Model() as dugongs_model:
age_data = pm.Data(""age_data"", age)
alpha = pm.Normal(""alpha"", mu=2.0, sigma=0.2)
beta = pm.Normal(""beta"", mu=1.5, sigma=0.5)
lam = pm.Normal(""lam"", mu=0.4, sigma=0.5)
mu = alpha - beta * pm.math.abs(lam) ** age_data
pm.Normal(""length"", mu=mu, sigma=0.25, observed=y)
return dugongs_model
"
dugongs,02-floor-model,Floor model,scored,,-14.0898,"import numpy as np
import pymc as pm
def model(data):
""""""Floor model: ignores age and fits one mean length.""""""
y = np.asarray(data[""length""], dtype=float)
with pm.Model() as null_model:
intercept = pm.Normal(""intercept"", mu=0.0, sigma=10.0)
sigma = pm.HalfNormal(""sigma"", sigma=5.0)
pm.Normal(""length"", mu=intercept, sigma=sigma, observed=y)
return null_model
"
dugongs,03-single-attempt-1,Single attempt 1,scored,,-4.6292,"import pymc as pm
import numpy as np
def model(data):
""""""
Probabilistic model of dugong length as a function of age.
Uses a von Bertalanffy growth model or similar asymptotic growth curve.
The von Bertalanffy model is commonly used for animal growth:
L(t) = L_inf * (1 - exp(-k * (t - t0)))
Parameters:
- L_inf: asymptotic maximum length
- k: growth rate coefficient
- t0: theoretical age at which length is zero (often negative)
We place weakly informative priors on these parameters.
""""""
age = data[""age""]
length = data[""length""]
with pm.Model() as dugong_model:
# Priors for von Bertalanffy parameters
# L_inf: asymptotic length, must be positive. Based on data, max length is ~2.74
# So L_inf should be somewhat larger than that.
L_inf = pm.HalfNormal(""L_inf"", sigma=2.0)
# k: growth rate, positive
k = pm.HalfNormal(""k"", sigma=1.0)
# t0: theoretical age at zero length. Can be negative.
# We use a Normal prior centered at a small negative value with reasonable spread
t0 = pm.Normal(""t0"", mu=-0.5, sigma=0.5)
# Deterministic growth curve
mu = L_inf * (1 - pm.math.exp(-k * (age - t0)))
# Ensure mu is positive (should be by construction if L_inf > 0 and k > 0)
# Add likelihood
sigma = pm.HalfNormal(""sigma"", sigma=0.2)
length_obs = pm.Normal(""length_obs"", mu=mu, sigma=sigma, observed=length)
return dugong_model
"
dugongs,04-single-attempt-2,Single attempt 2,scored,,-3.1969,"import pymc as pm
import numpy as np
def model(data):
age = data['age']
length = data['length']
with pm.Model() as dugong_model:
# Priors for the von Bertalanffy growth parameters
# L_infinity: asymptotic length
L_inf = pm.HalfNormal('L_inf', sigma=2)
# k: growth rate
k = pm.HalfNormal('k', sigma=1)
# Observation noise
sigma = pm.HalfNormal('sigma', sigma=0.2)
# Expected length
# Using the von Bertalanffy growth function: L(t) = L_inf * (1 - exp(-k * t))
mu = L_inf * (1 - pm.math.exp(-k * age))
# Likelihood
likelihood = pm.Normal('likelihood', mu=mu, sigma=sigma, observed=length)
return dugong_model
"
dugongs,05-single-attempt-3,Single attempt 3,scored,,-4.6876,"import pymc as pm
import numpy as np
def model(data):
ages = data['age']
lengths = data['length']
with pm.Model() as model:
# Priors for Von Bertalanffy parameters
# L_inf: asymptotic length. Max observed is ~2.74.
# A HalfNormal with sigma=2.0 allows reasonable mass above 2.74.
L_inf = pm.HalfNormal('L_inf', sigma=2.0)
# k: growth coefficient. Positive.
k = pm.HalfNormal('k', sigma=1.0)
# t0: theoretical age at length 0. Can be negative.
t0 = pm.Normal('t0', mu=0.0, sigma=1.0)
# Deterministic growth curve
mu = L_inf * (1 - pm.math.exp(-k * (ages - t0)))
# Observation noise
sigma = pm.HalfNormal('sigma', sigma=0.2)
# Likelihood
length_obs = pm.Normal('length_obs', mu=mu, sigma=sigma, observed=lengths)
return model
"
dugongs,06-single-attempt-4,Single attempt 4,scored,,-3.2267,"import pymc as pm
import numpy as np
def model(data):
age = data['age']
length = data['length']
with pm.Model() as dugong_model:
# Priors for the von Bertalanffy-like growth model: L = L_max * (1 - exp(-k * age))
# L_max: Asymptotic maximum length
# k: Growth rate coefficient
# Based on summary stats:
# Max length is ~2.74, so L_max should be slightly higher.
# We use a HalfNormal with a sigma large enough to cover plausible values.
L_max = pm.HalfNormal('L_max', sigma=2.0)
# k should be positive. A HalfNormal with sigma=1 is a reasonable weakly informative prior.
k = pm.HalfNormal('k', sigma=1.0)
# Deterministic growth curve
mu = L_max * (1 - pm.math.exp(-k * age))
# Likelihood
# sigma is the standard deviation of the observation error
sigma = pm.HalfNormal('sigma', sigma=0.5)
likelihood = pm.Normal('likelihood', mu=mu, sigma=sigma, observed=length)
return dugong_model
"
dugongs,07-loop-proposal-1,Loop proposal 1 (round 1),scored,,-4.9166,"import pymc as pm
import numpy as np
def model(data):
age = data['age']
length = data['length']
n_obs = len(age)
with pm.Model() as model:
# Create data container for age
age_data = pm.Data('age', age, dims=""obs_id"")
# Priors for von Bertalanffy growth parameters
L_inf = pm.HalfNormal('L_inf', sigma=3.0)
k = pm.HalfNormal('k', sigma=1.0)
t0 = pm.Normal('t0', mu=0.0, sigma=1.0)
# Expected length at each age
mu = L_inf * (1 - pm.math.exp(-k * (age_data - t0)))
# Likelihood
sigma = pm.HalfNormal('sigma', sigma=0.5)
y_obs = pm.Normal('y_obs', mu=mu, sigma=sigma, observed=length, dims=""obs_id"")
return model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
dugongs,08-loop-proposal-2,Loop proposal 2 (round 1),scored,,-4.6634,"import numpy as np
import pymc as pm
def model(data):
""""""
von Bertalanffy growth model for dugong length as a function of age.
""""""
age = data['age']
length = data['length']
with pm.Model() as dugong_model:
# Data containers
age_data = pm.Data(""age"", age, dims=""obs_id"")
# Priors for von Bertalanffy parameters
# L∞: asymptotic length, should be > max observed length
L_inf = pm.HalfNormal(""L_inf"", sigma=3.0)
# k: growth rate, positive
k = pm.HalfNormal(""k"", sigma=2.0)
# t0: theoretical age at zero length, can be negative
t0 = pm.Normal(""t0"", mu=0.0, sigma=1.0)
# Expected length
mu = L_inf * (1 - pm.math.exp(-k * (age_data - t0)))
# Observation model
sigma = pm.HalfNormal(""sigma"", sigma=0.5)
y_obs = pm.Normal(""y_obs"", mu=mu, sigma=sigma, observed=length, dims=""obs_id"")
return dugong_model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
dugongs,09-loop-proposal-3,Loop proposal 3 (round 2),scored,,-7.4306,"import pymc as pm
import numpy as np
def model(data):
""""""
Bayesian von Bertalanffy growth model with Log-Normal likelihood.
This model addresses the critique that a simple Normal likelihood with constant
variance may not capture the heteroscedasticity and skewness in dugong length data.
By using a Log-Normal likelihood, we assume the errors are multiplicative,
which is often more appropriate for biological growth data.
""""""
age = data['age']
length = data['length']
with pm.Model() as dugong_model:
# Data container for age
age_data = pm.Data('age', age, dims=""obs_id"")
# Priors for von Bertalanffy growth parameters
# L_inf: Asymptotic length. HalfNormal with sigma=3.0 allows for lengths up to ~6m (3 sigma),
# which is biologically plausible for dugongs.
L_inf = pm.HalfNormal('L_inf', sigma=3.0)
# k: Growth rate coefficient. HalfNormal with sigma=2.0 is weakly informative.
k = pm.HalfNormal('k', sigma=2.0)
# t0: Theoretical age at zero length. Normal centered at 0 with sigma=1.0.
# This allows for negative t0 (early growth) or positive t0 (delayed start).
t0 = pm.Normal('t0', mu=0.0, sigma=1.0)
# Expected length according to von Bertalanffy growth function
vb_mean = L_inf * (1 - pm.math.exp(-k * (age_data - t0)))
# Ensure vb_mean is positive to take log.
# In practice, with reasonable priors and data, this should be positive.
# We add a small epsilon for numerical stability if needed, but
# the model should constrain it naturally.
mu_log = pm.math.log(vb_mean)
# Observation model: Log-Normal likelihood
# sigma is the standard deviation on the log scale.
sigma = pm.HalfNormal('sigma', sigma=0.5)
# Observed likelihood
y_obs = pm.LogNormal('y_obs', mu=mu_log, sigma=sigma, observed=length, dims=""obs_id"")
return dugong_model
def gen_model(observed_data):
# Convert pandas DataFrame to dictionary of numpy arrays
data_dict = {column: observed_data[column].to_numpy() for column in observed_data.columns}
built_model = model(data_dict)
with built_model:
# Sample from posterior
trace = pm.sample(
200,
tune=200,
target_accept=0.90,
chains=1,
cores=1,
random_seed=42,
idata_kwargs={""log_likelihood"": True}
)
# Generate posterior predictive samples
posterior_predictive = pm.sample_posterior_predictive(
trace,
random_seed=314,
return_inferencedata=False
)
return built_model, posterior_predictive, trace"
dugongs,10-loop-proposal-4,Loop proposal 4 (round 2),scored,,-4.5121,"import pymc as pm
import numpy as np
def model(data):
age = data['age']
length = data['length']
with pm.Model() as dugong_model:
# Data containers
age_data = pm.Data(""age"", age, dims=""obs_id"")
# Priors for von Bertalanffy parameters
L_inf = pm.HalfNormal(""L_inf"", sigma=3.0)
k = pm.HalfNormal(""k"", sigma=2.0)
t0 = pm.Normal(""t0"", mu=0.0, sigma=1.0)
# Expected length
mu = L_inf * (1 - pm.math.exp(-k * (age_data - t0)))
# Heteroscedastic noise model: sigma scales with the mean length
# alpha is the log-scale intercept, beta is the scaling factor
alpha = pm.Normal(""alpha"", mu=0.0, sigma=1.0)
beta = pm.Normal(""beta"", mu=0.0, sigma=0.5)
sigma = pm.math.exp(alpha + beta * pm.math.log(mu))
# Likelihood
y_obs = pm.Normal(""y_obs"", mu=mu, sigma=sigma, observed=length, dims=""obs_id"")
return dugong_model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
disease-spread,01-reference,Reference,scored,,-45.6085,"import pymc as pm
def model(data):
""""""Infected count against time: the exponential-approach curve and prior of BoxingGym's
disease-spread environment, with a Binomial likelihood over a population of 50.
""""""
with pm.Model() as result:
t = pm.Data(""t"", data[""Time""])
y = pm.Data(""y"", data[""Infected_Count""])
theta = pm.TruncatedNormal(""theta"", mu=1, sigma=1, lower=0, upper=2)
pm.Binomial(""Infected_Count"", n=50, p=1-pm.math.exp(-theta*t), observed=y)
return result
"
disease-spread,02-floor-model,Floor model,scored,,-262.1291,"import pymc as pm
def model(data):
""""""Floor model: ignores time and fits one infection probability.""""""
with pm.Model() as result:
y = pm.Data(""y"", data[""Infected_Count""])
p = pm.Beta(""p"", alpha=1, beta=1)
pm.Binomial(""Infected_Count"", n=50, p=p, observed=y)
return result
"
disease-spread,03-single-attempt-1,Single attempt 1,scored,,-59.9733,"import pymc as pm
import numpy as np
def model(data):
""""""
Construct a PyMC model for the death_process task.
Parameters:
data (dict): A dictionary containing 'Time' and 'Infected_Count' arrays.
Returns:
pm.Model: The PyMC model.
""""""
times = np.array(data['Time'])
infected_counts = np.array(data['Infected_Count'])
N = 50 # Total population size
with pm.Model() as pmodel:
# Define parameters for the model
# We assume a linear relationship between time and the logit of the probability of infection
# p(t) = sigmoid(alpha + beta * t)
# Then the number of infected follows a Binomial(N, p(t))
# Priors for the linear coefficients
alpha = pm.Normal('alpha', mu=0, sigma=10)
beta = pm.Normal('beta', mu=0, sigma=10)
# Calculate the probability of infection at each time point
logit_p = alpha + beta * times
p = pm.math.sigmoid(logit_p)
# Observed likelihood
infected_observed = pm.Binomial('infected_observed', n=N, p=p, observed=infected_counts)
return pmodel
"
disease-spread,04-single-attempt-2,Single attempt 2,scored,,-59.8279,"import pymc as pm
import numpy as np
def model(data):
""""""
Defines a PyMC model for predicting infected counts in a population of 50.
Args:
data (dict): A dictionary containing 'Time' and 'Infected_Count' arrays.
Returns:
pm.Model: The defined PyMC model.
""""""
time = np.array(data['Time'])
infected_counts = np.array(data['Infected_Count'])
N = 50 # Total population size
with pm.Model() as m:
# Priors for the logistic regression coefficients
# alpha: intercept, beta: slope
alpha = pm.Normal('alpha', mu=0, sigma=5)
beta = pm.Normal('beta', mu=0, sigma=5)
# Compute the probability of infection at each time point
# Using the logistic function: p = 1 / (1 + exp(-(alpha + beta * t)))
logit_p = alpha + beta * time
p = pm.math.invlogit(logit_p)
# Observed likelihood: Binomial distribution
# The number of infected individuals is binomially distributed with N trials and probability p
infected_observed = pm.Binomial(
'infected_observed',
n=N,
p=p,
observed=infected_counts
)
return m
"
disease-spread,05-single-attempt-3,Single attempt 3,scored,,-60.0128,"import pymc as pm
import numpy as np
def model(data):
time = np.array(data['Time'])
infected_counts = np.array(data['Infected_Count'])
with pm.Model() as model:
# Priors for the logistic curve parameters
# beta: growth rate, should be positive
beta = pm.Gamma('beta', alpha=2, beta=1)
# t_mid: midpoint of the logistic curve, centered around 1.0 based on data
t_mid = pm.Normal('t_mid', mu=1.0, sigma=0.5)
# Total population is fixed at 50
K = 50
# Deterministic logistic function
# I(t) = K / (1 + exp(-beta * (t - t_mid)))
expected_infected = pm.Deterministic(
'expected_infected',
K / (1 + pm.math.exp(-beta * (time - t_mid)))
)
# Likelihood
# Using Gaussian likelihood for simplicity, as counts are relatively high
# and the Gaussian approximation to Binomial is reasonable.
# Alternatively, Binomial likelihood: Binomial(n=50, p=expected_infected/50)
# Let's use Binomial for better statistical grounding.
p_infected = expected_infected / K
# Clip p to [0, 1] to avoid numerical issues
p_infected = pm.math.clip(p_infected, 0, 1)
likelihood = pm.Binomial(
'likelihood',
n=50,
p=p_infected,
observed=infected_counts
)
return model
"
disease-spread,06-single-attempt-4,Single attempt 4,failed,failed at model build,,"import numpy as np
import pymc as pm
import theano.tensor as tt
def model(data):
""""""
Build a PyMC model for the death_process / infection spread problem.
The data consists of Time and Infected_Count observations from a population of 50.
We need to model the number of infected individuals as a function of time.
A common model for disease spread is the logistic growth model (SIR-like), where:
I(t) = N / (1 + ((N - I0) / I0) * exp(-r * t))
However, since we're observing noisy counts at specific times, we can use a simpler
parametric model or a stochastic process model.
Given the summary statistics:
- Time ranges from ~0 to ~2
- Infected_Count ranges from 1 to 47
- Mean infected count is ~30
Let's use a logistic growth model with parameters:
- r: growth rate
- I0: initial infected count
The logistic function: I(t) = N / (1 + ((N - I0) / I0) * exp(-r * t))
We'll place priors on r and I0, and use a likelihood that accounts for the discrete
nature of the counts (e.g., Normal or Poisson approximation, or just Normal for simplicity
since counts are relatively large).
""""""
N = 50 # Total population
times = data['Time']
infected_counts = data['Infected_Count']
with pm.Model() as pm_model:
# Priors on parameters
# Growth rate r: positive, reasonable range
r = pm.HalfNormal('r', sigma=5)
# Initial infected count I0: between 1 and N
# Using a Beta distribution scaled to [1, N]
# Or directly use a discrete uniform or normal truncated
I0 = pm.Beta('I0', alpha=2, beta=5, transform=pm.distributions.transforms.ordered)
# Scale I0 to be between 1 and N-1
I0_scaled = I0 * (N - 2) + 1
# Deterministic: predicted infected count at each time point
# Logistic growth: I(t) = N / (1 + ((N - I0) / I0) * exp(-r * t))
# Handle edge cases where I0 is very small
# Using a safer formulation
# Let's use a different parameterization to avoid numerical issues
# I(t) = N * sigmoid(r * (t - t0))
# where t0 is the inflection point
# sigmoid(x) = 1 / (1 + exp(-x))
# Alternative: use r and K (carrying capacity, which is N)
# I(t) = N / (1 + exp(-r * (t - t_mid)))
# where t_mid is the time at which I(t) = N/2
t_mid = pm.Normal('t_mid', mu=1.0, sigma=0.5)
# Predicted infected count using logistic function
I_pred = N / (1 + tt.exp(-r * (times - t_mid)))
# Likelihood: observed counts are approximately normal around the predicted values
# with some noise. Since counts are integers, we could use a Poisson or Negative Binomial,
# but for simplicity and given the moderate counts, a Normal likelihood with a small
# standard deviation works well.
sigma = pm.HalfNormal('sigma', sigma=5)
# Observed likelihood
infected_obs = pm.Normal('infected_obs', mu=I_pred, sigma=sigma, observed=infected_counts)
return pm_model
"
disease-spread,07-loop-proposal-1,Loop proposal 1 (round 1),scored,,-59.9324,"import numpy as np
import pymc as pm
def model(data):
""""""
Logistic growth model for disease spread.
Assumptions:
- Disease spread follows logistic growth
- Total population is 50 (carrying capacity)
- Observed counts follow a Binomial distribution
- Priors are weakly informative to allow flexibility
""""""
# Extract data
time = data['Time']
infected = data['Infected_Count']
N = 50 # Total population
# Create PyMC model
with pm.Model() as model:
# Define feature container for time
time_data = pm.Data('Time', time, dims='obs_id')
# Priors for logistic growth parameters
# r: growth rate (positive)
# t0: inflection point (centered around 1, since that's where we see ~25 infected)
r = pm.HalfNormal('r', sigma=5)
t0 = pm.Normal('t0', mu=1.0, sigma=0.5)
# Logistic function: I(t) = N / (1 + exp(-r*(t - t0)))
# Compute the expected number of infected
expected_infected = N / (1 + pm.math.exp(-r * (time_data - t0)))
# Convert to probability for Binomial distribution
p = expected_infected / N
# Clip to avoid numerical issues
p = pm.math.minimum(pm.math.maximum(p, 1e-10), 1 - 1e-10)
# Observed likelihood - Binomial
y_obs = pm.Binomial('y_obs', n=N, p=p, observed=infected, dims='obs_id')
return model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
disease-spread,08-loop-proposal-2,Loop proposal 2 (round 1),failed,failed at model build,,"import numpy as np
import pymc as pm
def model(data):
time = data['Time']
infected = data['Infected_Count']
N = 50 # total population
with pm.Model() as model:
# Feature container for time
time_data = pm.Data('Time', time, dims='obs_id')
# Logistic growth parameters
r = pm.HalfNormal('r', sigma=5)
t0 = pm.Normal('t0', mu=1.0, sigma=0.5)
# Deterministic logistic curve
mu_infected = pm.Deterministic(
'mu_infected',
N / (1 + pm.math.exp(-r * (time_data - t0))),
dims='obs_id'
)
# Overdispersion parameter
sigma = pm.HalfNormal('sigma', sigma=5)
# Negative Binomial likelihood
y_obs = pm.NegativeBinomial(
'y_obs',
mu=mu_infected,
sigma=sigma,
observed=infected,
dims='obs_id'
)
return model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
disease-spread,09-loop-proposal-3,Loop proposal 3 (round 2),scored,,-60.5719,"import numpy as np
import pymc as pm
import pandas as pd
def model(data):
""""""
Logistic growth model for disease spread with Negative Binomial likelihood.
Assumptions:
- Disease spread follows logistic growth dynamics.
- Total population is fixed at 50.
- Observed counts are subject to overdispersion relative to the logistic mean.
- Negative Binomial likelihood is used to model the count data, allowing for
extra variance beyond the Binomial constraint.
""""""
# Extract data
time = data['Time']
infected = data['Infected_Count']
N = 50 # Total population
# Create PyMC model
with pm.Model() as model:
# Define feature container for time
time_data = pm.Data('Time', time, dims='obs_id')
# Priors for logistic growth parameters
# r: growth rate (positive). HalfNormal with sigma=5 allows for rapid growth.
r = pm.HalfNormal('r', sigma=5)
# t0: inflection point. Centered at 1.0 with reasonable uncertainty.
t0 = pm.Normal('t0', mu=1.0, sigma=0.5)
# Logistic function: I(t) = N / (1 + exp(-r*(t - t0)))
# Compute the expected number of infected
expected_infected = N / (1 + pm.math.exp(-r * (time_data - t0)))
# Clip expected infected to ensure it stays within valid range for probability calculation
# though NegativeBinomial takes mu directly, we might want to ensure positivity.
# The logistic function naturally stays between 0 and N.
# Overdispersion parameter for Negative Binomial
# alpha is the dispersion parameter. Smaller alpha means more dispersion.
# Using a HalfNormal prior for alpha.
alpha = pm.HalfNormal('alpha', sigma=5)
# Observed likelihood: Negative Binomial
# pm.NegativeBinomial('y_obs', mu=expected_infected, alpha=alpha, observed=infected, dims='obs_id')
# Note: In some PyMC versions, the parameterization might differ.
# Standard parameterization is mu (mean) and alpha (dispersion).
# Variance = mu + mu^2 / alpha
y_obs = pm.NegativeBinomial('y_obs', mu=expected_infected, alpha=alpha, observed=infected, dims='obs_id')
return model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"
disease-spread,10-loop-proposal-4,Loop proposal 4 (round 2),scored,,-60.7518,"import numpy as np
import pymc as pm
import pandas as pd
def model(data):
""""""
Logistic growth model for disease spread with Negative Binomial likelihood.
Assumptions:
- Disease spread follows a logistic growth mean trend.
- Total population is 50 (carrying capacity).
- Observed counts exhibit overdispersion relative to Binomial, modeled via Negative Binomial.
- Priors are weakly informative.
""""""
# Extract data
time = data['Time']
infected = data['Infected_Count']
N = 50 # Total population
# Create PyMC model
with pm.Model() as model:
# Define feature container for time
time_data = pm.Data('Time', time, dims='obs_id')
# Priors for logistic growth parameters
# r: growth rate (positive, steep rise observed)
r = pm.HalfNormal('r', sigma=10)
# t0: inflection point (centered around 1.0, sigma=1.0 to be flexible)
t0 = pm.Normal('t0', mu=1.0, sigma=1.0)
# Logistic function: I(t) = N / (1 + exp(-r*(t - t0)))
# Compute the expected number of infected
expected_infected = N / (1 + pm.math.exp(-r * (time_data - t0)))
# Clip expected infected to be within [1, N-1] to avoid log issues or zero/negative means
# We want mean > 0 for NegativeBinomial.
# Also, NegativeBinomial parametrization in PyMC uses mu and alpha (or n, p).
# Using mu and alpha parametrization: mu is mean, alpha is dispersion.
# Var = mu + mu^2 / alpha
# Clip mean to be strictly positive and <= N
mu = pm.math.minimum(pm.math.maximum(expected_infected, 0.5), N - 0.5)
# Dispersion parameter for Negative Binomial
# High alpha means low dispersion (closer to Poisson/Binomial)
# Low alpha means high dispersion
alpha = pm.HalfNormal('alpha', sigma=5)
# Observed likelihood - Negative Binomial
# mu is the mean, alpha is the dispersion parameter
y_obs = pm.NegativeBinomial('y_obs', mu=mu, alpha=alpha, observed=infected, dims='obs_id')
return model
def gen_model(observed_data):
built_model = model({column: observed_data[column].to_numpy() for column in observed_data.columns})
with built_model:
trace = pm.sample(200, tune=200, target_accept=0.90, chains=1, cores=1, random_seed=42, idata_kwargs={""log_likelihood"": True})
posterior_predictive = pm.sample_posterior_predictive(trace, random_seed=314, return_inferencedata=False)
return built_model, posterior_predictive, trace"