logit_utils.py 10 KB

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