Bayesian_Zahra.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. # Constrained Bayesian fit (Gamma for NC, Beta-Prime for AE) — no regularization, no r-prior
  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_path = "../data/"
  8. suv = io.loadmat(data_path + "suv_percentilesSLOthenUWM.mat")['lung_SUVperc_COMBINED'][0:58, :, :]
  9. flags = io.loadmat(data_path + "flags_combined.mat")['flags'][0:58, 3] # 0=NC, 1=AE
  10. # Feature X = max SUV_94 per subject; label y = flags
  11. X = np.nanmax(suv[:, :, 94], axis=1).astype(float).ravel()
  12. y = np.asarray(flags, int).ravel()
  13. # Guard for logs
  14. X = np.clip(X, 1e-12, None)
  15. p_emp = float(y.mean())
  16. # Small helpers
  17. def logistic(z):
  18. z = np.clip(z, -60, 60)
  19. return 1.0 / (1.0 + np.exp(-z))
  20. def sigmoid(t):
  21. return 1.0 / (1.0 + np.exp(-t))
  22. def softplus(t):
  23. t = np.asarray(t, float)
  24. return np.log1p(np.exp(-np.abs(t))) + np.maximum(t, 0.0)
  25. # dE(x) pieces for log-odds
  26. def dE_ess(x, a, b, s, k, th):
  27. x = np.asarray(x, float)
  28. return (a - k) * np.log(x) - (a + b) * np.log1p(x / s) + x / th
  29. def dE_const(a, b, s, k, th):
  30. return -(a * np.log(s)) - betaln(a, b) + k * np.log(th) + gammaln(k)
  31. def dE_full(x, a, b, s, k, th):
  32. return dE_ess(x, a, b, s, k, th) + dE_const(a, b, s, k, th)
  33. # Monotonicity cap for theta
  34. def theta_max(a, b, k, s, eps=1e-12):
  35. A = a - k
  36. if A <= 0:
  37. return np.inf
  38. r = np.sqrt(a + b) - np.sqrt(max(A, eps))
  39. if r <= 1e-12:
  40. return np.inf
  41. return s / (r * r)
  42. # φ = [p_raw, b_raw, s_raw, k_raw, d_raw, u_raw] (unconstrained)
  43. def unpack_phi_mono(phi):
  44. p_raw, b_raw, s_raw, k_raw, d_raw, u_raw = phi
  45. p = sigmoid(p_raw) # (0,1)
  46. b = softplus(b_raw) + 1e-6 # >0
  47. s = softplus(s_raw) + 1e-6 # >0
  48. k = softplus(k_raw) + 1e-6 # >0
  49. delta = softplus(d_raw) + 1e-6 # >0
  50. a = k + delta # enforce a > k
  51. th_cap = theta_max(a, b, k, s) # theta cap from monotonicity
  52. th = th_cap * sigmoid(u_raw) # 0 < theta <= th_cap
  53. return p, a, b, s, k, th
  54. # Prior on r = theta / theta_max (softly avoid boundaries)
  55. thcap = theta_max(a, b, k, s)
  56. if np.isfinite(thcap) and thcap > 0:
  57. r = np.clip(th / thcap, 1e-9, 1 - 1e-9)
  58. # Negative log Beta prior: -[(α-1)log r + (β-1)log(1-r)] (const dropped)
  59. npr_r = -((0.5) * np.log(r) + (0.5) * np.log(1.0 - r))
  60. else:
  61. npr_r = 0.0
  62. # Prior on p
  63. TAU = 25.0 # shrink toward empirical AE rate
  64. alpha = max(TAU * p_emp, 1e-6)
  65. beta = max(TAU * (1.0 - p_emp), 1e-6)
  66. # Objective: negative log-posterior (likelihood + Beta prior on p)
  67. def neg_post_phi_mono(phi, X, y):
  68. p, a, b, s, k, th = unpack_phi_mono(phi)
  69. eps = 1e-12
  70. L = (np.log(p) - np.log(1 - p)) + dE_full(X, a, b, s, k, th)
  71. px = logistic(L)
  72. nll = -np.sum(y * np.log(px + eps) + (1 - y) * np.log(1 - px + eps))
  73. # Beta(alpha, beta) prior on p → negative log-prior
  74. npr_p = -((alpha - 1) * np.log(p + eps) + (beta - 1) * np.log(1 - p + eps))
  75. return nll + npr_r
  76. # Initialization (stable, simple)
  77. def init_phi(X, y):
  78. # Gamma(k, theta) MoM for NC group (only need k0 as a safe size proxy)
  79. X0 = X[y == 0]
  80. m0 = X0.mean() if X0.size else X.mean()
  81. v0 = X0.var() if X0.size else X.var()
  82. k0 = 2.0 if v0 <= 0 else max((m0**2)/(v0 + 1e-9), 1.5)
  83. # AE median to seed s0
  84. X1 = X[y == 1]
  85. m1 = np.median(X1) if X1.size else np.median(X)
  86. p0 = np.clip(float(y.mean()), 1e-3, 1 - 1e-3)
  87. b0, s0 = 1.5, max(m1, 0.5)
  88. return np.array([
  89. np.log(p0 / (1 - p0)), # p_raw
  90. np.log(np.expm1(b0) + 1e-9), # b_raw
  91. np.log(np.expm1(s0) + 1e-9), # s_raw
  92. np.log(np.expm1(k0) + 1e-9), # k_raw
  93. np.log(np.expm1(1.0) + 1e-9), # d_raw (delta)
  94. -0.2 # u_raw (keeps theta a bit below cap initially)
  95. ], float)
  96. # Fit wrapper (one retry)
  97. def fit_bayes_mono(X, y, phi_start=None, rng=None):
  98. if rng is None:
  99. rng = np.random.default_rng(0)
  100. if phi_start is None:
  101. phi_start = init_phi(X, y)
  102. obj = lambda phi: neg_post_phi_mono(phi, X, y)
  103. res = optimize.minimize(
  104. obj, phi_start, method="L-BFGS-B",
  105. options={"maxiter": 6000, "ftol": 1e-9}
  106. )
  107. if not (res.success and np.isfinite(res.fun)):
  108. phi_try = phi_start + rng.normal(0, 0.2, size=phi_start.shape)
  109. res = optimize.minimize(
  110. obj, phi_try, method="L-BFGS-B",
  111. options={"maxiter": 6000, "ftol": 1e-9}
  112. )
  113. return unpack_phi_mono(res.x), res
  114. # prediction
  115. def P_with(theta, x):
  116. p, a, b, s, k, th = theta
  117. L = (np.log(p) - np.log(1 - p)) + dE_full(x, a, b, s, k, th)
  118. return logistic(L)
  119. # Run fit + plot
  120. theta_hat, res = fit_bayes_mono(X, y)
  121. print("Optimization success:", res.success, " fval:", float(res.fun))
  122. print("theta (p,a,b,s,k,theta):", tuple(float(t) for t in theta_hat))
  123. # x-range (cap right end at 10 for readability)
  124. x_lo = max(1e-6, float(X.min()) * 0.8)
  125. x_hi = min(10.0, float(X.max()) * 1.2)
  126. xg = np.linspace(x_lo, x_hi, 600)
  127. p_curve = P_with(theta_hat, xg)
  128. fig, ax = plt.subplots(figsize=(7.0, 4.6), dpi=140)
  129. ax.plot(xg, p_curve, color="#000000", lw=2.2, label="P(AE|x) (MAP)")
  130. # overlay data with tiny vertical jitter so points don't overlap
  131. rng_plot = np.random.default_rng(999)
  132. jit = (rng_plot.random(len(y)) - 0.5) * 0.06
  133. ax.scatter(X[y==0], (y + jit)[y==0], s=22, alpha=0.55, color="#2ca02c", edgecolors='none', label='NC')
  134. ax.scatter(X[y==1], (y + jit)[y==1], s=26, alpha=0.75, color="#ff7f0e", edgecolors='none', label='AE')
  135. ax.set_ylim(-0.05, 1.05)
  136. ax.set_xlabel('x')
  137. ax.set_ylabel('P(AE | x)')
  138. ax.set_title('Constrained Bayesian fit (no regularization prior on p and r:alpha and beta=1.5')
  139. ax.grid(alpha=0.3)
  140. ax.legend(loc='lower right', frameon=False)
  141. plt.tight_layout()
  142. plt.show()