logit_utils_gen.py 22 KB

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