bayesian.py 14 KB

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