Bayesian_Zahra.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #BetaPrime vs Gamma, hard-mono fit WITH constant + weak regularization
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from scipy import optimize
  5. from scipy.special import betaln, gammaln
  6. import scipy.io as io
  7. # ---------- Data ----------
  8. data_path = "../data/"
  9. # === Load data ===
  10. data_path = "../data/"
  11. suv = io.loadmat(data_path + "suv_percentilesSLOthenUWM.mat")['lung_SUVperc_COMBINED'][0:58, :, :]
  12. flags = io.loadmat(data_path + "flags_combined.mat")['flags'][0:58, 3]
  13. X = np.nanmax(suv[:, :, 94], axis=1).reshape(-1)
  14. X_NC = X[flags == 0]
  15. X_AE = X[flags == 1]
  16. y = np.array([1]*len(X_AE) + [0]*len(X_NC), int) # 1=AE, 0=NC
  17. X = np.concatenate([X_AE, X_NC], axis=0)
  18. # sanity checks now that X,y actually exist
  19. n = len(y); n1 = int(y.sum()); p_emp = n1 / n
  20. rng = np.random.default_rng(12345)
  21. # ---------- Helpers ----------
  22. def logistic(z):
  23. z = np.clip(z, -60, 60)
  24. return 1.0/(1.0+np.exp(-z))
  25. def sigmoid(t):
  26. return 1.0/(1.0+np.exp(-t))
  27. def softplus(t):
  28. t = np.asarray(t, float)
  29. return np.log1p(np.exp(-np.abs(t))) + np.maximum(t, 0.0)
  30. # --- Eq: logit P(AE|x) = log(p/(1-p)) + dE(x) ---
  31. # where dE(x) = dE_ess(x) + C(params)
  32. def dE_ess(x, a, b, s, k, th):
  33. # Essential (x-dependent) terms:
  34. # (a - k) * log(x) - (a + b) * log(1 + x/s) + x/th
  35. x = np.asarray(x, float)
  36. return (a - k) * np.log(x) - (a + b) * np.log1p(x/s) + x/th
  37. def dE_const(a, b, s, k, th):
  38. # Constant (parameter-only) terms:
  39. # C = -a*log(s) - log B(a,b) + k*log(th) + log Γ(k)
  40. return -(a*np.log(s)) - betaln(a, b) + k*np.log(th) + gammaln(k)
  41. def dE_full(x, a, b, s, k, th):
  42. # Total evidence term: dE(x) = dE_ess(x) + C
  43. return dE_ess(x, a, b, s, k, th) + dE_const(a, b, s, k, th)
  44. # ---------- Global monotonicity cap for theta ----------
  45. def theta_max(a, b, k, s, eps=1e-12):
  46. A = a - k
  47. if A <= 0:
  48. return np.inf
  49. r = np.sqrt(a + b) - np.sqrt(max(A, eps))
  50. if r <= 1e-12:
  51. return np.inf
  52. return s/(r*r)
  53. # phi = [p_raw, b_raw, s_raw, k_raw, d_raw, u_raw]
  54. def unpack_phi_mono(phi):
  55. p_raw, b_raw, s_raw, k_raw, d_raw, u_raw = phi
  56. # Map raw parameters into valid constrained space:
  57. # p = sigmoid(p_raw) ∈ (0,1) → AE prior (class prior)
  58. p = sigmoid(p_raw)
  59. # b = softplus(b_raw) > 0 → Beta–Prime shape parameter
  60. b = softplus(b_raw) + 1e-6
  61. # s = softplus(s_raw) > 0 → Beta–Prime scale parameter
  62. s = softplus(s_raw) + 1e-6
  63. # k = softplus(k_raw) > 0 → Gamma shape parameter
  64. k = softplus(k_raw) + 1e-6
  65. # delta = softplus(d_raw) > 0; a = k + delta > k
  66. delta = softplus(d_raw) + 1e-6
  67. a = k + delta
  68. # θ (theta) is constrained: 0 < θ ≤ θ_max(a,b,k,s)
  69. th_cap = theta_max(a, b, k, s)
  70. th = th_cap * sigmoid(u_raw) # map u_raw ∈ R into (0, th_cap]
  71. return p, a, b, s, k, th
  72. # ---------- Priors ----------
  73. # Beta prior on p centered at empirical rate
  74. TAU = 25.0 # reduce to ~5 if you want it weaker
  75. alpha = max(TAU * float(p_emp), 1e-6)
  76. beta = max(TAU * (1.0 - float(p_emp)), 1e-6)
  77. # Weak log-normal shrinkage on positive parameters
  78. def nlog_lognormal(x, mu, sigma, eps=1e-12):
  79. # -log LogNormal(x | mu, sigma) up to additive const
  80. x = np.maximum(x, eps)
  81. lx = np.log(x)
  82. return 0.5 * ((lx - mu)/sigma)**2 + lx
  83. # ---------- Objective ----------
  84. def neg_post_phi_mono_WITH_CONST_REG(phi, X, y):
  85. p, a, b, s, k, th = unpack_phi_mono(phi)
  86. eps = 1e-12
  87. # Likelihood with constant included
  88. z = (np.log(p) - np.log(1-p)) + dE_full(X, a, b, s, k, th)
  89. px = logistic(z)
  90. nll = -np.sum(y*np.log(px + eps) + (1-y)*np.log(1 - px + eps))
  91. # Prior on p ~ Beta(alpha, beta)
  92. npr_p = -((alpha-1)*np.log(p + eps) + (beta-1)*np.log(1 - p + eps))
  93. # --- Regularization (weak priors) ---
  94. # AE median m1: use AE median if present; otherwise overall median.
  95. if (y == 1).any():
  96. m1 = np.median(X[y == 1])
  97. else:
  98. m1 = np.median(X)
  99. reg = 0.0 # total penalty starts at zero
  100. # 1) Gamma shape k (>0): very weak prior centered at 2 (σ=1.2).
  101. reg += nlog_lognormal(k, mu=np.log(2.0), sigma=1.2)
  102. # 2) Beta-Prime shape b (>0): same weak prior.
  103. reg += nlog_lognormal(b, mu=np.log(2.0), sigma=1.2)
  104. # 3) Beta-Prime scale s (>0): center near AE median (tighter σ=0.5).
  105. reg += nlog_lognormal(s, mu=np.log(max(m1, 1e-6)), sigma=0.5)
  106. # 4) Left-tail gap delta = a - k (>0): center around ~1.5 (σ=0.5)
  107. delta = a - k
  108. reg += nlog_lognormal(delta, mu=np.log(1.5), sigma=0.5)
  109. # Keep theta away from the boundary: Beta(3,3) on r = th/th_cap
  110. thcap = theta_max(a, b, k, s)
  111. if np.isfinite(thcap) and thcap > 0:
  112. r = np.clip(th/thcap, 1e-9, 1-1e-9)
  113. npr_r = -((3-1)*np.log(r) + (3-1)*np.log(1 - r))
  114. else:
  115. npr_r = 0.0
  116. return nll + npr_p + reg + npr_r
  117. # ---------- Initialization ----------
  118. def init_phi(X, y):
  119. # Method-of-moments init for Gamma(k, theta) using NC data (y==0)
  120. # ref: https://en.wikipedia.org/wiki/Gamma_distribution#Estimation_of_parameters
  121. X0 = X[y==0]
  122. m0 = X0.mean() if X0.size else X.mean() # sample mean
  123. v0 = X0.var() if X0.size else X.var() # sample variance
  124. if v0 <= 0:
  125. # If variance is degenerate, pick a safe, sane starting point
  126. k0, th0 = 2.0, max(m0/2, 0.1)
  127. else:
  128. # MoM: k = m^2 / v, theta = v / m, with small eps and lower bounds
  129. k0 = max((m0**2)/(v0 + 1e-9), 1.5)
  130. th0 = max(v0/(m0 + 1e-9), 0.3)
  131. X1 = X[y==1]
  132. m1 = np.median(X1) if X1.size else np.median(X)
  133. # Empirical AE rate as a starting prior for p. Clip away from 0/1 so logit is finite.
  134. # p0 = n_AE / n, but truncated to [1e-3, 1-1e-3] to avoid infinities in log(p/(1-p)).
  135. p0 = np.clip(float(y.mean()), 1e-3, 1 - 1e-3)
  136. # Simple, stable seeds for AE Beta–Prime:
  137. # b0 = 1.5 → mild shape; not too spiky, not too flat.
  138. # s0 = max(m1, 0.5) → anchor scale near the AE median, but don’t go tiny.
  139. b0, s0 = 1.5, max(m1, 0.5)
  140. # Pack raw parameters φ for the optimizer.
  141. # We optimize in an unconstrained space and map with:
  142. # p = sigmoid(p_raw)
  143. # b,s,k = softplus(raw) + 1e-6
  144. # a = k + softplus(delta_raw) + 1e-6
  145. # theta = theta_max * sigmoid(u_raw)
  146. # To “invert” softplus for the initial guess we use log(expm1(v)) which is the exact inverse
  147. # of softplus when you define softplus(t) = log(1 + exp(t)). The +1e-9 is just numerical padding.
  148. raw = np.array([
  149. np.log(p0/(1-p0)), # p_raw
  150. np.log(np.expm1(b0) + 1e-9), # b_raw
  151. np.log(np.expm1(s0) + 1e-9), # s_raw
  152. np.log(np.expm1(k0) + 1e-9), # k_raw
  153. np.log(np.expm1(1.0) + 1e-9), # delta_raw
  154. -0.2 # u_raw (keeps theta a bit below cap initially)
  155. ], float)
  156. return raw
  157. # ---------- Fitting ----------
  158. def fit_hard_mono_WITH_CONST_REG(X, y, phi_start=None, maxtries=6, jitter=0.3, rng=None):
  159. if rng is None:
  160. rng = np.random.default_rng(12345)
  161. if phi_start is None:
  162. phi_start = init_phi(X, y)
  163. phi = phi_start.copy()
  164. last_err = None
  165. for _ in range(maxtries):
  166. res = optimize.minimize(
  167. neg_post_phi_mono_WITH_CONST_REG, phi, args=(X, y),
  168. method="L-BFGS-B",
  169. options=dict(maxiter=12000, ftol=1e-10)
  170. )
  171. if res.success and np.isfinite(res.fun):
  172. return unpack_phi_mono(res.x), res
  173. last_err = res
  174. phi = phi + rng.normal(0, jitter, size=phi.shape)
  175. raise RuntimeError(f"Fit failed. Last status: {getattr(last_err, 'message', 'n/a')}")
  176. # ---------- Convenience ----------
  177. def P_with(theta, x):
  178. p, a, b, s, k, th = theta
  179. L = (np.log(p) - np.log(1-p)) + dE_full(x, a, b, s, k, th)
  180. return logistic(L)
  181. def diag_report(theta, X):
  182. p, a, b, s, k, th = theta
  183. thcap = theta_max(a, b, k, s)
  184. C = dE_const(a, b, s, k, th)
  185. logit_p = np.log(p) - np.log(1 - p)
  186. A = a - k
  187. den = np.sqrt(a + b) - np.sqrt(max(A, 1e-12))
  188. xs = np.inf if den <= 1e-12 else s*np.sqrt(max(A,1e-12))/den
  189. print({
  190. "p": p, "a": a, "b": b, "s": s, "k": k, "theta": th,
  191. "theta_max": thcap, "theta/theta_max": (th/thcap if np.isfinite(thcap) else np.nan),
  192. "logit(p)": logit_p, "C": C, "x* (bottleneck)": xs
  193. })
  194. def plot_s_shape(theta, X, y, rng=None, ax=None, label='P(AE | x)'):
  195. if rng is None:
  196. rng = np.random.default_rng(0)
  197. if ax is None:
  198. fig, ax = plt.subplots(figsize=(7, 4.5))
  199. x_lo = max(1e-6, float(X.min())*0.8)
  200. x_hi = float(X.max())*1.2
  201. xg = np.linspace(x_lo, x_hi, 600)
  202. pg = P_with(theta, xg)
  203. ax.plot(xg, pg, lw=2, label=label)
  204. jit = (rng.random(len(X)) - 0.5) * 0.06
  205. y_jit = y + jit
  206. ax.scatter(X[y==0], y_jit[y==0], s=22, alpha=0.35, label='NC (y=0)', edgecolors='none')
  207. ax.scatter(X[y==1], y_jit[y==1], s=28, alpha=0.60, label='AE (y=1)', edgecolors='none')
  208. ax.set_ylim(-0.05, 1.05)
  209. ax.set_xlim(x_lo, x_hi)
  210. ax.set_xlabel('x')
  211. ax.set_ylabel('P(AE | x)')
  212. ax.set_title('S-shaped P(AE | x) with hard-mono fit (constant included, regularized)')
  213. ax.grid(True, alpha=0.3)
  214. ax.legend(loc='lower right', frameon=False)
  215. return ax
  216. # ---------- Run fit ----------
  217. theta_hat, res = fit_hard_mono_WITH_CONST_REG(X, y, rng=rng)
  218. print("Optimization success:", res.success, "fval:", res.fun)
  219. diag_report(theta_hat, X)
  220. ax = plot_s_shape(theta_hat, X, y, rng=rng)
  221. plt.show()
  222. #CI Estimation
  223. # Delta-method
  224. import numdifftools as nd
  225. # wrap scalar objective for numdifftools
  226. def build_objective(X, y):
  227. def f(phi):
  228. return neg_post_phi_mono_WITH_CONST_REG(np.asarray(phi, float), X, y)
  229. return f
  230. # compute Σ_φ (covariance in phi-space) at MAP using numdifftools.Hessian
  231. phi_hat = res.x.copy() # MAP in raw-phi space
  232. f_obj = build_objective(X, y) # scalar negative log-posterior
  233. H = nd.Hessian(f_obj, method='central')(phi_hat)
  234. Sigma_phi = invert_with_eigenfloor(H, floor=1e-6)
  235. # 95% Wald band via Delta method
  236. z = norm.ppf(0.975) # 1.96 for 95% ppf stands for percent point function — it’s the inverse CDF
  237. def g_px_at_x(x):
  238. """Return g(φ) = P(AE | x, φ), so we can get ∇g(φ̂) via numdifftools.Gradient."""
  239. #Build a scalar function g(φ) = P(AE | x, φ) for a fixed x.
  240. #We return this function so numdifftools.Gradient can compute ∇g(φ̂).
  241. def g(phi):
  242. p, a, b, s, k, th = unpack_phi_mono(np.asarray(phi, float))
  243. L = (np.log(p) - np.log(1 - p)) + dE_full(x, a, b, s, k, th)
  244. return logistic(L)
  245. return g
  246. # x-grid
  247. x_lo = max(1e-6, float(X.min()) * 0.8)
  248. x_hi = min(10.0, float(X.max()) * 1.2)
  249. xg = np.linspace(x_lo, x_hi, 500)
  250. p_hat = np.empty_like(xg) # point estimate at MAP
  251. p_lo = np.empty_like(xg) # lower 95%
  252. p_hi = np.empty_like(xg) # upper 95%
  253. for i, x in enumerate(xg):
  254. gx = g_px_at_x(x)
  255. # point estimate at MAP
  256. ph = gx(phi_hat)
  257. # gradient wrt φ at φ̂ via numdifftools.Gradient
  258. grad = nd.Gradient(gx, method='central')(phi_hat) # shape (d,)
  259. # Delta-method variance on probability scale: var ≈ ∇g^T Σ_φ ∇g
  260. var = float(grad @ Sigma_phi @ grad)
  261. se = np.sqrt(max(var, 0.0))
  262. p_hat[i] = ph
  263. p_lo[i] = np.clip(ph - z * se, 0.0, 1.0)
  264. p_hi[i] = np.clip(ph + z * se, 0.0, 1.0)
  265. # plot
  266. fig, ax = plt.subplots(figsize=(7,4.5 ))
  267. # curve + band (sharp colors)
  268. ax.plot(xg, p_hat, color="#000000", lw=2.2, label='P(AE|x) at MAP')
  269. ax.fill_between(xg, p_lo, p_hi, facecolor="#1f77b4", alpha=0.18, label='95% Wald band (Delta)')
  270. ax.plot(xg, p_lo, color="#1f77b4")
  271. ax.plot(xg, p_hi, color="#1f77b4")
  272. # overlay data with tiny vertical jitter
  273. rng_plot = np.random.default_rng(999)
  274. jit = (rng_plot.random(len(X)) - 0.5) * 0.06
  275. ax.scatter(X[y==0], (y + jit)[y==0], s=22, alpha=0.55, color="#2ca02c", edgecolors='none', label='NC')
  276. ax.scatter(X[y==1], (y + jit)[y==1], s=26, alpha=0.75, color="#ff7f0e", edgecolors='none', label='AE')
  277. ax.set_ylim(-0.05, 1.05)
  278. ax.set_xlabel('x')
  279. ax.set_ylabel('P(AE | x)')
  280. ax.set_title('Delta–method band using numdifftools Hessian/Gradient')
  281. ax.grid(alpha=0.3)
  282. ax.legend(loc='lower right')
  283. plt.show()