logit_utils_gen.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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. dict {"pars", "cost", "success"}
  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. "chi2": chi2 statistic,}
  278. Ref:
  279. https://en.wikipedia.org/wiki/Logistic_regression
  280. https://en.wikipedia.org/wiki/Akaike_information_criterion
  281. https://www.medicine.mcgill.ca/epidemiology/joseph/courses/epib-621/logfit.pdf
  282. """
  283. def goodness_of_fit(self, x, y, pars, thresh = 0.5):
  284. # model probabilities
  285. p = self.model(x, pars)
  286. # log likelihood
  287. llf = -self.nllf(x, y, pars)
  288. # information criteria
  289. k, n = len(pars), len(x)
  290. AIC = 2*k - 2*llf
  291. BIC = k*np.log(n) - 2*llf
  292. # chi2
  293. dof = n - k
  294. r = (y - p)/np.sqrt(p*(1-p) + self.small)
  295. chi2 = np.sum(r**2)
  296. p_val = scipy.stats.chi2.sf(chi2, dof)
  297. # using model as classifier
  298. matches = y == np.heaviside(p - thresh, 1)
  299. # accuracy A
  300. A = np.count_nonzero(matches)/n
  301. return {"LLF": llf,
  302. "AIC": AIC,
  303. "BIC": BIC,
  304. "A" : A,
  305. "chi2": chi2,
  306. "p-value(chi2)": p_val, # not very useful
  307. "n": n, "k": k, "dof": dof}
  308. """
  309. Calculation of asymptotic variance-covariance matrix of regression
  310. parameters pars
  311. cov_{asymp}[pars] = H^{-1}
  312. where H is hessian of nllf
  313. H = [d^2(nllf)/(d(pars)_a d(pars)_b ]_{a,b}
  314. for the logistic regression of the polynomial model:
  315. log(f(x)/(1 - f(x))) ~ sum_{i=0}^degree b_i(pars) x^i
  316. Input:
  317. x: array of n floats
  318. pars: array of r = degree+1 floats, model parameters
  319. Return:
  320. array of rxr floats; r = degree + 1
  321. Ref:
  322. * https://stats.stackexchange.com/questions/89484/how-to-compute-the-standard-errors-of-a-logistic-regressions-coefficients
  323. * https://goodboychan.github.io/machine_learning/2020/09/14/02-Regularized-likelihood-methods.html
  324. """
  325. def cov(self, x, y, pars):
  326. # coefficients
  327. beta = self.get_beta(pars)
  328. # design matrix -- add column of 1's at the beginning of your X_train matrix
  329. X = np.column_stack([x**i for i in range(len(beta))])
  330. # Jacobian J = [dbeta_i/dpars_j]_{ij}
  331. J, H = self.get_jac_beta(pars, hess = True)
  332. # signs
  333. s = 2.0*y - 1
  334. # decision function for conditional probability Prob(Y = y| x)
  335. F = s*(X @ beta)
  336. # probabilities p_i = P(Y=y_i | x_i)
  337. p = safe_expit(F)
  338. q = 1 - p
  339. # calculate hessian
  340. L = X @ J
  341. H = (L.T*(q*p))@L - np.tensordot((s*q)@X, H, axes = ([0], [0]))
  342. if self.lam is not None:
  343. Hp = H + 2*self.lam[1]*np.eye(len(pars)) # H' = H + lambda id
  344. iHp = np.linalg.inv(Hp) # inv(H')
  345. return iHp@H@iHp
  346. # covariance matrix C_params = H^-1
  347. return np.linalg.inv(H)
  348. """
  349. Calculating standard errors fo model parameters for normal distribution of parameters:
  350. pars ~ N(mean_pars, cov_pars)
  351. Input:
  352. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  353. Return:
  354. array of r floats, standard errors of parameters
  355. """
  356. def get_SE_pars_normal(self, cov_pars):
  357. # computing standard errors of parameters
  358. return np.sqrt(np.diag(cov_pars))
  359. """
  360. Calculating quantiles of the model parameters at given probabilities p
  361. for normal distribution of parameters:
  362. pars ~ N(mean_pars, cov_pars)
  363. Input:
  364. probs: array of m floats, probabilities
  365. mean_pars: array of r = degree+1 floats, mean model parameters
  366. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  367. Return:
  368. array of mxr floats
  369. """
  370. def get_pars_quantiles_normal(self, probs, mean_pars, cov_pars):
  371. # mean and standard variance parameters
  372. locs = mean_pars
  373. scales = np.sqrt(np.diag(cov_pars))
  374. # computing quantiles of parameters
  375. return locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  376. """
  377. Calculating quantiles of the model values
  378. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  379. with
  380. F(x|beta) = sum_{i=0}^degree x^i beta_i
  381. at given probabilities p and values x assuming
  382. normal distribution of parameters:
  383. pars ~ N(mean_pars, cov_pars)
  384. This distribution is asymptotic MLE distribution of parameters.
  385. Input:
  386. x: array of n float
  387. probs: array of m floats, probabilities
  388. mean_pars: array of r = degree+1 floats, mean model parameters
  389. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  390. Return:
  391. array of mxn floats
  392. """
  393. def get_model_quantiles_normal(self, x, probs, mean_pars, cov_pars,
  394. exact = True, seed = 1977, m = 10**5):
  395. mean_beta = self.get_beta(mean_pars)
  396. X = np.column_stack([x**i for i in range(len(mean_beta))])
  397. if exact and self.mono3:
  398. # init random generator
  399. rng = np.random.default_rng(seed)
  400. pars = rng.multivariate_normal(mean_pars, cov_pars, size = m)
  401. # get betas
  402. beta = np.apply_along_axis(self.get_beta, 1, pars)
  403. # quantiles of decision function
  404. Q = np.quantile(X@beta.T, probs, axis = 1)
  405. return np.apply_along_axis(safe_expit, 1, Q)
  406. # J = d(beta)/d(pars)
  407. J = self.get_jac_beta(mean_pars)
  408. # transform data
  409. S = X@J
  410. # mean and standard variance of logit (aka log of odds)
  411. locs = X@mean_beta
  412. scales = np.sqrt(np.diag(S@cov_pars@S.T))
  413. # computing quantiles of logit
  414. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  415. # convert logit to expit
  416. return safe_expit(Q)
  417. """
  418. Calculating quantiles using delta method of the model values
  419. f(x|pars) = 1/(1 + exp(-F(x|beta))) beta = beta(pars)
  420. with
  421. F(x|beta) = sum_{i=0}^degree x^i beta_i
  422. at given probabilities p and values x assuming
  423. normal distribution of parameters :
  424. pars ~ N(mean_pars, cov_pars)
  425. This distribution is asymptotic MLE distribution of parameters.
  426. We approximate exact model with linear expansion
  427. f(x|pars) = p(x|pars_mean) + dp/db(x|pars_mean) (pars - pars_mean)
  428. and the last term is normally distributed.
  429. Input:
  430. x: array of n float
  431. probs: array of m floats, probabilities
  432. mean_pars: array of r = degree+1 floats, mean model parameters
  433. cov_pars: array of rxr floats, variance-covariance matrix of parameters
  434. Return:
  435. array of mxn floats
  436. """
  437. def get_model_quantiles_delta(self, x, probs, mean_pars, cov_pars):
  438. mean_beta = self.get_beta(mean_pars)
  439. X = np.column_stack([x**i for i in range(len(mean_beta))])
  440. F = X@mean_beta
  441. # J = d(beta)/d(pars)
  442. J = self.get_jac_beta(mean_pars)
  443. # S = d(F)/d(pars)
  444. S = X@J
  445. # attributes of normal distribution of model values
  446. locs = safe_expit(F)
  447. scales = np.sqrt(np.diag(S@cov_pars@S.T))/(4*np.cosh(F/2)**2)
  448. # computing quantiles of logit
  449. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  450. return np.clip(Q, a_min = 0, a_max = 1)
  451. """
  452. Generate parameters assuming normal distribution.
  453. Input:
  454. x : array of n floats
  455. y : array of n int in {0,1}
  456. m: integer, number of samples
  457. seed : int, seed for the random generator
  458. Return:
  459. array of mx(degree + 1)
  460. """
  461. def get_normal_pars(self, x, y, m, seed = 1977):
  462. res = self.fit(x, y, method = "diff_evol")
  463. assert res["success"], "Fit did not succeed."
  464. # optimal parameters
  465. pars = res["pars"]
  466. # covariance matrix of parameters
  467. cov = self.cov(x, y, pars)
  468. # init random generator
  469. rng = np.random.default_rng(seed)
  470. return rng.multivariate_normal(pars, cov, size = m)
  471. """
  472. Generate m parameters via non-parametric bootstrapping with a minimal constraint
  473. that both groups should be present in the sampled data:
  474. boostrapped sample = (xb, yb) by sampling with replacement pairs (x_i, y_i)
  475. with condition that yb can not be just 0 or just 1
  476. Input:
  477. x : array of n floats
  478. y : array of n int in {0,1}
  479. m: integer, number of samples
  480. seed : int, seed for the random generator
  481. Return:
  482. array of mx(degree + 1)
  483. """
  484. def get_nonparam_boots_pars(self, x, y, m, seed = 1977):
  485. # fitting original data
  486. res_fit = self.fit(x, y, method = "diff_evol")
  487. assert res_fit["success"]
  488. pars0 = res_fit["pars"]
  489. n = len(x)
  490. rng = np.random.default_rng(seed)
  491. # generate parameters
  492. lst = [pars0]
  493. while True:
  494. # create set indices for sampling with replacement + constraint
  495. idx = rng.choice(n, n)
  496. if np.sum(y[idx]) in [0, n]: continue
  497. # do fitting
  498. res_fit = self.fit(x[idx], y[idx], pars0, method="local")
  499. if not res_fit["success"]: continue
  500. # store pars
  501. lst.append(res_fit["pars"])
  502. if len(lst) == m: break
  503. return np.array(lst)
  504. """
  505. Generate m parameters via non-parametric stratified bootstrapping:
  506. boostrapped sample = (xb, yb)
  507. xb = (sampled with replacement from x0, sampled with replacement from x1)
  508. yb = (0...0, 1...1)
  509. Input:
  510. x : array of n floats
  511. y : array of n int in {0,1}
  512. m: integer, number of samples
  513. seed : int, seed for the random generator
  514. Return:
  515. array of mx(degree + 1)
  516. """
  517. def get_nonparam_stratified_boots_pars(self, x, y, m, seed = 1977):
  518. # pars of original data
  519. res_fit = self.fit(x, y, method = "diff_evol")
  520. assert res_fit["success"]
  521. pars0 = res_fit["pars"]
  522. # statistics about groups
  523. xs = [x[y == i] for i in range(2)]
  524. ns = [len(e) for e in xs]
  525. # common vector states
  526. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  527. rng = np.random.default_rng(seed)
  528. # generate parameters
  529. lst = [pars0]
  530. for _ in range(m):
  531. # stratified sampling with replacement
  532. xb = np.concatenate([rng.choice(xs[i], ns[i]) for i in range(2)])
  533. # do fitting
  534. res_fit = self.fit(xb, yb, pars0, method="local")
  535. if not res_fit["success"]: continue
  536. # store pars
  537. lst.append(res_fit["pars"])
  538. if len(lst) == m: break
  539. return np.array(lst)
  540. """
  541. Generate m parameters via parametric bootstrapping:
  542. boostrapped sample = (x, yb) yb ~ B(model(x, fitted pars))
  543. where B is Bernoulli distribution
  544. Input:
  545. x : array of n floats
  546. y : array of n int in {0,1}
  547. m: integer, number of samples
  548. seed : int, seed for the random generator
  549. Return:
  550. array of mx(degree + 1)
  551. Ref:
  552. * https://www.scirp.org/journal/paperinformation?paperid=70962
  553. * https://en.wikipedia.org/wiki/Bernoulli_distribution
  554. """
  555. def get_parametric_boots_pars(self, x, y, m, seed = 1977):
  556. # first discuss original dataset
  557. res_fit = self.fit(x, y, method = "diff_evol")
  558. assert res_fit["success"]
  559. pars0 = res_fit["pars"]
  560. p = self.model(x, pars0)
  561. n = len(x)
  562. rng = np.random.default_rng(seed)
  563. # generate parameters
  564. lst = [pars0]
  565. while True:
  566. # Generate new binary outcomes from Bernoulli(p_i)
  567. y_sim = rng.binomial(n = 1, p = p)
  568. if np.sum(y_sim) in [0, n]: continue
  569. # do fitting
  570. res_fit = self.fit(x, y_sim, pars0, method="local")
  571. if not res_fit["success"]: continue
  572. # store pars
  573. lst.append(res_fit["pars"])
  574. if len(lst) == m: break
  575. return np.array(lst)