logit_utils.py 11 KB

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