logit_utils.py 9.6 KB

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