_binomtest.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. from math import sqrt
  2. import numpy as np
  3. from scipy._lib._util import _validate_int
  4. from scipy.optimize import brentq
  5. from scipy.special import ndtri
  6. from ._discrete_distns import binom
  7. from ._common import ConfidenceInterval
  8. class BinomTestResult:
  9. """
  10. Result of `scipy.stats.binomtest`.
  11. Attributes
  12. ----------
  13. k : int
  14. The number of successes (copied from `binomtest` input).
  15. n : int
  16. The number of trials (copied from `binomtest` input).
  17. alternative : str
  18. Indicates the alternative hypothesis specified in the input
  19. to `binomtest`. It will be one of ``'two-sided'``, ``'greater'``,
  20. or ``'less'``.
  21. statistic: float
  22. The estimate of the proportion of successes.
  23. pvalue : float
  24. The p-value of the hypothesis test.
  25. """
  26. def __init__(self, k, n, alternative, statistic, pvalue):
  27. self.k = k
  28. self.n = n
  29. self.alternative = alternative
  30. self.statistic = statistic
  31. self.pvalue = pvalue
  32. # add alias for backward compatibility
  33. self.proportion_estimate = statistic
  34. def __repr__(self):
  35. s = ("BinomTestResult("
  36. f"k={self.k}, "
  37. f"n={self.n}, "
  38. f"alternative={self.alternative!r}, "
  39. f"statistic={self.statistic}, "
  40. f"pvalue={self.pvalue})")
  41. return s
  42. def proportion_ci(self, confidence_level=0.95, method='exact'):
  43. """
  44. Compute the confidence interval for ``statistic``.
  45. Parameters
  46. ----------
  47. confidence_level : float, optional
  48. Confidence level for the computed confidence interval
  49. of the estimated proportion. Default is 0.95.
  50. method : {'exact', 'wilson', 'wilsoncc'}, optional
  51. Selects the method used to compute the confidence interval
  52. for the estimate of the proportion:
  53. 'exact' :
  54. Use the Clopper-Pearson exact method [1]_.
  55. 'wilson' :
  56. Wilson's method, without continuity correction ([2]_, [3]_).
  57. 'wilsoncc' :
  58. Wilson's method, with continuity correction ([2]_, [3]_).
  59. Default is ``'exact'``.
  60. Returns
  61. -------
  62. ci : ``ConfidenceInterval`` object
  63. The object has attributes ``low`` and ``high`` that hold the
  64. lower and upper bounds of the confidence interval.
  65. References
  66. ----------
  67. .. [1] C. J. Clopper and E. S. Pearson, The use of confidence or
  68. fiducial limits illustrated in the case of the binomial,
  69. Biometrika, Vol. 26, No. 4, pp 404-413 (Dec. 1934).
  70. .. [2] E. B. Wilson, Probable inference, the law of succession, and
  71. statistical inference, J. Amer. Stat. Assoc., 22, pp 209-212
  72. (1927).
  73. .. [3] Robert G. Newcombe, Two-sided confidence intervals for the
  74. single proportion: comparison of seven methods, Statistics
  75. in Medicine, 17, pp 857-872 (1998).
  76. Examples
  77. --------
  78. >>> from scipy.stats import binomtest
  79. >>> result = binomtest(k=7, n=50, p=0.1)
  80. >>> result.statistic
  81. 0.14
  82. >>> result.proportion_ci()
  83. ConfidenceInterval(low=0.05819170033997342, high=0.26739600249700846)
  84. """
  85. if method not in ('exact', 'wilson', 'wilsoncc'):
  86. raise ValueError("method must be one of 'exact', 'wilson' or "
  87. "'wilsoncc'.")
  88. if not (0 <= confidence_level <= 1):
  89. raise ValueError('confidence_level must be in the interval '
  90. '[0, 1].')
  91. if method == 'exact':
  92. low, high = _binom_exact_conf_int(self.k, self.n,
  93. confidence_level,
  94. self.alternative)
  95. else:
  96. # method is 'wilson' or 'wilsoncc'
  97. low, high = _binom_wilson_conf_int(self.k, self.n,
  98. confidence_level,
  99. self.alternative,
  100. correction=method == 'wilsoncc')
  101. return ConfidenceInterval(low=low, high=high)
  102. def _findp(func):
  103. try:
  104. p = brentq(func, 0, 1)
  105. except RuntimeError:
  106. raise RuntimeError('numerical solver failed to converge when '
  107. 'computing the confidence limits') from None
  108. except ValueError as exc:
  109. raise ValueError('brentq raised a ValueError; report this to the '
  110. 'SciPy developers') from exc
  111. return p
  112. def _binom_exact_conf_int(k, n, confidence_level, alternative):
  113. """
  114. Compute the estimate and confidence interval for the binomial test.
  115. Returns proportion, prop_low, prop_high
  116. """
  117. if alternative == 'two-sided':
  118. alpha = (1 - confidence_level) / 2
  119. if k == 0:
  120. plow = 0.0
  121. else:
  122. plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
  123. if k == n:
  124. phigh = 1.0
  125. else:
  126. phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
  127. elif alternative == 'less':
  128. alpha = 1 - confidence_level
  129. plow = 0.0
  130. if k == n:
  131. phigh = 1.0
  132. else:
  133. phigh = _findp(lambda p: binom.cdf(k, n, p) - alpha)
  134. elif alternative == 'greater':
  135. alpha = 1 - confidence_level
  136. if k == 0:
  137. plow = 0.0
  138. else:
  139. plow = _findp(lambda p: binom.sf(k-1, n, p) - alpha)
  140. phigh = 1.0
  141. return plow, phigh
  142. def _binom_wilson_conf_int(k, n, confidence_level, alternative, correction):
  143. # This function assumes that the arguments have already been validated.
  144. # In particular, `alternative` must be one of 'two-sided', 'less' or
  145. # 'greater'.
  146. p = k / n
  147. if alternative == 'two-sided':
  148. z = ndtri(0.5 + 0.5*confidence_level)
  149. else:
  150. z = ndtri(confidence_level)
  151. # For reference, the formulas implemented here are from
  152. # Newcombe (1998) (ref. [3] in the proportion_ci docstring).
  153. denom = 2*(n + z**2)
  154. center = (2*n*p + z**2)/denom
  155. q = 1 - p
  156. if correction:
  157. if alternative == 'less' or k == 0:
  158. lo = 0.0
  159. else:
  160. dlo = (1 + z*sqrt(z**2 - 2 - 1/n + 4*p*(n*q + 1))) / denom
  161. lo = center - dlo
  162. if alternative == 'greater' or k == n:
  163. hi = 1.0
  164. else:
  165. dhi = (1 + z*sqrt(z**2 + 2 - 1/n + 4*p*(n*q - 1))) / denom
  166. hi = center + dhi
  167. else:
  168. delta = z/denom * sqrt(4*n*p*q + z**2)
  169. if alternative == 'less' or k == 0:
  170. lo = 0.0
  171. else:
  172. lo = center - delta
  173. if alternative == 'greater' or k == n:
  174. hi = 1.0
  175. else:
  176. hi = center + delta
  177. return lo, hi
  178. def binomtest(k, n, p=0.5, alternative='two-sided'):
  179. """
  180. Perform a test that the probability of success is p.
  181. The binomial test [1]_ is a test of the null hypothesis that the
  182. probability of success in a Bernoulli experiment is `p`.
  183. Details of the test can be found in many texts on statistics, such
  184. as section 24.5 of [2]_.
  185. Parameters
  186. ----------
  187. k : int
  188. The number of successes.
  189. n : int
  190. The number of trials.
  191. p : float, optional
  192. The hypothesized probability of success, i.e. the expected
  193. proportion of successes. The value must be in the interval
  194. ``0 <= p <= 1``. The default value is ``p = 0.5``.
  195. alternative : {'two-sided', 'greater', 'less'}, optional
  196. Indicates the alternative hypothesis. The default value is
  197. 'two-sided'.
  198. Returns
  199. -------
  200. result : `~scipy.stats._result_classes.BinomTestResult` instance
  201. The return value is an object with the following attributes:
  202. k : int
  203. The number of successes (copied from `binomtest` input).
  204. n : int
  205. The number of trials (copied from `binomtest` input).
  206. alternative : str
  207. Indicates the alternative hypothesis specified in the input
  208. to `binomtest`. It will be one of ``'two-sided'``, ``'greater'``,
  209. or ``'less'``.
  210. statistic : float
  211. The estimate of the proportion of successes.
  212. pvalue : float
  213. The p-value of the hypothesis test.
  214. The object has the following methods:
  215. proportion_ci(confidence_level=0.95, method='exact') :
  216. Compute the confidence interval for ``statistic``.
  217. Notes
  218. -----
  219. .. versionadded:: 1.7.0
  220. References
  221. ----------
  222. .. [1] Binomial test, https://en.wikipedia.org/wiki/Binomial_test
  223. .. [2] Jerrold H. Zar, Biostatistical Analysis (fifth edition),
  224. Prentice Hall, Upper Saddle River, New Jersey USA (2010)
  225. Examples
  226. --------
  227. >>> from scipy.stats import binomtest
  228. A car manufacturer claims that no more than 10% of their cars are unsafe.
  229. 15 cars are inspected for safety, 3 were found to be unsafe. Test the
  230. manufacturer's claim:
  231. >>> result = binomtest(3, n=15, p=0.1, alternative='greater')
  232. >>> result.pvalue
  233. 0.18406106910639114
  234. The null hypothesis cannot be rejected at the 5% level of significance
  235. because the returned p-value is greater than the critical value of 5%.
  236. The test statistic is equal to the estimated proportion, which is simply
  237. ``3/15``:
  238. >>> result.statistic
  239. 0.2
  240. We can use the `proportion_ci()` method of the result to compute the
  241. confidence interval of the estimate:
  242. >>> result.proportion_ci(confidence_level=0.95)
  243. ConfidenceInterval(low=0.05684686759024681, high=1.0)
  244. """
  245. k = _validate_int(k, 'k', minimum=0)
  246. n = _validate_int(n, 'n', minimum=1)
  247. if k > n:
  248. raise ValueError('k must not be greater than n.')
  249. if not (0 <= p <= 1):
  250. raise ValueError("p must be in range [0,1]")
  251. if alternative not in ('two-sided', 'less', 'greater'):
  252. raise ValueError("alternative not recognized; \n"
  253. "must be 'two-sided', 'less' or 'greater'")
  254. if alternative == 'less':
  255. pval = binom.cdf(k, n, p)
  256. elif alternative == 'greater':
  257. pval = binom.sf(k-1, n, p)
  258. else:
  259. # alternative is 'two-sided'
  260. d = binom.pmf(k, n, p)
  261. rerr = 1 + 1e-7
  262. if k == p * n:
  263. # special case as shortcut, would also be handled by `else` below
  264. pval = 1.
  265. elif k < p * n:
  266. ix = _binary_search_for_binom_tst(lambda x1: -binom.pmf(x1, n, p),
  267. -d*rerr, np.ceil(p * n), n)
  268. # y is the number of terms between mode and n that are <= d*rerr.
  269. # ix gave us the first term where a(ix) <= d*rerr < a(ix-1)
  270. # if the first equality doesn't hold, y=n-ix. Otherwise, we
  271. # need to include ix as well as the equality holds. Note that
  272. # the equality will hold in very very rare situations due to rerr.
  273. y = n - ix + int(d*rerr == binom.pmf(ix, n, p))
  274. pval = binom.cdf(k, n, p) + binom.sf(n - y, n, p)
  275. else:
  276. ix = _binary_search_for_binom_tst(lambda x1: binom.pmf(x1, n, p),
  277. d*rerr, 0, np.floor(p * n))
  278. # y is the number of terms between 0 and mode that are <= d*rerr.
  279. # we need to add a 1 to account for the 0 index.
  280. # For comparing this with old behavior, see
  281. # tst_binary_srch_for_binom_tst method in test_morestats.
  282. y = ix + 1
  283. pval = binom.cdf(y-1, n, p) + binom.sf(k-1, n, p)
  284. pval = min(1.0, pval)
  285. result = BinomTestResult(k=k, n=n, alternative=alternative,
  286. statistic=k/n, pvalue=pval)
  287. return result
  288. def _binary_search_for_binom_tst(a, d, lo, hi):
  289. """
  290. Conducts an implicit binary search on a function specified by `a`.
  291. Meant to be used on the binomial PMF for the case of two-sided tests
  292. to obtain the value on the other side of the mode where the tail
  293. probability should be computed. The values on either side of
  294. the mode are always in order, meaning binary search is applicable.
  295. Parameters
  296. ----------
  297. a : callable
  298. The function over which to perform binary search. Its values
  299. for inputs lo and hi should be in ascending order.
  300. d : float
  301. The value to search.
  302. lo : int
  303. The lower end of range to search.
  304. hi : int
  305. The higher end of the range to search.
  306. Returns
  307. -------
  308. int
  309. The index, i between lo and hi
  310. such that a(i)<=d<a(i+1)
  311. """
  312. while lo < hi:
  313. mid = lo + (hi-lo)//2
  314. midval = a(mid)
  315. if midval < d:
  316. lo = mid+1
  317. elif midval > d:
  318. hi = mid-1
  319. else:
  320. return mid
  321. if a(lo) <= d:
  322. return lo
  323. else:
  324. return lo-1