logit_utils.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. Input:
  123. x: array of n float
  124. probs: array of m floats, probabilities
  125. mean_b: array of r = degree+1 floats, mean model parameters
  126. cov: array of rxr floats, variance-covariance matrix of parameters
  127. Return:
  128. array of mxn floats
  129. """
  130. def logit_poly_model_quantiles_normal(x, probs, mean_b, cov):
  131. X = np.column_stack([x**i for i in range(len(mean_b))])
  132. # mean and standard variance of logit (aka log of odds)
  133. locs = X@mean_b
  134. scales = np.sqrt(np.diag(X@cov@X.T))
  135. # computing quantiles of logit
  136. Q = locs + np.outer(scipy.stats.norm.ppf(probs),scales)
  137. # convert logit to expit
  138. return 1/(1 + np.exp(-Q))
  139. """
  140. Calculating quantiles using delta method of the model values
  141. p(x|b) = 1/(1 + exp(-F(x|b)))
  142. with
  143. F(x|b) = sum_{i=0}^degree x^i b_i
  144. at given probabilities p and values x assuming
  145. normal distribution of parameters:
  146. b ~ N(mean_b, cov)
  147. We approximate exact model with linear expansion
  148. p(x|b) = p(x|b_mean) + dp/db (x| b_mean) (b - b_mean)
  149. and the last term is normally distributed.
  150. Input:
  151. x: array of n float
  152. probs: array of m floats, probabilities
  153. mean_b: array of r = degree+1 floats, mean model parameters
  154. cov: array of rxr floats, variance-covariance matrix of parameters
  155. Return:
  156. array of mxn floats
  157. """
  158. def logit_poly_model_quantiles_delta(x, probs, mean_b, cov):
  159. X = np.column_stack([x**i for i in range(len(mean_b))])
  160. F = X@mean_b
  161. locs = 1/(1 + np.exp(-F))
  162. scales = np.sqrt(np.diag(X@cov@X.T))/(4*np.cosh(F/2)**2)
  163. # computing quantiles of logit
  164. Q = locs + np.outer(scipy.stats.norm.ppf(probs), scales)
  165. return np.clip(Q, a_min = 0, a_max = 1)