protectbayes 0.1.0.dev1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ """Bayesian partially protected Lasso and elastic net regression.
2
+
3
+ Cite Yaman, Atalan & Gill (2024), doi:10.1016/j.electstud.2023.102730,
4
+ and Atalan, Yaman & Gill (2026), doi:10.1080/02664763.2025.2559025.
5
+ """
6
+
7
+ from .core import ProtectedFit, load_fit, protect_elastic_net, protect_lasso
8
+ from .cv import CVResult, cv_protect
9
+
10
+ __version__ = "0.1.0.dev1"
11
+ __all__ = [
12
+ "ProtectedFit",
13
+ "CVResult",
14
+ "protect_lasso",
15
+ "protect_elastic_net",
16
+ "cv_protect",
17
+ "load_fit",
18
+ ]
protectbayes/_glm.py ADDED
@@ -0,0 +1,155 @@
1
+ """Bernoulli-logit and Poisson-log likelihoods and exact slice updates."""
2
+
3
+ import numpy as np
4
+ from scipy.special import expit, gammaln, logsumexp
5
+
6
+
7
+ def validate_family(family):
8
+ if not isinstance(family, str) or family not in ("gaussian", "binomial", "poisson"):
9
+ raise ValueError("family must be gaussian, binomial (Bernoulli), or poisson")
10
+ return family
11
+
12
+
13
+ def validate_response(y, family):
14
+ if family == "binomial" and not np.isin(y, (0, 1)).all():
15
+ raise ValueError("Binomial outcomes must be numeric 0 or 1")
16
+ if family == "poisson" and np.any((y < 0) | (y != np.floor(y))):
17
+ raise ValueError("Poisson outcomes must be nonnegative integers")
18
+
19
+
20
+ def log_likelihood(eta, y, family):
21
+ if family == "binomial":
22
+ return -np.logaddexp(0, (1 - 2 * y) * eta)
23
+ with np.errstate(over="ignore", invalid="ignore"):
24
+ value = y * eta - np.exp(eta) - gammaln(y + 1)
25
+ return np.where(np.isnan(value), -np.inf, value)
26
+
27
+
28
+ def mean_response(eta, family):
29
+ if family == "gaussian":
30
+ return eta
31
+ if family == "binomial":
32
+ return expit(eta)
33
+ with np.errstate(over="ignore"):
34
+ mu = np.exp(eta)
35
+ if not np.isfinite(mu).all():
36
+ raise ValueError("Poisson prediction overflow; check newdata and offsets")
37
+ return mu
38
+
39
+
40
+ def _slice(current, density, height, width, rng):
41
+ # Randomly split finite stepping-out budget (Neal, 2003).
42
+ left = current - rng.random() * width
43
+ right = left + width
44
+ j = rng.integers(64)
45
+ k = 63 - j
46
+ while j > 0 and density(left) > height:
47
+ left -= width
48
+ j -= 1
49
+ while k > 0 and density(right) > height:
50
+ right += width
51
+ k -= 1
52
+ for _ in range(2000):
53
+ z = rng.uniform(left, right)
54
+ if density(z) >= height:
55
+ return z
56
+ if z < current:
57
+ left = z
58
+ else:
59
+ right = z
60
+ raise FloatingPointError("GLM slice sampler failed; rescale data or revise priors")
61
+
62
+
63
+ def chain(d, cfg, method, seed, local_variance):
64
+ rng = np.random.default_rng(seed)
65
+ family = cfg["family"]
66
+ X, y, offset, weight = (d[k] for k in ("X", "response", "offset", "weights"))
67
+ at = int(d["intercept"])
68
+ p = X.shape[1]
69
+ if at:
70
+ X = np.column_stack((np.ones(len(X)), X))
71
+ reg = ~d["protected"]
72
+ lp = cfg["lambda_prior"]
73
+ hierarchical = method == "lasso"
74
+ lasso, ridge = cfg["lasso"], cfg["ridge"]
75
+ wy = weight * y
76
+ total_y = wy.sum()
77
+ b = np.zeros(p + at)
78
+ if at and family == "binomial":
79
+ b[0] = (
80
+ np.log(total_y + 0.5)
81
+ - np.log((weight * (1 - y)).sum() + 0.5)
82
+ - np.average(offset, weights=weight)
83
+ )
84
+ elif at:
85
+ b[0] = np.log(total_y + 0.5) - logsumexp(offset, b=weight)
86
+
87
+ if family == "binomial":
88
+ sign = 1 - 2 * y
89
+
90
+ def likelihood(z):
91
+ return -np.sum(weight * np.logaddexp(0, sign * (z + offset)))
92
+ else:
93
+
94
+ def likelihood(z):
95
+ e = z + offset
96
+ if not np.isfinite(e).all():
97
+ return -np.inf
98
+ with np.errstate(over="ignore", invalid="ignore"):
99
+ value = np.sum(wy * e - weight * np.exp(e))
100
+ return -np.inf if not np.isfinite(value) else value
101
+
102
+ xb = X @ b
103
+ ll = likelihood(xb)
104
+ curvature = 0.25 if family == "binomial" else max(0.1, total_y / weight.sum())
105
+ info = (X**2).T @ weight * curvature
106
+ if not np.isfinite(ll) or not np.isfinite(info).all():
107
+ raise FloatingPointError("Non-finite initial GLM state; check data and offsets")
108
+ lam2 = rng.gamma(lp[0], 1 / lp[1]) if hierarchical and reg.any() else None
109
+ v = np.ones(p)
110
+ draws, warmup, thin = (cfg[k] for k in ("draws", "warmup", "thin"))
111
+ B = np.empty((draws, p + at))
112
+ L = np.empty(draws) if lam2 is not None else None
113
+
114
+ for i in range(warmup + draws * thin):
115
+ if hierarchical:
116
+ sd = np.sqrt(v)
117
+ else:
118
+ sd = np.full(p, cfg["protected_sd"])
119
+ sd[reg] = 1 / np.sqrt(ridge + (1 / v[reg] if lasso > 0 else 0))
120
+ if at:
121
+ sd = np.r_[cfg["intercept_sd"], sd]
122
+ width = np.maximum(2 / np.sqrt(info + 1 / sd**2), np.finfo(float).eps)
123
+ for j in range(len(b)):
124
+ current, column, scale = b[j], X[:, j], sd[j]
125
+
126
+ def target(z, current=current, column=column, scale=scale, xb=xb):
127
+ return likelihood(xb + (z - current) * column) - 0.5 * (z / scale) ** 2
128
+
129
+ height = ll - 0.5 * (current / scale) ** 2 - rng.exponential()
130
+ b[j] = _slice(current, target, height, width[j], rng)
131
+ xb = xb + (b[j] - current) * column
132
+ ll = likelihood(xb)
133
+ xb = X @ b
134
+ ll = likelihood(xb)
135
+ if not np.isfinite(ll):
136
+ raise FloatingPointError("Non-finite GLM sampler state")
137
+ slope = b[at:]
138
+ if hierarchical:
139
+ rates = np.full(p, np.sqrt(2 * cfg["protected_rate"]))
140
+ if lam2 is not None:
141
+ rates[reg] = np.sqrt(lam2)
142
+ v = local_variance(slope, rates, rng)
143
+ if lam2 is not None:
144
+ lam2 = rng.gamma(lp[0] + reg.sum(), 1 / (lp[1] + v[reg].sum() / 2))
145
+ if not np.isfinite(lam2) or lam2 <= 0:
146
+ raise FloatingPointError("Non-finite Lasso rate")
147
+ elif lasso > 0 and reg.any():
148
+ v[reg] = local_variance(slope[reg], lasso, rng)
149
+ if i >= warmup and (i - warmup + 1) % thin == 0:
150
+ k = (i - warmup + 1) // thin - 1
151
+ raw = slope / d["scale"]
152
+ B[k] = np.r_[b[0] - d["center"] @ raw, raw] if at else raw
153
+ if L is not None:
154
+ L[k] = np.sqrt(lam2)
155
+ return B, None, L