bayesian.py 14 KB

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