Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions posterior_database/bibliography/references.bib
Original file line number Diff line number Diff line change
Expand Up @@ -361,3 +361,14 @@ @article{pagani2022
publisher={Wiley},
doi={10.1111/sjos.12532}
}

@article{hoffman2014nuts,
author = {Matthew D. Hoffman and Andrew Gelman},
title = {The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo},
journal = {Journal of Machine Learning Research},
year = {2014},
volume = {15},
number = {47},
pages = {1593--1623},
url = {http://jmlr.org/papers/v15/hoffman14a.html}
}
106 changes: 106 additions & 0 deletions posterior_database/data/data-raw/german_credit/german_credit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""
Generate the posteriordb data set `german_credit`.

German credit data with 24 standardized numeric predictors, as used in
Hoffman & Gelman (2014), "The No-U-Turn Sampler", JMLR 15, Section 4.1.2.

Source:
UCI Statlog (German Credit Data), file german.data-numeric
https://archive.ics.uci.edu/dataset/144/statlog+german+credit+data
24 numeric attributes + class column (1 = good, 2 = bad), 1000 rows.

Preprocessing:
* y = 1 for good credit risk, 0 for bad.
* The 24 predictors are standardized to mean 0 and variance 1 using the
population SD (ddof = 0).

Output:
german_credit.json {"N": 1000, "D": 24, "X": [[...], ...], "y": [...]}
german_credit.json.zip zipped copy, as stored in posteriordb

Usage:
python german_credit.py # downloads from UCI
python german_credit.py --input german.data-numeric --outdir out/

Requires only numpy.
"""

import argparse
import hashlib
import json
import os
import urllib.request
import zipfile

import numpy as np

NAME = "german_credit"
UCI_URL = (
"https://archive.ics.uci.edu/ml/machine-learning-databases/"
"statlog/german/german.data-numeric"
)
N_EXPECTED = 1000
D_EXPECTED = 24


def load_raw(path=None):
if path is not None:
with open(path, "r") as f:
text = f.read()
else:
print(f"Downloading {UCI_URL} ...")
with urllib.request.urlopen(UCI_URL) as resp:
text = resp.read().decode("ascii")

rows = [line.split() for line in text.strip().splitlines() if line.strip()]
raw = np.array(rows, dtype=float)
if raw.shape != (N_EXPECTED, D_EXPECTED + 1):
raise ValueError(
f"Expected shape ({N_EXPECTED}, {D_EXPECTED + 1}), got {raw.shape}. "
"Is this the german.data-numeric file (not german.data)?"
)
return raw


def standardize(M):
mu = M.mean(axis=0)
sd = M.std(axis=0, ddof=0)
bad = np.where(sd < 1e-12)[0]
if bad.size:
raise ValueError(f"Zero-variance columns at indices {bad.tolist()}")
return (M - mu) / sd


def main():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--input", help="local path to german.data-numeric (else download)")
p.add_argument("--outdir", default=".", help="output directory")
args = p.parse_args()
os.makedirs(args.outdir, exist_ok=True)

raw = load_raw(args.input)
cls = raw[:, D_EXPECTED].astype(int)
if not set(np.unique(cls)) <= {1, 2}:
raise ValueError(f"Unexpected class labels: {np.unique(cls)}")
y = (cls == 1).astype(int)
X = standardize(raw[:, :D_EXPECTED])

data = {"N": int(X.shape[0]), "D": int(X.shape[1]), "X": X.tolist(), "y": y.tolist()}
payload = json.dumps(data, separators=(",", ":"))

json_path = os.path.join(args.outdir, f"{NAME}.json")
with open(json_path, "w") as f:
f.write(payload)
with zipfile.ZipFile(json_path + ".zip", "w", compression=zipfile.ZIP_DEFLATED) as z:
z.write(json_path, arcname=f"{NAME}.json")

print(f"N = {len(y)}, good (y=1) = {y.sum()}, bad (y=0) = {len(y) - y.sum()}")
print(f"X shape = {X.shape}")
print(f"Wrote {json_path} and {json_path}.zip")
print(f"sha256(json) = {hashlib.sha256(payload.encode()).hexdigest()}")


if __name__ == "__main__":
main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""
Generate the posteriordb data set `german_credit_interactions`.

German credit data with 24 standardized main effects and all 276 pairwise
interactions (300 predictors), as used in Hoffman & Gelman (2014),
"The No-U-Turn Sampler", JMLR 15, Section 4.1.3.

Source:
UCI Statlog (German Credit Data), file german.data-numeric
https://archive.ics.uci.edu/dataset/144/statlog+german+credit+data
24 numeric attributes + class column (1 = good, 2 = bad), 1000 rows.

Preprocessing:
* y = 1 for good credit risk, 0 for bad.
* The 24 main effects are standardized to mean 0 and variance 1 using the
population SD (ddof = 0).
* Interactions are products of pairs of the *standardized* main effects,
all pairs j < k in itertools.combinations order, appended after the
24 main effects. No squared terms. 24 + 276 = 300 columns.
* By default the 276 interaction columns are then re-standardized to
mean 0 and variance 1, so all predictors are on the same scale.
Use --no-restandardize-interactions to keep the raw products.

Column order: x1, ..., x24, x1:x2, x1:x3, ..., x1:x24, x2:x3, ..., x23:x24

Output:
german_credit_interactions.json {"N": 1000, "D": 300, "X": [[...], ...], "y": [...]}
german_credit_interactions.json.zip zipped copy, as stored in posteriordb

Usage:
python german_credit_interactions.py # downloads from UCI
python german_credit_interactions.py --input german.data-numeric --outdir out/

Requires only numpy.
"""

import argparse
import hashlib
import itertools
import json
import os
import urllib.request
import zipfile

import numpy as np

NAME = "german_credit_interactions"
UCI_URL = (
"https://archive.ics.uci.edu/ml/machine-learning-databases/"
"statlog/german/german.data-numeric"
)
N_EXPECTED = 1000
D_EXPECTED = 24


def load_raw(path=None):
if path is not None:
with open(path, "r") as f:
text = f.read()
else:
print(f"Downloading {UCI_URL} ...")
with urllib.request.urlopen(UCI_URL) as resp:
text = resp.read().decode("ascii")

rows = [line.split() for line in text.strip().splitlines() if line.strip()]
raw = np.array(rows, dtype=float)
if raw.shape != (N_EXPECTED, D_EXPECTED + 1):
raise ValueError(
f"Expected shape ({N_EXPECTED}, {D_EXPECTED + 1}), got {raw.shape}. "
"Is this the german.data-numeric file (not german.data)?"
)
return raw


def standardize(M, what):
mu = M.mean(axis=0)
sd = M.std(axis=0, ddof=0)
bad = np.where(sd < 1e-12)[0]
if bad.size:
raise ValueError(f"Zero-variance {what} columns at indices {bad.tolist()}")
return (M - mu) / sd


def main():
p = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
p.add_argument("--input", help="local path to german.data-numeric (else download)")
p.add_argument("--outdir", default=".", help="output directory")
p.add_argument("--no-restandardize-interactions", action="store_true",
help="keep raw products of standardized main effects")
args = p.parse_args()
os.makedirs(args.outdir, exist_ok=True)

raw = load_raw(args.input)
cls = raw[:, D_EXPECTED].astype(int)
if not set(np.unique(cls)) <= {1, 2}:
raise ValueError(f"Unexpected class labels: {np.unique(cls)}")
y = (cls == 1).astype(int)

X_main = standardize(raw[:, :D_EXPECTED], "main-effect")
pairs = list(itertools.combinations(range(D_EXPECTED), 2))
X_int = np.column_stack([X_main[:, j] * X_main[:, k] for j, k in pairs])
if not args.no_restandardize_interactions:
X_int = standardize(X_int, "interaction")
X = np.hstack([X_main, X_int])
assert X.shape == (1000, 300)

data = {"N": int(X.shape[0]), "D": int(X.shape[1]), "X": X.tolist(), "y": y.tolist()}
payload = json.dumps(data, separators=(",", ":"))

json_path = os.path.join(args.outdir, f"{NAME}.json")
with open(json_path, "w") as f:
f.write(payload)
with zipfile.ZipFile(json_path + ".zip", "w", compression=zipfile.ZIP_DEFLATED) as z:
z.write(json_path, arcname=f"{NAME}.json")

print(f"N = {len(y)}, good (y=1) = {y.sum()}, bad (y=0) = {len(y) - y.sum()}")
print(f"X shape = {X.shape}, SD range = [{X.std(0).min():.6f}, {X.std(0).max():.6f}]")
print(f"Wrote {json_path} and {json_path}.zip")
print(f"sha256(json) = {hashlib.sha256(payload.encode()).hexdigest()}")


if __name__ == "__main__":
main()
Binary file not shown.
Binary file not shown.
20 changes: 20 additions & 0 deletions posterior_database/data/info/german_credit.info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "german_credit",
"keywords": [
"german credit",
"logistic regression",
"NUTS paper"
],
"title": "German credit data (24 standardized numeric predictors)",
"description": "UCI Statlog German credit (german.data-numeric), 1000 customers. 24 numeric predictors standardized to mean 0, variance 1 (population SD). y = 1 good credit risk, 0 bad. As used in Hoffman & Gelman (2014), Sec. 4.1.2.",
"urls": [
"https://archive.ics.uci.edu/dataset/144/statlog+german+credit+data",
"https://jmlr.org/papers/v15/hoffman14a.html"
],
"references": [
"hoffman2014nuts"
],
"data_file": "data/data/german_credit.json",
"added_date": "2026-11-06",
"added_by": "Michał Kamiński"
}
20 changes: 20 additions & 0 deletions posterior_database/data/info/german_credit_interactions.info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "german_credit_interactions",
"keywords": [
"german credit",
"logistic regression",
"NUTS paper"
],
"title": "German credit data with pairwise interactions (300 predictors)",
"description": "UCI Statlog German credit (german.data-numeric), 1000 customers. 24 standardized main effects followed by all 276 pairwise products (j < k, itertools.combinations order) of the standardized main effects, re-standardized to mean 0 / variance 1. No squared terms. y = 1 good, 0 bad. As used in Hoffman & Gelman (2014), Sec. 4.1.3.",
"urls": [
"https://archive.ics.uci.edu/dataset/144/statlog+german+credit+data",
"https://jmlr.org/papers/v15/hoffman14a.html"
],
"references": [
"hoffman2014nuts"
],
"data_file": "data/data/german_credit_interactions.json",
"added_date": "2026-11-06",
"added_by": "Michał Kamiński"
}
16 changes: 16 additions & 0 deletions posterior_database/models/info/german_credit_hlr.info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "german_credit_hlr",
"title": "German Credit Hierarchical Logistic Regression (Centered Parameterization)",
"added_by": "Michal Kaminski",
"added_date": "2026-11-09",
"description": "Hierarchical Bayesian logistic regression for the UCI Statlog German credit data, as used in the empirical evaluation of the No-U-Turn Sampler (Hoffman and Gelman, 2014, Section 4.1.3). The predictors are the 24 standardized numeric attributes expanded with all 276 pairwise interactions, giving 300 coefficients. The intercept and coefficients share a normal prior with mean 0 and unknown variance sigma2, which is given an exponential prior with rate 0.01 (mean and standard deviation 100). The posterior has 302 parameters, and the strong dependence between sigma2 and the 301 coefficients makes it considerably harder to sample than the non-hierarchical model. This version uses the centered parameterization. The model is written generatively; note that the log density printed in the paper omits the intercept from the likelihood and uses N/2 instead of 301/2 in the log sigma2 normalizing term.",
"model_implementations": {
"stan": {
"model_code": "models/stan/german_credit_hlr.stan"
},
"pymc": {
"model_code": "models/pymc/german_credit_hlr.py"
}
},
"references": "hoffman2014nuts"
}
16 changes: 16 additions & 0 deletions posterior_database/models/info/german_credit_hlr_nc.info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "german_credit_hlr_nc",
"title": "German Credit Hierarchical Logistic Regression (Non-Centered Parameterization)",
"added_by": "Michal Kaminski",
"added_date": "2026-11-09",
"description": "Hierarchical Bayesian logistic regression for the UCI Statlog German credit data, based on the model used in the empirical evaluation of the No-U-Turn Sampler (Hoffman and Gelman, 2014, Section 4.1.3). The predictors are the 24 standardized numeric attributes expanded with all 276 pairwise interactions, giving 300 coefficients. The intercept and coefficients share a normal prior with mean 0 and unknown variance sigma2, which is given an exponential prior with rate 0.01 (mean and standard deviation 100). This version uses a non-centered parameterization: the intercept and coefficients are expressed as sqrt(sigma2) times standard normal variables (alpha_raw, beta_raw), which reduces the dependence between the variance and the coefficients in the space the sampler explores. The implied posterior over alpha, beta and sigma2 is identical to the centered version.",
"model_implementations": {
"stan": {
"model_code": "models/stan/german_credit_hlr_nc.stan"
},
"pymc": {
"model_code": "models/pymc/german_credit_hlr_nc.py"
}
},
"references": "hoffman2014nuts"
}
16 changes: 16 additions & 0 deletions posterior_database/models/info/german_credit_lr.info.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "german_credit_lr",
"title": "German Credit Bayesian Logistic Regression",
"added_by": "Michal Kaminski",
"added_date": "2026-11-09",
"description": "Bayesian logistic regression for the UCI Statlog German credit data (1000 customers, 24 standardized numeric predictors), as used in the empirical evaluation of the No-U-Turn Sampler (Hoffman and Gelman, 2014, Section 4.1.2). The binary response indicates whether a customer is a good (1) or bad (0) credit risk. The intercept and the 24 regression coefficients are given independent weakly informative normal priors with mean 0 and variance 100 (standard deviation 10). The posterior has 25 parameters and serves as a relatively well-conditioned baseline.",
"model_implementations": {
"stan": {
"model_code": "models/stan/german_credit_lr.stan"
},
"pymc": {
"model_code": "models/pymc/german_credit_lr.py"
}
},
"references": "hoffman2014nuts"
}
19 changes: 19 additions & 0 deletions posterior_database/models/pymc/german_credit_hlr.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import numpy as np
import pymc as pm
import pytensor.tensor as pt


def make_model(data: dict) -> pm.Model:
X = np.asarray(data["X"], dtype=float)
y = np.asarray(data["y"], dtype=int)
N, D = X.shape
assert N == int(data["N"]) and D == int(data["D"])

with pm.Model() as model:
sigma2 = pm.Exponential("sigma2", lam=0.01)
sigma = pt.sqrt(sigma2)
alpha = pm.Normal("alpha", mu=0.0, sigma=sigma)
beta = pm.Normal("beta", mu=0.0, sigma=sigma, shape=D)
logits = alpha + pt.dot(X, beta)
pm.Bernoulli("y_obs", logit_p=logits, observed=y)
return model
24 changes: 24 additions & 0 deletions posterior_database/models/pymc/german_credit_hlr_nc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import numpy as np
import pymc as pm
import pytensor.tensor as pt


def make_model(data: dict) -> pm.Model:
X = np.asarray(data["X"], dtype=float)
y = np.asarray(data["y"], dtype=int)
N, D = X.shape
assert N == int(data["N"]) and D == int(data["D"])

with pm.Model() as model:
sigma2 = pm.Exponential("sigma2", lam=0.01)
sigma = pt.sqrt(sigma2)

alpha_raw = pm.Normal("alpha_raw", 0.0, 1.0)
beta_raw = pm.Normal("beta_raw", 0.0, 1.0, shape=D)

alpha = pm.Deterministic("alpha", sigma * alpha_raw)
beta = pm.Deterministic("beta", sigma * beta_raw)

logits = alpha + pt.dot(X, beta)
pm.Bernoulli("y_obs", logit_p=logits, observed=y)
return model
Loading
Loading