logit_utils_gen.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  1. """
  2. The file provides a class for logistic regression utilities with polynomial
  3. logit (log odds) function:
  4. p(x|pars) = 1/(1 + exp(-F(x|beta(pars))))
  5. with log odds F of polynomial form:
  6. F(x|beta) = sum_{j=0}^degree beta_j x^j
  7. with decision function (aka logit) F and parameters
  8. beta(pars) = [beta(pars)_j]_{j=0}^degree
  9. where pars are regression parameters and len(pars) = degree + 1.
  10. Coefficients beta(pars) can be constrained to be monotonic
  11. function of x by using monotonic cubic transformation:
  12. beta(pars) = mc.forward_map(pars)
  13. where mc is module mono_cubic2.
  14. NOTES: The model defines the conditional probability
  15. Prob(Y = y|x, pars) = 1/(1 + exp(-s(y) F(x| beta(pars))))
  16. where
  17. s(y) = 2*y - 1
  18. with x in R and y in {0,1}. For degree = 1 this is standard logistic regression
  19. beta(pars) = (pars[0], pars[1]).
  20. and generally without monotonicity condition
  21. beta(pars) = [pars_i]_{i=0}^degree
  22. For degree = 3 and mono = True the coefficients beta(pars) are constrained to be
  23. monotonic by using monotonic cubic transformation.
  24. We have data
  25. {(x_i, y_i) : x_i in R, y_i in {0,1}, i = 0, ..., n-1 }
  26. and the model is fit to data by minimizing negative log-likelihood function:
  27. nlff = -sum_i log(Prob(Y = y_i| x_i, pars)) : neg. log likelihood
  28. with respect to parameters pars. We can have regularization term in cost function
  29. and this case we minimize cost function:
  30. cost(pars) = nllf(pars) + lambda ||pars||^2
  31. Author: Martin Horvat, January 2026
  32. """
  33. import numpy as np
  34. import scipy
  35. import scipy.optimize
  36. import mono_cubic2 as mc
  37. def resize_with_const(v, n, val=0):
  38. """
  39. Resize a 1D vector to a specified length `n`.
  40. If the input vector `v` is longer than `n`, it is truncated.
  41. If it is shorter, it is padded with the constant value `val`.
  42. If it is already of length `n`, it is returned unchanged.
  43. Parameters:
  44. v (array-like): Input 1D vector (list or NumPy array).
  45. n (int): Target length of the output vector.
  46. val (scalar, optional): Value used to pad if `v` is shorter than `n`. Default is 0.
  47. Returns:
  48. np.ndarray: Resized 1D NumPy array of length `n`.
  49. """
  50. v = np.asarray(v)
  51. if len(v) == n: return v
  52. if len(v) > n: return v[:n]
  53. return np.concatenate([v, np.full(n - len(v), val)])
  54. def safe_exp(x, max_exp = 700):
  55. """
  56. A numerically robust version of np.exp that avoids overflow by clipping the input.
  57. Parameters:
  58. x : array_like
  59. Input value or array.
  60. max_exp : float
  61. Maximum allowed exponent value. np.exp(709) ≈ 8.2e307 (close to float64 max).
  62. Returns:
  63. array_like
  64. The exponential of the input with overflow protection.
  65. """
  66. return np.exp(np.clip(x, -max_exp, max_exp))
  67. def safe_expit(x, max_exp = 700): return 1/(1 + safe_exp(-x, max_exp))
  68. """
  69. Fitting data
  70. {(x_i, y_i) : x_i in R, y_i in {0,1}, i = 0, ..., n-1 }
  71. to model function
  72. f(x|pars) = 1/(1 + exp(-F(x|beta(pars))))
  73. with log odds of polynomial form:
  74. log(f(x|pars)/(1 - f(x|pars))) = F(x| beta(pars))
  75. where F is decision function (aka logit)
  76. F(x|beta) = sum_{i=0}^degree beta_i x^i
  77. and coefficients
  78. beta(pars) = [beta_i(pars)]_{i=0}^degrees
  79. Conditional probability
  80. Prob(Y = y_i|x, pars) = 1/(1 + exp(-s(y) F(x|beta(pars)))
  81. with
  82. s(y) = 2*y -1
  83. """
  84. class LogisticPolyRegression:
  85. """
  86. Class constructor.
  87. Input:
  88. degree: int, degree of polynomial
  89. mono: boolean, default False
  90. lambda: None or tuple float, L2 regularization
  91. """
  92. def __init__(self, degree = 1, mono = False, lam = None):
  93. self.degree = degree
  94. self.mono = mono
  95. self.big = 200
  96. self.small = 1e-8
  97. self.lam = lam
  98. if mono:
  99. assert self.degree in [1, 3], f"Degree {self.degree} not supported in mono!"
  100. self.mono3 = self.mono and (self.degree == 3)
  101. """
  102. Mapping regression parameters pars to coefficients beta
  103. beta = beta(pars)
  104. used in decision function:
  105. F(x|beta) = sum_{i=0}^degree beta_i x^i
  106. Input:
  107. pars
  108. Return:
  109. beta
  110. """
  111. def get_beta(self, pars):
  112. beta = mc.forward_map(pars) if self.mono3 else pars
  113. return np.array(beta)
  114. """
  115. Mapping beta to regression parameters used in decision function.
  116. Input:
  117. beta: coefficient beta
  118. Return:
  119. pars
  120. """
  121. def get_pars(self, beta):
  122. pars = mc.backward_map(beta) if self.mono3 else beta
  123. return np.array(pars)
  124. """
  125. Calculate jacobian between beta and regression parameters
  126. J = d(beta)/d(pars)
  127. = [d(beta_i)/d(pars_a)]_{i,a}
  128. and
  129. H = [d^2 beta_i/(d(pars_a) d(pars_b))]_{i,a,b}
  130. Input:
  131. pars
  132. hess: boolean, False
  133. Return:
  134. J if hess = True
  135. (J, H) if hess = False
  136. """
  137. def get_jac_beta(self, pars, hess = False):
  138. n = len(pars)
  139. J = mc.forward_map_jacobian(pars) if self.mono3 else np.eye(n)
  140. if not hess: return J
  141. H = mc.forward_map_hessian(pars) if self.mono3 else np.zeros(shape = (n, n, n))
  142. return (J, H)
  143. """
  144. Model function
  145. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  146. Input:
  147. x: scalar value or a array of values
  148. pars: array of r = degree + 1 floats, model parameters array of floats
  149. Return:
  150. model function values
  151. """
  152. def model(self, x, pars):
  153. beta = self.get_beta(pars) # beta
  154. X = np.column_stack([x**i for i in range(len(beta))])
  155. F = X @ beta # decision function, X beta
  156. return safe_expit(F)
  157. """
  158. Calculate negative log-likelihood function
  159. nllf = -sum_i log(Prob(Y = y_i| x_i, pars)) : neg. log likelihood
  160. grad = [d(nllf)/d(pars_a)]_a : jacobian
  161. where
  162. Prob(Y = y_i| x_i, pars) = 1/(1 + exp(-s_i F(x_i| beta))) beta=beta(pars)
  163. s_i = 2*y_i - 1
  164. Input:
  165. x: array of n floats
  166. y: array of n int in {0,1}
  167. pars: array of r = degree + 1 floats, model parameters array of floats
  168. jac: boolean, default False, if jacobian is needed
  169. Return:
  170. nllf : if jac is false
  171. (nllf, grad) : if jac is true
  172. """
  173. def nllf(self, x, y, pars, jac = False):
  174. beta = self.get_beta(pars)
  175. X = np.column_stack([x**i for i in range(len(beta))])
  176. # signs
  177. s = 2.0*y - 1
  178. # decision function for conditional probability Prob(Y = y| x)
  179. F = s*(X @ beta)
  180. nllf = np.sum(np.log(1 + safe_exp(-F)))
  181. if not jac: return nllf
  182. J = self.get_jac_beta(pars)
  183. grad = -(s*safe_expit(-F)) @ (X @ J)
  184. return (nllf, grad)
  185. """
  186. Penalty function
  187. Input:
  188. pars: array of r = degree + 1 floats, model parameters array of floats
  189. jac: boolean, default False, if jacobian is needed
  190. Return:
  191. val : if jac is false
  192. (val, grad) : if jac is true
  193. """
  194. def penalty(self, pars, jac = False):
  195. val = self.lam[0]*np.sum(np.abs(pars)) + self.lam[1]*np.sum(pars**2)
  196. if jac:
  197. grad = self.lam[0]*np.sign(pars) + 2*self.lam[1]*pars
  198. return (val, grad)
  199. return val
  200. """
  201. Cost function
  202. """
  203. def cost(self, x, y, pars, jac = False):
  204. val = self.nllf(x, y, pars, jac)
  205. if self.lam is not None:
  206. pen = self.penalty(pars, jac)
  207. return (val[0] + pen[0], val[1] + pen[1]) if jac else val + pen
  208. return val
  209. """
  210. Estimate parameters.
  211. Input:
  212. x: array of n floats
  213. y: array of n int in {0,1}
  214. Return:
  215. pars0
  216. """
  217. def get_est_pars(self, x, y):
  218. L = np.log(2*len(x) + 1)
  219. if self.mono3:
  220. z = L*np.polyfit(x, 2.0*y - 1, 1)[::-1]
  221. beta = resize_with_const(z, self.degree + 1, 1e-8)
  222. else:
  223. beta = L*np.polyfit(x, 2.0*y - 1, self.degree)[::-1]
  224. return self.get_pars(beta)
  225. """
  226. Performing logistic regression with log odds of polynomial form:
  227. log(f(x|pars)/(1 - f(x|pars))) = F(x|beta) beta = beta(pars)
  228. and this gives
  229. f(x|pars) = 1/(1 + exp(-F(x|beta)))
  230. where coefficient beta = [beta_i(pars)]_{i=0}^degree, with decision
  231. function (aka logit)
  232. F(x|beta) = sum_{i=0}^degree beta_i x^i
  233. Input:
  234. x: array of n floats
  235. y: array of n int in {0, 1}
  236. Return:
  237. pars
  238. """
  239. def fit(self, x, y, pars0 = None, method = "local"):
  240. bnds = [(-self.big, self.big)]*(self.degree + 1)
  241. if method == "local":
  242. pars0 = self.get_est_pars(x, y)
  243. cf = lambda pars: self.cost(x, y, pars, jac = True)
  244. res = scipy.optimize.minimize(cf, x0 = pars0, method = 'L-BFGS-B',
  245. jac = True, bounds = bnds, tol=1e-12)
  246. elif method == "diff_evol":
  247. cf = lambda pars: self.cost(x, y, pars, jac = False)
  248. res = scipy.optimize.differential_evolution(cf, bounds = bnds,
  249. tol = 1e-8, polish = False)
  250. cf = lambda pars: self.cost(x, y, pars, jac = True)
  251. res = scipy.optimize.minimize(cf, x0 = res.x, method = 'L-BFGS-B',
  252. jac = True, bounds = bnds, tol=1e-12)
  253. elif method == "anneal":
  254. cf = lambda pars: self.cost(x, y, pars, jac = False)
  255. res = scipy.optimize.dual_annealing(cf, bounds = bnds)
  256. else:
  257. assert False, "This method is not supported."
  258. return {"pars": res.x, "cost": res.fun, "success": res.success}
  259. """
  260. Producing goodness of fit measures:
  261. LLF = log_likelihood function
  262. AIC = Akaike information criterion
  263. BIC = Bayesian information criterion
  264. Input:
  265. x: array of n floats
  266. y: array of n int in {0,1}
  267. pars: array of r = degree+1 floats, model parameters
  268. thresh: float, default 0.5, threshold value for classification
  269. Return:
  270. {"n": n,
  271. "k": r,
  272. "dof": n - r,
  273. "LLF": log_likelihood,
  274. "AIC": AIC,
  275. "BIC": BIC,
  276. "A": classification accuracy (threshold values = 0.5 prob)}
  277. Ref:
  278. https://en.wikipedia.org/wiki/Logistic_regression
  279. https://en.wikipedia.org/wiki/Akaike_information_criterion
  280. https://www.medicine.mcgill.ca/epidemiology/joseph/courses/epib-621/logfit.pdf
  281. """
  282. def goodness_of_fit(self, x, y, pars, thresh = 0.5):
  283. # model probabilities
  284. p = self.model(x, pars)
  285. # log likelihood
  286. llf = -self.nllf(x, y, pars)
  287. # information criteria
  288. k, n = len(pars), len(x)
  289. AIC = 2*k - 2*llf
  290. BIC = k*np.log(n) - 2*llf
  291. # chi2
  292. dof = n - k
  293. r = (y - p)/np.sqrt(p*(1-p) + self.small)
  294. chi2 = np.sum(r**2)
  295. p_val = scipy.stats.chi2.sf(chi2, dof)
  296. # using model as classifier
  297. matches = y == np.heaviside(p - thresh, 1)
  298. # accuracy A
  299. A = np.count_nonzero(matches)/n
  300. return {"LLF": llf,
  301. "AIC": AIC,
  302. "BIC": BIC,
  303. "A" : A,
  304. "chi2": chi2,
  305. "p-value(chi2)": p_val, # not very useful
  306. "n": n, "k": k, "dof": dof}
  307. """
  308. Calculation of asymptotic variance-covariance matrix of regression
  309. parameters pars
  310. cov_{asymp}[pars] = H^{-1}
  311. where H is hessian of nllf
  312. H = [d^2(nllf)/(d(pars)_a d(pars)_b ]_{a,b}
  313. for the logistic regression of the polynomial model:
  314. log(f(x)/(1 - f(x))) ~ sum_{i=0}^degree b_i(pars) x^i
  315. Input:
  316. x: array of n floats
  317. pars: array of r = degree+1 floats, model parameters
  318. Return:
  319. array of rxr floats; r = degree + 1
  320. Ref:
  321. * https://stats.stackexchange.com/questions/89484/how-to-compute-the-standard-errors-of-a-logistic-regressions-coefficients
  322. * https://goodboychan.github.io/machine_learning/2020/09/14/02-Regularized-likelihood-methods.html
  323. """
  324. def cov(self, x, y, pars):
  325. # coefficients
  326. beta = self.get_beta(pars)
  327. # design matrix -- add column of 1's at the beginning of your X_train matrix
  328. X = np.column_stack([x**i for i in range(len(beta))])
  329. # Jacobian J = [dbeta_i/dpars_j]_{ij}
  330. J, H = self.get_jac_beta(pars, hess = True)
  331. # signs
  332. s = 2.0*y - 1
  333. # decision function for conditional probability Prob(Y = y| x)
  334. F = s*(X @ beta)
  335. # probabilities p_i = P(Y=y_i | x_i)
  336. p = safe_expit(F)
  337. q = 1 - p
  338. # calculate hessian
  339. L = X @ J
  340. H = (L.T*(q*p))@L - np.tensordot((s*q)@X, H, axes = ([0], [0]))
  341. if self.lam is not None:
  342. Hp = H + 2*self.lam[1]*np.eye(len(pars)) # H' = H + lambda id
  343. iHp = np.linalg.inv(Hp) # inv(H')
  344. return iHp@H@iHp
  345. # covariance matrix C_params = H^-1
  346. return np.linalg.inv(H)
  347. """
  348. Calculating quantiles of the model parameters at given probabilities p
  349. for normal distribution of parameters:
  350. pars ~ N(mean_pars, cov_pars)
  351. Input:
  352. probs: array of m floats, probabilities
  353. mean_pars: array of r = degree+1 floats, mean model parameters
  354. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  355. Return:
  356. array of mxr floats
  357. """
  358. def get_pars_quantiles_normal(self, probs, mean_pars, cov_pars):
  359. # mean and standard variance parameters
  360. locs = mean_pars
  361. scales = np.sqrt(np.diag(cov_pars))
  362. # computing quantiles of parameters
  363. return locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  364. """
  365. Calculating quantiles of the model values
  366. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  367. with
  368. F(x|beta) = sum_{i=0}^degree x^i beta_i
  369. at given probabilities p and values x assuming
  370. normal distribution of parameters:
  371. pars ~ N(mean_pars, cov_pars)
  372. This distribution is asymptotic MLE distribution of parameters.
  373. Input:
  374. x: array of n float
  375. probs: array of m floats, probabilities
  376. mean_pars: array of r = degree+1 floats, mean model parameters
  377. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  378. Return:
  379. array of mxn floats
  380. """
  381. def get_model_quantiles_normal(self, x, probs, mean_pars, cov_pars,
  382. exact = True, seed = 1977, m = 10**5):
  383. mean_beta = self.get_beta(mean_pars)
  384. X = np.column_stack([x**i for i in range(len(mean_beta))])
  385. if exact and self.mono3:
  386. # init random generator
  387. rng = np.random.default_rng(seed)
  388. pars = rng.multivariate_normal(mean_pars, cov_pars, size = m)
  389. # get betas
  390. beta = np.apply_along_axis(self.get_beta, 1, pars)
  391. # quantiles of decision function
  392. Q = np.quantile(X@beta.T, probs, axis = 1)
  393. return np.apply_along_axis(safe_expit, 1, Q)
  394. # J = d(beta)/d(pars)
  395. J = self.get_jac_beta(mean_pars)
  396. # transform data
  397. S = X@J
  398. # mean and standard variance of logit (aka log of odds)
  399. locs = X@mean_beta
  400. scales = np.sqrt(np.diag(S@cov_pars@S.T))
  401. # computing quantiles of logit
  402. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  403. # convert logit to expit
  404. return safe_expit(Q)
  405. """
  406. Calculating quantiles using delta method of the model values
  407. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  408. with
  409. F(x|beta) = sum_{i=0}^degree x^i beta_i
  410. at given probabilities p and values x assuming
  411. normal distribution of parameters :
  412. pars ~ N(mean_pars, cov_pars)
  413. This distribution is asymptotic MLE distribution of parameters.
  414. We approximate exact model with linear expansion
  415. f(x|pars) = p(x|pars_mean) + dp/db(x|pars_mean) (pars - pars_mean)
  416. and the last term is normally distributed.
  417. Input:
  418. x: array of n float
  419. probs: array of m floats, probabilities
  420. mean_pars: array of r = degree+1 floats, mean model parameters
  421. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  422. Return:
  423. array of mxn floats
  424. """
  425. def get_model_quantiles_delta(self, x, probs, mean_pars, cov_pars):
  426. mean_beta = self.get_beta(mean_pars)
  427. X = np.column_stack([x**i for i in range(len(mean_beta))])
  428. F = X@mean_beta
  429. # J = d(beta)/d(pars)
  430. J = self.get_jac_beta(mean_pars)
  431. # S = d(F)/d(pars)
  432. S = X@J
  433. # attributes of normal distribution of model values
  434. locs = safe_expit(F)
  435. scales = np.sqrt(np.diag(S@cov_pars@S.T))/(4*np.cosh(F/2)**2)
  436. # computing quantiles of logit
  437. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  438. return np.clip(Q, a_min = 0, a_max = 1)
  439. """
  440. Generate parameters assuming normal distribution.
  441. Input:
  442. x : array of n floats
  443. y : array of n int in {0,1}
  444. m: integer, number of samples
  445. seed : int, seed for the random generator
  446. Return:
  447. array of mx(degree + 1)
  448. """
  449. def get_normal_pars(self, x, y, m, seed = 1977):
  450. res = self.fit(x, y, method = "diff_evol")
  451. assert res["success"], "Fit did not succeed."
  452. # optimal parameters
  453. pars = res["pars"]
  454. # covariance matrix of parameters
  455. cov = self.cov(x, y, pars)
  456. # init random generator
  457. rng = np.random.default_rng(seed)
  458. return rng.multivariate_normal(pars, cov, size = m)
  459. """
  460. Generate m parameters via non-parametric bootstrapping with a minimal constraint
  461. that both groups should be present in the sampled data:
  462. boostrapped sample = (xb, yb) by sampling with replacement pairs (x_i, y_i)
  463. with condition that yb can not be just 0 or just 1
  464. Input:
  465. x : array of n floats
  466. y : array of n int in {0,1}
  467. m: integer, number of samples
  468. seed : int, seed for the random generator
  469. Return:
  470. array of mx(degree + 1)
  471. """
  472. def get_nonparam_boots_pars(self, x, y, m, seed = 1977):
  473. # fitting original data
  474. res_fit = self.fit(x, y, method = "diff_evol")
  475. assert res_fit["success"]
  476. pars0 = res_fit["pars"]
  477. n = len(x)
  478. rng = np.random.default_rng(seed)
  479. # generate parameters
  480. lst = [pars0]
  481. while True:
  482. # create set indices for sampling with replacement + constraint
  483. idx = rng.choice(n, n)
  484. if np.sum(y[idx]) in [0, n]: continue
  485. # do fitting
  486. res_fit = self.fit(x[idx], y[idx], pars0, method="local")
  487. if not res_fit["success"]: continue
  488. # store pars
  489. lst.append(res_fit["pars"])
  490. if len(lst) == m: break
  491. return np.array(lst)
  492. """
  493. Generate m parameters via non-parametric stratified bootstrapping:
  494. boostrapped sample = (xb, yb)
  495. xb = (sampled with replacement from x0, sampled with replacement from x1)
  496. yb = (0...0, 1...1)
  497. Input:
  498. x : array of n floats
  499. y : array of n int in {0,1}
  500. m: integer, number of samples
  501. seed : int, seed for the random generator
  502. Return:
  503. array of mx(degree + 1)
  504. """
  505. def get_nonparam_stratified_boots_pars(self, x, y, m, seed = 1977):
  506. # pars of original data
  507. res_fit = self.fit(x, y, method = "diff_evol")
  508. assert res_fit["success"]
  509. pars0 = res_fit["pars"]
  510. # statistics about groups
  511. xs = [x[y == i] for i in range(2)]
  512. ns = [len(e) for e in xs]
  513. # common vector states
  514. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  515. rng = np.random.default_rng(seed)
  516. # generate parameters
  517. lst = [pars0]
  518. for _ in range(m):
  519. # stratified sampling with replacement
  520. xb = np.concatenate([rng.choice(xs[i], ns[i]) for i in range(2)])
  521. # do fitting
  522. res_fit = self.fit(xb, yb, pars0, method="local")
  523. if not res_fit["success"]: continue
  524. # store pars
  525. lst.append(res_fit["pars"])
  526. if len(lst) == m: break
  527. return np.array(lst)
  528. """
  529. Generate m parameters via parametric bootstrapping:
  530. boostrapped sample = (x, yb) yb ~ B(model(x, fitted pars))
  531. where B is Bernoulli distribution
  532. Input:
  533. x : array of n floats
  534. y : array of n int in {0,1}
  535. m: integer, number of samples
  536. seed : int, seed for the random generator
  537. Return:
  538. array of mx(degree + 1)
  539. Ref:
  540. * https://www.scirp.org/journal/paperinformation?paperid=70962
  541. * https://en.wikipedia.org/wiki/Bernoulli_distribution
  542. """
  543. def get_parametric_boots_pars(self, x, y, m, seed = 1977):
  544. # first discuss original dataset
  545. res_fit = self.fit(x, y, method = "diff_evol")
  546. assert res_fit["success"]
  547. pars0 = res_fit["pars"]
  548. p = self.model(x, pars0)
  549. n = len(x)
  550. rng = np.random.default_rng(seed)
  551. # generate parameters
  552. lst = [pars0]
  553. while True:
  554. # Generate new binary outcomes from Bernoulli(p_i)
  555. y_sim = rng.binomial(n = 1, p = p)
  556. if np.sum(y_sim) in [0, n]: continue
  557. # do fitting
  558. res_fit = self.fit(x, y_sim, pars0, method="local")
  559. if not res_fit["success"]: continue
  560. # store pars
  561. lst.append(res_fit["pars"])
  562. if len(lst) == m: break
  563. return np.array(lst)