logit.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. """
  2. Logistic regression utilities with polynomial logit (log odds) function:
  3. p(x|b) = 1/(1 + exp(-F(x|b)))
  4. with log odds F of polynomial form:
  5. F(x|b) = sum_{i=0}^degree b_i x^i
  6. with decision function (aka logit) F and parameters
  7. b = [b_i]_{i=0}^degree
  8. Author: Martin Horvat, January 2026
  9. """
  10. import numpy as np
  11. import scipy
  12. import scipy.stats
  13. from sklearn import linear_model
  14. """
  15. Model function
  16. p(x|b) = 1/(1 + exp(-F(x|b)))
  17. with log odds of polynomial form:
  18. log(p(x|b)/(1 - p(x|b))) = F(x|b)
  19. F(x|b) = sum_{i=0}^degree b_i x^i
  20. with decision function (aka logit) F and parameters
  21. b = [b_i]_{i=0}^degree
  22. Input:
  23. x: scalar value or a array of values
  24. b = [b_i]_{i=0}^degree: array of r = degree + 1 floats
  25. model parameters array of floats
  26. Return:
  27. model function values
  28. """
  29. def logit_poly_model(x, b):
  30. X = np.column_stack([x**i for i in range(len(b))])
  31. F = X @ b
  32. return 1/(1 + np.exp(-F))
  33. """
  34. Performing logistic regression with log odds of polynomial form:
  35. log(p(x|b)/(1 - p(x|b))) = F(x|b)
  36. F(x|b) = sum_{i=0}^degree b_i x^i
  37. with decision function (aka logit) F and b = [b_i]_{i=0}^degree.
  38. This gives
  39. p(x|b) = 1/(1 + exp(-F(x|b)))
  40. Input:
  41. lm: instance linear_model.LogisticRegression
  42. x: array of n floats
  43. y: array of n int in {0,1}
  44. d: degree of decision function
  45. Return:
  46. params = [b_0, ..., b_degree], array of r = degree + 1 floats
  47. """
  48. def logit_poly_fit(x, y, degree = 1, lm = None):
  49. if lm is None: lm = linear_model.LogisticRegression(penalty = None)
  50. X_feature = np.column_stack([x**i for i in range(1, degree+1)])
  51. lm.fit(X_feature, y)
  52. return np.r_[lm.intercept_[0], lm.coef_[0,:]]
  53. """
  54. Producing goodness of fit measures:
  55. LLF = log_likelihood function
  56. AIC = Akaike information criterion
  57. BIC = Bayesian information criterion
  58. Input:
  59. x: array of n floats
  60. y: array of n int in {0,1}
  61. b: array of r = degree+1 floats, model parameters
  62. thresh: float, default 0.5, threshold value for classification
  63. Return:
  64. {"n": n, "k":k, "dof":n-k,
  65. "LLF": log_likelihood,
  66. "AIC": AIC,
  67. "BIC": BIC,
  68. "A": classification accuracy (threshold values = 0.5 prob)}
  69. Ref:
  70. https://en.wikipedia.org/wiki/Logistic_regression
  71. https://en.wikipedia.org/wiki/Akaike_information_criterion
  72. https://www.medicine.mcgill.ca/epidemiology/joseph/courses/epib-621/logfit.pdf
  73. """
  74. def logit_poly_goodness_of_fit(x, y, b, thresh=0.5):
  75. # model probabilities
  76. p = logit_poly_model(x, b)
  77. # log likelihood
  78. eps = 1e-20 # prevent log(0)
  79. llf = np.sum(y*np.log(p + eps) + (1 - y)*np.log(1 - p + eps))
  80. # information criteria
  81. k, n = len(b), len(x)
  82. AIC = 2*k - 2*llf
  83. BIC = k*np.log(n) - 2*llf
  84. # chi2
  85. dof = n - k
  86. r = (y - p)/np.sqrt(p*(1-p))
  87. chi2 = np.sum(r**2)
  88. p_val = scipy.stats.chi2.sf(chi2, dof)
  89. # using model as classifier
  90. matches = y == np.heaviside(p - thresh, 1)
  91. return {"LLF": llf, "AIC": AIC, "BIC": BIC,
  92. "A" : np.count_nonzero (matches)/n,
  93. "chi2": chi2, "p-value(chi2)": p_val, # not very useful
  94. "n": n, "k": k, "dof": dof}
  95. """
  96. Calculation of asymptotic variance-covariance matrix for the
  97. logistic regression of the polynomial model:
  98. log(p(x)/(1 - p(x))) ~ sum_{i=0}^degree b_i x^i
  99. Input:
  100. x: array of n floats
  101. b: array of r = degree+1 floats, model parameters
  102. Return:
  103. array of rxr floats; r = degree + 1
  104. Ref:
  105. https://stats.stackexchange.com/questions/89484/how-to-compute-the-standard-errors-of-a-logistic-regressions-coefficients
  106. """
  107. def logit_poly_cov(x, b):
  108. # Calculate matrix of predicted class probabilities.
  109. probs = logit_poly_model(x, b)
  110. # Design matrix -- add column of 1's at the beginning of your X_train matrix
  111. X = np.column_stack([x**i for i in range(len(b))])
  112. # Initiate matrix of 0's, fill diagonal with each predicted observation's variance
  113. V = np.diagflat(probs*(1 - probs)) # dig.matrix where each element is p*(1-p)
  114. # Covariance matrix C_params = (X^T V X)^-1
  115. return np.linalg.inv(X.T@V@X)
  116. """
  117. Calculating quantiles of the model parameters at given probabilities p
  118. for normal distribution of parameters:
  119. b ~ N(mean_b, cov)
  120. Input:
  121. probs: array of m floats, probabilities
  122. mean_b: array of r = degree+1 floats, mean model parameters
  123. cov: array of rxr floats, variance-covariance matrix of parameters
  124. Return:
  125. array of mxn floats
  126. """
  127. def logit_poly_pars_quantiles_normal(probs, mean_b, cov):
  128. # mean and standard variance parameters
  129. locs = mean_b
  130. scales = np.sqrt(np.diag(cov))
  131. # computing quantiles of parameters
  132. return locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  133. """
  134. Calculating quantiles of the model values
  135. p(x|b) = 1/(1 + exp(-F(x|b)))
  136. with
  137. F(x|b) = sum_{i=0}^degree x^i b_i
  138. at given probabilities p and values x assuming
  139. normal distribution of parameters:
  140. b ~ N(mean_b, cov)
  141. This distribution is asymptotic MLE distribution of parameters.
  142. Input:
  143. x: array of n float
  144. probs: array of m floats, probabilities
  145. mean_b: array of r = degree+1 floats, mean model parameters
  146. cov: array of rxr floats, variance-covariance matrix of parameters
  147. Return:
  148. array of mxn floats
  149. """
  150. def logit_poly_model_quantiles_normal(x, probs, mean_b, cov):
  151. X = np.column_stack([x**i for i in range(len(mean_b))])
  152. # mean and standard variance of logit (aka log of odds)
  153. locs = X@mean_b
  154. scales = np.sqrt(np.diag(X@cov@X.T))
  155. # computing quantiles of logit
  156. Q = locs + np.outer(scipy.stats.norm.ppf(probs),scales)
  157. # convert logit to expit
  158. return 1/(1 + np.exp(-Q))
  159. """
  160. Calculating quantiles using delta method of the model values
  161. p(x|b) = 1/(1 + exp(-F(x|b)))
  162. with
  163. F(x|b) = sum_{i=0}^degree x^i b_i
  164. at given probabilities p and values x assuming
  165. normal distribution of parameters :
  166. b ~ N(mean_b, cov)
  167. This distribution is asymptotic MLE distribution of parameters.
  168. We approximate exact model with linear expansion
  169. p(x|b) = p(x|b_mean) + dp/db(x| b_mean) (b - b_mean)
  170. and the last term is normally distributed.
  171. Input:
  172. x: array of n float
  173. probs: array of m floats, probabilities
  174. mean_b: array of r = degree+1 floats, mean model parameters
  175. cov: array of rxr floats, variance-covariance matrix of parameters
  176. Return:
  177. array of mxn floats
  178. """
  179. def logit_poly_model_quantiles_delta(x, probs, mean_b, cov):
  180. X = np.column_stack([x**i for i in range(len(mean_b))])
  181. F = X@mean_b
  182. locs = 1/(1 + np.exp(-F))
  183. scales = np.sqrt(np.diag(X@cov@X.T))/(4*np.cosh(F/2)**2)
  184. # computing quantiles of logit
  185. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  186. return np.clip(Q, a_min = 0, a_max = 1)
  187. """
  188. Generate m parameters via non-parametric bootstrapping with a minimal constraint
  189. that both groups should be present in the sampled data:
  190. boostrapped sample = (xb, yb) by sampling with replacement pairs (x_i, y_i)
  191. with condition that yb can not be just 0 or just 1
  192. Input:
  193. x : array of n floats
  194. y : array of n int in {0,1}
  195. m: integer, number of samples
  196. degree: int, degree of decision function
  197. seed : int, seed for the random generator
  198. lm: linear_model.LogisticRegression
  199. Return:
  200. array of mx(degree + 1)
  201. Return:
  202. array of mx(degree + 1)
  203. """
  204. def get_nonparam_boots_pars(x, y, m, degree = 1, seed = 1977, lm = None):
  205. if lm is None: lm = linear_model.LogisticRegression(penalty = None)
  206. rng = np.random.default_rng(seed)
  207. # fitting original data
  208. pars = logit_poly_fit(x, y, degree = degree, lm = lm)
  209. n = len(x)
  210. # generate parameters
  211. lst = [pars]
  212. while True:
  213. # create set indices for sampling with replacement + constraint
  214. idx = rng.choice(n, n)
  215. if np.sum(y[idx]) in [0, n]: continue
  216. lst.append(logit_poly_fit(x[idx], y[idx], degree=degree, lm = lm))
  217. if len(lst) == m: break
  218. return np.array(lst)
  219. """
  220. Generate m parameters via non-parametric stratified bootstrapping:
  221. boostrapped sample = (xb, yb)
  222. xb = (sampled with replacement from x0, sampled with replacement from x1)
  223. yb = (0...0, 1...1)
  224. Input:
  225. x : array of n floats
  226. y : array of n int in {0,1}
  227. m: integer, number of samples
  228. degree: int, degree of decision function
  229. seed : int, seed for the random generator
  230. lm: linear_model.LogisticRegression
  231. Return:
  232. array of mx(degree + 1)
  233. """
  234. def get_nonparam_stratified_boots_pars(x, y, m, degree = 1, seed = 1977, lm = None):
  235. if lm is None: lm = linear_model.LogisticRegression(penalty = None)
  236. rng = np.random.default_rng(seed)
  237. # pars of original data
  238. pars = logit_poly_fit(x, y, degree = degree, lm = lm)
  239. # statistics about groups
  240. xs = [x[y == i] for i in range(2)]
  241. ns = [len(e) for e in xs]
  242. # common vector states
  243. yb = np.concatenate([np.full(ns[i], i) for i in range(2)])
  244. # generate parameters
  245. lst = [pars]
  246. for _ in range(m):
  247. # stratified sampling with replacement
  248. xb = np.concatenate([rng.choice(xs[i], ns[i]) for i in range(2)])
  249. # do fitting
  250. lst.append(logit_poly_fit(xb, yb, degree = degree, lm = lm))
  251. return np.array(lst)
  252. """
  253. Generate m parameters via parametric bootstrapping:
  254. boostrapped sample = (x, yb) yb ~ B(model(x, fitted pars))
  255. where B is Bernoulli distribution
  256. Input:
  257. x : array of n floats
  258. y : array of n int in {0,1}
  259. m: integer, number of samples
  260. degree: int, degree of decision function
  261. seed : int, seed for the random generator
  262. lm: linear_model.LogisticRegression
  263. Return:
  264. array of mx(degree + 1)
  265. Ref:
  266. * https://www.scirp.org/journal/paperinformation?paperid=70962
  267. * https://en.wikipedia.org/wiki/Bernoulli_distribution
  268. """
  269. def get_parametric_boots_pars(x, y, m, degree = 1, seed = 1977, lm = None):
  270. if lm is None: lm = linear_model.LogisticRegression(penalty = None)
  271. # first discuss original dataset
  272. pars = logit_poly_fit(x, y, degree = degree, lm = lm)
  273. p = logit_poly_model(x, pars)
  274. rng = np.random.default_rng(seed)
  275. n = len(x)
  276. # generate parameters
  277. lst = [pars]
  278. while True:
  279. # Generate new binary outcomes from Bernoulli(p_i)
  280. y_sim = rng.binomial(n = 1, p = p)
  281. if np.sum(y_sim) in [0, n]: continue
  282. lst.append(logit_poly_fit(x, y_sim, degree = degree, lm = lm))
  283. if len(lst) == m: break
  284. return np.array(lst)