bayesian.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import numpy as np
  2. import scipy
  3. """
  4. Bayesian model describing conditional probability
  5. Prob(X|Y = 1)
  6. = Prob(Y=1)p(X|Y=1)/(Prob(Y=0) p(X|Y=0) + Prob(Y=1) p(X|Y=1))
  7. = 1 /(1 + O p(X|Y=0)/p(X|Y=1))
  8. = 1/(1 + exp( -F))
  9. where F is the decision function
  10. F = log(p(X|Y=1)) - log(p(X|Y=0)) - log(O)
  11. and O are the odds
  12. O = Prob(Y=0)/Prob(Y=1)
  13. """
  14. class BayesianModelRegression:
  15. """
  16. Constructor
  17. Input:
  18. odds: float, ratio Prob(Y=0)/Prob(Y=1)
  19. log_pdfs: function (x, pars, choice = 2)
  20. match choice:
  21. case 0: return log_pdf0
  22. case 1: return log_pdf1
  23. case _: return (log_pdf0, log_pdf1)
  24. bounds: tuple of bounds, (bounds0, bound1)
  25. distr_sample: function (rng, x, pars, n, choice):
  26. generate n sampled os points using pdfs(choice, pars)
  27. """
  28. def __init__(self, odds, log_pdfs, bounds, distr_sample = None):
  29. self.odds = odds
  30. self.log_odds = np.log(odds)
  31. self.log_pdfs = log_pdfs
  32. self.bounds = bounds
  33. self.distr_sample = distr_sample
  34. """
  35. Calculate decision function:
  36. decision = log(p(X|Y=1)) - log(p(X|Y=0)) - log(odds)
  37. Input:
  38. x: float or array of floats
  39. pars: parameters for log_pdfs
  40. Return:
  41. float or array of float
  42. """
  43. def decision(self, x, pars):
  44. # log of pdf for each group
  45. lf0, lf1 = self.log_pdfs(x, pars)
  46. return lf1 - lf0 - self.log_odds
  47. """
  48. Calculate model of the conditional probability Prob(X|Y = 1)
  49. Input:
  50. x: float or array of floats
  51. pars: parameters for log_pdfs
  52. """
  53. def model(self, x, pars):
  54. # decision function
  55. F = self.decision(x, pars)
  56. # calculating model
  57. return 1/(1 + np.exp(-F))
  58. """
  59. Negative Log Likelihood function:
  60. neg. log likelihood = -sum_i log(Prob(X = x_i, Y = y_i))
  61. where
  62. Prob(X, Y = 1) = 1/(1 + exp(-F))
  63. Prob(X, Y = 0) = 1 - Prob(X, Y = 1) = 1/(1 + exp(+F))
  64. with
  65. log Prob(X, Y = y) = -log(1 + exp(-S(y) F))
  66. S(y) = [ +1 : y = 1
  67. [ -1 : y = 0
  68. Input:
  69. x: array of floats
  70. y: array of ints in {0,1}
  71. pars: array of floats, model parameters
  72. Return:
  73. float: negative log likelihood
  74. """
  75. def nllf(self, x, y, pars):
  76. # signs for the groups:
  77. # group 1 has + sign and group 0 has - sign
  78. S = 2.0*y - 1
  79. # decision function
  80. F = self.decision(x, pars)
  81. return np.sum(np.log(1 + np.exp(-S*F)))
  82. """
  83. MLE fitting of a distribution, given by log_pdf, to data x associated
  84. to the group 0 or 1 by maximizing
  85. loglikehood_{single group} = sum_i log_pdf(x | pars)
  86. Input:
  87. x: array of floats
  88. choice: int in {0,1}, selecting the group
  89. method: string in ["local", "diff_evol", "anneal"]
  90. seed: int, seed of the random generator
  91. Return:
  92. {"pars": pars_MLE, "cost": NLLF at pars_MLE}
  93. """
  94. def fit_distr(self, x, choice, method = "local", seed = 1977):
  95. fname = "fit_distr"
  96. cost = lambda pars: -np.sum(self.log_pdfs(x, pars, choice))
  97. bnds = self.bounds[choice]
  98. match method:
  99. case "local":
  100. # random parameters from boundaries
  101. pars0 = np.random.default_rng(seed).uniform(*zip(*bnds))
  102. # use local optimizer
  103. res = scipy.optimize.minimize(cost, pars0, bounds = bnds, method = "L-BFGS-B")
  104. case "diff_evol":
  105. res = scipy.optimize.differential_evolution(cost, bounds = bnds)
  106. case "annel":
  107. res = scipy.optimize.dual_annealing(cost, bounds = bnds)
  108. case _:
  109. assert False, f"{fname}::this method does not exist"
  110. return {"pars": res.x, "success": res.success, "cost": res.fun}
  111. """
  112. MLE fitting of the Bayesian model:
  113. pars_MLE = argmin_pars NLLF(pars| x, y)
  114. Input:
  115. x: array of floats
  116. y: array of ints in {0,1}
  117. method: string in ["local", "diff_evol", "anneal"], optimizer
  118. Return:
  119. {"pars": pars_MLE, "cost": NLLF at pars_MLE}
  120. """
  121. def fit(self, x, y, pars0 = None, method = "local"):
  122. fname = "fit"
  123. # defined nllf as function of parameters, data is already included
  124. cost = lambda pars: self.nllf(x, y, pars)
  125. # joint bounds of two groups
  126. bnds = np.concatenate(self.bounds)
  127. match method:
  128. case "local":
  129. # estimate initial guess of parameters (for local method)
  130. if pars0 is None:
  131. get_pars = lambda choice: self.fit_distr(x[y == choice], choice)["pars"]
  132. pars0 = np.r_[get_pars(0), get_pars(1)]
  133. # optimize using local optimizer
  134. res = scipy.optimize.minimize(cost, pars0, bounds = bnds, method = "L-BFGS-B")
  135. case "diff_evol":
  136. res = scipy.optimize.differential_evolution(cost, bounds = bnds)
  137. case "anneal":
  138. res = scipy.optimize.dual_annealing(cost, bounds = bnds)
  139. case _:
  140. assert False, f"{fname}::this method does not exist"
  141. return {"pars": res.x, "success": res.success, "cost": res.fun}
  142. """
  143. Producing goodness of fit measures:
  144. LLF = log_likelihood function
  145. AIC = Akaike information criterion
  146. BIC = Bayesian information criterion
  147. Input:
  148. x: array of floats
  149. y: array of ints in {0,1}
  150. pars: array of floats, model parameters
  151. thresh: float, default 0.5, threshold value for classification
  152. Return:
  153. {"n": n, "k":k, "dof":n-k,
  154. "LLF": log_likelihood,
  155. "AIC": AIC,
  156. "BIC": BIC,
  157. "A": classification accuracy (threshold values = 0.5 prob)}
  158. """
  159. def goodness_of_fit(self, x, y, pars, thresh = 0.5):
  160. # model probabilities
  161. p = self.model(x, pars)
  162. # log likelihood
  163. llf = -self.nllf(x, y, pars)
  164. # information criteria
  165. k, n = len(pars), len(x)
  166. AIC = 2*k - 2*llf
  167. BIC = k*np.log(n) - 2*llf
  168. # chi2
  169. dof = n - k
  170. r = (y - p)/np.sqrt(p*(1-p))
  171. chi2 = np.sum(r**2)
  172. p_val = scipy.stats.chi2.sf(chi2, dof)
  173. # using model as classifier
  174. matches = y == np.heaviside(p - thresh, 1)
  175. return {"LLF": llf, "AIC": AIC, "BIC": BIC,
  176. "A" : np.count_nonzero (matches)/n,
  177. "chi2": chi2, "p-value(chi2)": p_val, # not very useful
  178. "n": n, "k": k, "dof": dof}
  179. """
  180. Generate m parameters via non-parametric bootstrapping with minimal constraint
  181. bootstrapped sampled = (xb, yb) sampled with replacement from (x,y)
  182. Input:
  183. x : array of n floats
  184. y : array of n int in {0,1}
  185. m: integer, number of samples
  186. seed : int, seed for the random generator
  187. method: string in ["local", "diff_evol", "anneal"], optimizer
  188. Return:
  189. array of m x len(pars) floats
  190. """
  191. def get_nonparam_boots_pars(self, x, y, m, seed = 1, method = "local"):
  192. fname = "get_nonparam_boots_pars"
  193. rng = np.random.default_rng(seed)
  194. # discussing original data
  195. res = self.fit(x, y, method = method)
  196. assert res["success"], f"{fname}::fitting original data failed."
  197. # generate bootstrapped parameters
  198. pars = res["pars"]
  199. lst = [pars]
  200. n = len(x)
  201. while True:
  202. # sampling with replacement with restrictions
  203. idx = rng.choice(n, n)
  204. if np.sum(y[idx]) in [0, n]: continue
  205. res = self.fit(x[idx], y[idx], pars0 = pars, method = method)
  206. if not res["success"]: continue
  207. lst.append(res["pars"])
  208. if len(lst) == m: break
  209. return np.array(lst)
  210. """
  211. Generate m parameters via non-parametric stratified bootstrapping:
  212. bootstrapped sampled = (xb, yb) sampled with replacement from (x,y) for each groups separately
  213. meaning
  214. xb = (sampled with replacement from x0, sampled with replacement from x1)
  215. yb = (0 ... 0, 1 ... 1)
  216. n0 n1
  217. Note samples from each group in yb is constant and same as in y.
  218. Input:
  219. x : array of n floats
  220. y : array of n int in {0,1}
  221. m: integer, number of samples
  222. seed : int, seed for the random generator
  223. method: string in ["local", "diff_evol", "anneal"], optimizer
  224. Return:
  225. array of m x len(pars) floats
  226. """
  227. def get_nonparam_strat_boots_pars(self, x, y, m, seed = 1, method = "local"):
  228. fname = "get_nonparam_strat_boots_pars"
  229. rng = np.random.default_rng(seed)
  230. # discussing original data
  231. res = self.fit(x, y, method = method)
  232. assert res["success"], f"{fname}::fitting original data failed."
  233. # separate data of both groups
  234. xs = [x[y == i] for i in range(2)]
  235. ns = [len(e) for e in xs]
  236. # common vector states
  237. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  238. # generate bootstrapped parameters
  239. pars = res["pars"]
  240. lst = [pars]
  241. while True:
  242. # stratified sampling with replacement
  243. xb = np.concatenate([rng.choice(xs[i], ns[i]) for i in range(2)])
  244. # do fitting
  245. res = self.fit(xb, yb, pars0 = pars, method = method)
  246. if not res["success"]: continue
  247. lst.append(res["pars"])
  248. if len(lst) == m: break
  249. return np.array(lst)
  250. """
  251. Generate m parameters via parametric bootstrapping:
  252. bootstrapped sample = (x, yb) yb ~ B(ymodel)
  253. Input:
  254. x : array of n floats
  255. y : array of n int in {0,1}
  256. m: integer, number of samples
  257. seed : int, seed for the random generator
  258. method:
  259. Return:
  260. array of m x len(pars) floats
  261. """
  262. def get_param_boots_pars(self, x, y, m, seed = 1, method = "local"):
  263. fname = "get_param_boots_pars"
  264. rng = np.random.default_rng(seed)
  265. # discussing original data
  266. res = self.fit(x, y, method = method)
  267. assert res["success"], f"{fname}::fitting original data failed."
  268. # calculate predicted conditional probabilities
  269. pars = res["pars"]
  270. p = self.model(x, pars)
  271. # generate bootstrapped parameters
  272. lst = [pars]
  273. n = len(x)
  274. while True:
  275. # Generate new binary outcomes from Bernoulli(p_i)
  276. y_sim = rng.binomial(n = 1, p = p)
  277. if np.sum(y_sim) in [0, n]: continue
  278. # fit and get new parameter
  279. res = self.fit(x, y_sim, pars0 = pars, method=method)
  280. if not res["success"]: continue
  281. lst.append(res["pars"])
  282. if len(lst) == m: break
  283. return np.array(lst)
  284. """
  285. Generate m parameters via parametric stratified bootstrapping by
  286. sampling x from parametrized distributions associated to individual groups:
  287. bootstrapped sample = (xb, yb)
  288. xb = (sampled from distr for x0, sampled from distr for x1)
  289. yb = (0 ... 0, 1 ... 1)
  290. n0 n1
  291. Input:
  292. x : array of n floats
  293. y : array of n int in {0,1}
  294. m: integer, number of samples
  295. seed : int, seed for the random generator
  296. method:
  297. Return:
  298. array of m x len(pars) floats
  299. """
  300. def get_param_strat_boots_pars(self, x, y, m, seed = 1, method = "local"):
  301. fname = "get_param_strat_boots_pars"
  302. assert self.distr_sample is not None, f"{fname}::distr_sample is not defined"
  303. rng = np.random.default_rng(seed)
  304. # separate data of both groups
  305. xs = [x[y == i] for i in range(2)]
  306. ns = [len(e) for e in xs]
  307. # separate data of both groups
  308. pars_g = np.concatenate([self.fit_distr(e, i)["pars"] for i, e in enumerate(xs)])
  309. # discussing original data
  310. res = self.fit(x, y, method = method)
  311. assert res["success"], f"{fname}::fitting original data failed."
  312. # common vector states
  313. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  314. # generate bootstrapped parameters
  315. pars = res["pars"]
  316. lst = [pars]
  317. while True:
  318. # Generate new sample of points for each group
  319. xb = self.distr_sample(rng, pars_g, ns)
  320. # fit and get new parameter
  321. res = self.fit(xb, yb, pars0 = pars, method = method)
  322. if not res["success"]: continue
  323. lst.append(res["pars"])
  324. if len(lst) == m: break
  325. return np.array(lst)