statistics.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. """
  2. Basic statistics module.
  3. This module provides functions for calculating statistics of data, including
  4. averages, variance, and standard deviation.
  5. Calculating averages
  6. --------------------
  7. ================== =============================================
  8. Function Description
  9. ================== =============================================
  10. mean Arithmetic mean (average) of data.
  11. harmonic_mean Harmonic mean of data.
  12. median Median (middle value) of data.
  13. median_low Low median of data.
  14. median_high High median of data.
  15. median_grouped Median, or 50th percentile, of grouped data.
  16. mode Mode (most common value) of data.
  17. ================== =============================================
  18. Calculate the arithmetic mean ("the average") of data:
  19. >>> mean([-1.0, 2.5, 3.25, 5.75])
  20. 2.625
  21. Calculate the standard median of discrete data:
  22. >>> median([2, 3, 4, 5])
  23. 3.5
  24. Calculate the median, or 50th percentile, of data grouped into class intervals
  25. centred on the data values provided. E.g. if your data points are rounded to
  26. the nearest whole number:
  27. >>> median_grouped([2, 2, 3, 3, 3, 4]) #doctest: +ELLIPSIS
  28. 2.8333333333...
  29. This should be interpreted in this way: you have two data points in the class
  30. interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
  31. the class interval 3.5-4.5. The median of these data points is 2.8333...
  32. Calculating variability or spread
  33. ---------------------------------
  34. ================== =============================================
  35. Function Description
  36. ================== =============================================
  37. pvariance Population variance of data.
  38. variance Sample variance of data.
  39. pstdev Population standard deviation of data.
  40. stdev Sample standard deviation of data.
  41. ================== =============================================
  42. Calculate the standard deviation of sample data:
  43. >>> stdev([2.5, 3.25, 5.5, 11.25, 11.75]) #doctest: +ELLIPSIS
  44. 4.38961843444...
  45. If you have previously calculated the mean, you can pass it as the optional
  46. second argument to the four "spread" functions to avoid recalculating it:
  47. >>> data = [1, 2, 2, 4, 4, 4, 5, 6]
  48. >>> mu = mean(data)
  49. >>> pvariance(data, mu)
  50. 2.5
  51. Exceptions
  52. ----------
  53. A single exception is defined: StatisticsError is a subclass of ValueError.
  54. """
  55. __all__ = [ 'StatisticsError',
  56. 'pstdev', 'pvariance', 'stdev', 'variance',
  57. 'median', 'median_low', 'median_high', 'median_grouped',
  58. 'mean', 'mode', 'harmonic_mean',
  59. ]
  60. import collections
  61. import math
  62. import numbers
  63. from fractions import Fraction
  64. from decimal import Decimal
  65. from itertools import groupby
  66. from bisect import bisect_left, bisect_right
  67. # === Exceptions ===
  68. class StatisticsError(ValueError):
  69. pass
  70. # === Private utilities ===
  71. def _sum(data, start=0):
  72. """_sum(data [, start]) -> (type, sum, count)
  73. Return a high-precision sum of the given numeric data as a fraction,
  74. together with the type to be converted to and the count of items.
  75. If optional argument ``start`` is given, it is added to the total.
  76. If ``data`` is empty, ``start`` (defaulting to 0) is returned.
  77. Examples
  78. --------
  79. >>> _sum([3, 2.25, 4.5, -0.5, 1.0], 0.75)
  80. (<class 'float'>, Fraction(11, 1), 5)
  81. Some sources of round-off error will be avoided:
  82. # Built-in sum returns zero.
  83. >>> _sum([1e50, 1, -1e50] * 1000)
  84. (<class 'float'>, Fraction(1000, 1), 3000)
  85. Fractions and Decimals are also supported:
  86. >>> from fractions import Fraction as F
  87. >>> _sum([F(2, 3), F(7, 5), F(1, 4), F(5, 6)])
  88. (<class 'fractions.Fraction'>, Fraction(63, 20), 4)
  89. >>> from decimal import Decimal as D
  90. >>> data = [D("0.1375"), D("0.2108"), D("0.3061"), D("0.0419")]
  91. >>> _sum(data)
  92. (<class 'decimal.Decimal'>, Fraction(6963, 10000), 4)
  93. Mixed types are currently treated as an error, except that int is
  94. allowed.
  95. """
  96. count = 0
  97. n, d = _exact_ratio(start)
  98. partials = {d: n}
  99. partials_get = partials.get
  100. T = _coerce(int, type(start))
  101. for typ, values in groupby(data, type):
  102. T = _coerce(T, typ) # or raise TypeError
  103. for n,d in map(_exact_ratio, values):
  104. count += 1
  105. partials[d] = partials_get(d, 0) + n
  106. if None in partials:
  107. # The sum will be a NAN or INF. We can ignore all the finite
  108. # partials, and just look at this special one.
  109. total = partials[None]
  110. assert not _isfinite(total)
  111. else:
  112. # Sum all the partial sums using builtin sum.
  113. # FIXME is this faster if we sum them in order of the denominator?
  114. total = sum(Fraction(n, d) for d, n in sorted(partials.items()))
  115. return (T, total, count)
  116. def _isfinite(x):
  117. try:
  118. return x.is_finite() # Likely a Decimal.
  119. except AttributeError:
  120. return math.isfinite(x) # Coerces to float first.
  121. def _coerce(T, S):
  122. """Coerce types T and S to a common type, or raise TypeError.
  123. Coercion rules are currently an implementation detail. See the CoerceTest
  124. test class in test_statistics for details.
  125. """
  126. # See http://bugs.python.org/issue24068.
  127. assert T is not bool, "initial type T is bool"
  128. # If the types are the same, no need to coerce anything. Put this
  129. # first, so that the usual case (no coercion needed) happens as soon
  130. # as possible.
  131. if T is S: return T
  132. # Mixed int & other coerce to the other type.
  133. if S is int or S is bool: return T
  134. if T is int: return S
  135. # If one is a (strict) subclass of the other, coerce to the subclass.
  136. if issubclass(S, T): return S
  137. if issubclass(T, S): return T
  138. # Ints coerce to the other type.
  139. if issubclass(T, int): return S
  140. if issubclass(S, int): return T
  141. # Mixed fraction & float coerces to float (or float subclass).
  142. if issubclass(T, Fraction) and issubclass(S, float):
  143. return S
  144. if issubclass(T, float) and issubclass(S, Fraction):
  145. return T
  146. # Any other combination is disallowed.
  147. msg = "don't know how to coerce %s and %s"
  148. raise TypeError(msg % (T.__name__, S.__name__))
  149. def _exact_ratio(x):
  150. """Return Real number x to exact (numerator, denominator) pair.
  151. >>> _exact_ratio(0.25)
  152. (1, 4)
  153. x is expected to be an int, Fraction, Decimal or float.
  154. """
  155. try:
  156. # Optimise the common case of floats. We expect that the most often
  157. # used numeric type will be builtin floats, so try to make this as
  158. # fast as possible.
  159. if type(x) is float or type(x) is Decimal:
  160. return x.as_integer_ratio()
  161. try:
  162. # x may be an int, Fraction, or Integral ABC.
  163. return (x.numerator, x.denominator)
  164. except AttributeError:
  165. try:
  166. # x may be a float or Decimal subclass.
  167. return x.as_integer_ratio()
  168. except AttributeError:
  169. # Just give up?
  170. pass
  171. except (OverflowError, ValueError):
  172. # float NAN or INF.
  173. assert not _isfinite(x)
  174. return (x, None)
  175. msg = "can't convert type '{}' to numerator/denominator"
  176. raise TypeError(msg.format(type(x).__name__))
  177. def _convert(value, T):
  178. """Convert value to given numeric type T."""
  179. if type(value) is T:
  180. # This covers the cases where T is Fraction, or where value is
  181. # a NAN or INF (Decimal or float).
  182. return value
  183. if issubclass(T, int) and value.denominator != 1:
  184. T = float
  185. try:
  186. # FIXME: what do we do if this overflows?
  187. return T(value)
  188. except TypeError:
  189. if issubclass(T, Decimal):
  190. return T(value.numerator)/T(value.denominator)
  191. else:
  192. raise
  193. def _counts(data):
  194. # Generate a table of sorted (value, frequency) pairs.
  195. table = collections.Counter(iter(data)).most_common()
  196. if not table:
  197. return table
  198. # Extract the values with the highest frequency.
  199. maxfreq = table[0][1]
  200. for i in range(1, len(table)):
  201. if table[i][1] != maxfreq:
  202. table = table[:i]
  203. break
  204. return table
  205. def _find_lteq(a, x):
  206. 'Locate the leftmost value exactly equal to x'
  207. i = bisect_left(a, x)
  208. if i != len(a) and a[i] == x:
  209. return i
  210. raise ValueError
  211. def _find_rteq(a, l, x):
  212. 'Locate the rightmost value exactly equal to x'
  213. i = bisect_right(a, x, lo=l)
  214. if i != (len(a)+1) and a[i-1] == x:
  215. return i-1
  216. raise ValueError
  217. def _fail_neg(values, errmsg='negative value'):
  218. """Iterate over values, failing if any are less than zero."""
  219. for x in values:
  220. if x < 0:
  221. raise StatisticsError(errmsg)
  222. yield x
  223. # === Measures of central tendency (averages) ===
  224. def mean(data):
  225. """Return the sample arithmetic mean of data.
  226. >>> mean([1, 2, 3, 4, 4])
  227. 2.8
  228. >>> from fractions import Fraction as F
  229. >>> mean([F(3, 7), F(1, 21), F(5, 3), F(1, 3)])
  230. Fraction(13, 21)
  231. >>> from decimal import Decimal as D
  232. >>> mean([D("0.5"), D("0.75"), D("0.625"), D("0.375")])
  233. Decimal('0.5625')
  234. If ``data`` is empty, StatisticsError will be raised.
  235. """
  236. if iter(data) is data:
  237. data = list(data)
  238. n = len(data)
  239. if n < 1:
  240. raise StatisticsError('mean requires at least one data point')
  241. T, total, count = _sum(data)
  242. assert count == n
  243. return _convert(total/n, T)
  244. def harmonic_mean(data):
  245. """Return the harmonic mean of data.
  246. The harmonic mean, sometimes called the subcontrary mean, is the
  247. reciprocal of the arithmetic mean of the reciprocals of the data,
  248. and is often appropriate when averaging quantities which are rates
  249. or ratios, for example speeds. Example:
  250. Suppose an investor purchases an equal value of shares in each of
  251. three companies, with P/E (price/earning) ratios of 2.5, 3 and 10.
  252. What is the average P/E ratio for the investor's portfolio?
  253. >>> harmonic_mean([2.5, 3, 10]) # For an equal investment portfolio.
  254. 3.6
  255. Using the arithmetic mean would give an average of about 5.167, which
  256. is too high.
  257. If ``data`` is empty, or any element is less than zero,
  258. ``harmonic_mean`` will raise ``StatisticsError``.
  259. """
  260. # For a justification for using harmonic mean for P/E ratios, see
  261. # http://fixthepitch.pellucid.com/comps-analysis-the-missing-harmony-of-summary-statistics/
  262. # http://papers.ssrn.com/sol3/papers.cfm?abstract_id=2621087
  263. if iter(data) is data:
  264. data = list(data)
  265. errmsg = 'harmonic mean does not support negative values'
  266. n = len(data)
  267. if n < 1:
  268. raise StatisticsError('harmonic_mean requires at least one data point')
  269. elif n == 1:
  270. x = data[0]
  271. if isinstance(x, (numbers.Real, Decimal)):
  272. if x < 0:
  273. raise StatisticsError(errmsg)
  274. return x
  275. else:
  276. raise TypeError('unsupported type')
  277. try:
  278. T, total, count = _sum(1/x for x in _fail_neg(data, errmsg))
  279. except ZeroDivisionError:
  280. return 0
  281. assert count == n
  282. return _convert(n/total, T)
  283. # FIXME: investigate ways to calculate medians without sorting? Quickselect?
  284. def median(data):
  285. """Return the median (middle value) of numeric data.
  286. When the number of data points is odd, return the middle data point.
  287. When the number of data points is even, the median is interpolated by
  288. taking the average of the two middle values:
  289. >>> median([1, 3, 5])
  290. 3
  291. >>> median([1, 3, 5, 7])
  292. 4.0
  293. """
  294. data = sorted(data)
  295. n = len(data)
  296. if n == 0:
  297. raise StatisticsError("no median for empty data")
  298. if n%2 == 1:
  299. return data[n//2]
  300. else:
  301. i = n//2
  302. return (data[i - 1] + data[i])/2
  303. def median_low(data):
  304. """Return the low median of numeric data.
  305. When the number of data points is odd, the middle value is returned.
  306. When it is even, the smaller of the two middle values is returned.
  307. >>> median_low([1, 3, 5])
  308. 3
  309. >>> median_low([1, 3, 5, 7])
  310. 3
  311. """
  312. data = sorted(data)
  313. n = len(data)
  314. if n == 0:
  315. raise StatisticsError("no median for empty data")
  316. if n%2 == 1:
  317. return data[n//2]
  318. else:
  319. return data[n//2 - 1]
  320. def median_high(data):
  321. """Return the high median of data.
  322. When the number of data points is odd, the middle value is returned.
  323. When it is even, the larger of the two middle values is returned.
  324. >>> median_high([1, 3, 5])
  325. 3
  326. >>> median_high([1, 3, 5, 7])
  327. 5
  328. """
  329. data = sorted(data)
  330. n = len(data)
  331. if n == 0:
  332. raise StatisticsError("no median for empty data")
  333. return data[n//2]
  334. def median_grouped(data, interval=1):
  335. """Return the 50th percentile (median) of grouped continuous data.
  336. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5])
  337. 3.7
  338. >>> median_grouped([52, 52, 53, 54])
  339. 52.5
  340. This calculates the median as the 50th percentile, and should be
  341. used when your data is continuous and grouped. In the above example,
  342. the values 1, 2, 3, etc. actually represent the midpoint of classes
  343. 0.5-1.5, 1.5-2.5, 2.5-3.5, etc. The middle value falls somewhere in
  344. class 3.5-4.5, and interpolation is used to estimate it.
  345. Optional argument ``interval`` represents the class interval, and
  346. defaults to 1. Changing the class interval naturally will change the
  347. interpolated 50th percentile value:
  348. >>> median_grouped([1, 3, 3, 5, 7], interval=1)
  349. 3.25
  350. >>> median_grouped([1, 3, 3, 5, 7], interval=2)
  351. 3.5
  352. This function does not check whether the data points are at least
  353. ``interval`` apart.
  354. """
  355. data = sorted(data)
  356. n = len(data)
  357. if n == 0:
  358. raise StatisticsError("no median for empty data")
  359. elif n == 1:
  360. return data[0]
  361. # Find the value at the midpoint. Remember this corresponds to the
  362. # centre of the class interval.
  363. x = data[n//2]
  364. for obj in (x, interval):
  365. if isinstance(obj, (str, bytes)):
  366. raise TypeError('expected number but got %r' % obj)
  367. try:
  368. L = x - interval/2 # The lower limit of the median interval.
  369. except TypeError:
  370. # Mixed type. For now we just coerce to float.
  371. L = float(x) - float(interval)/2
  372. # Uses bisection search to search for x in data with log(n) time complexity
  373. # Find the position of leftmost occurrence of x in data
  374. l1 = _find_lteq(data, x)
  375. # Find the position of rightmost occurrence of x in data[l1...len(data)]
  376. # Assuming always l1 <= l2
  377. l2 = _find_rteq(data, l1, x)
  378. cf = l1
  379. f = l2 - l1 + 1
  380. return L + interval*(n/2 - cf)/f
  381. def mode(data):
  382. """Return the most common data point from discrete or nominal data.
  383. ``mode`` assumes discrete data, and returns a single value. This is the
  384. standard treatment of the mode as commonly taught in schools:
  385. >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
  386. 3
  387. This also works with nominal (non-numeric) data:
  388. >>> mode(["red", "blue", "blue", "red", "green", "red", "red"])
  389. 'red'
  390. If there is not exactly one most common value, ``mode`` will raise
  391. StatisticsError.
  392. """
  393. # Generate a table of sorted (value, frequency) pairs.
  394. table = _counts(data)
  395. if len(table) == 1:
  396. return table[0][0]
  397. elif table:
  398. raise StatisticsError(
  399. 'no unique mode; found %d equally common values' % len(table)
  400. )
  401. else:
  402. raise StatisticsError('no mode for empty data')
  403. # === Measures of spread ===
  404. # See http://mathworld.wolfram.com/Variance.html
  405. # http://mathworld.wolfram.com/SampleVariance.html
  406. # http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  407. #
  408. # Under no circumstances use the so-called "computational formula for
  409. # variance", as that is only suitable for hand calculations with a small
  410. # amount of low-precision data. It has terrible numeric properties.
  411. #
  412. # See a comparison of three computational methods here:
  413. # http://www.johndcook.com/blog/2008/09/26/comparing-three-methods-of-computing-standard-deviation/
  414. def _ss(data, c=None):
  415. """Return sum of square deviations of sequence data.
  416. If ``c`` is None, the mean is calculated in one pass, and the deviations
  417. from the mean are calculated in a second pass. Otherwise, deviations are
  418. calculated from ``c`` as given. Use the second case with care, as it can
  419. lead to garbage results.
  420. """
  421. if c is None:
  422. c = mean(data)
  423. T, total, count = _sum((x-c)**2 for x in data)
  424. # The following sum should mathematically equal zero, but due to rounding
  425. # error may not.
  426. U, total2, count2 = _sum((x-c) for x in data)
  427. assert T == U and count == count2
  428. total -= total2**2/len(data)
  429. assert not total < 0, 'negative sum of square deviations: %f' % total
  430. return (T, total)
  431. def variance(data, xbar=None):
  432. """Return the sample variance of data.
  433. data should be an iterable of Real-valued numbers, with at least two
  434. values. The optional argument xbar, if given, should be the mean of
  435. the data. If it is missing or None, the mean is automatically calculated.
  436. Use this function when your data is a sample from a population. To
  437. calculate the variance from the entire population, see ``pvariance``.
  438. Examples:
  439. >>> data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5]
  440. >>> variance(data)
  441. 1.3720238095238095
  442. If you have already calculated the mean of your data, you can pass it as
  443. the optional second argument ``xbar`` to avoid recalculating it:
  444. >>> m = mean(data)
  445. >>> variance(data, m)
  446. 1.3720238095238095
  447. This function does not check that ``xbar`` is actually the mean of
  448. ``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
  449. impossible results.
  450. Decimals and Fractions are supported:
  451. >>> from decimal import Decimal as D
  452. >>> variance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  453. Decimal('31.01875')
  454. >>> from fractions import Fraction as F
  455. >>> variance([F(1, 6), F(1, 2), F(5, 3)])
  456. Fraction(67, 108)
  457. """
  458. if iter(data) is data:
  459. data = list(data)
  460. n = len(data)
  461. if n < 2:
  462. raise StatisticsError('variance requires at least two data points')
  463. T, ss = _ss(data, xbar)
  464. return _convert(ss/(n-1), T)
  465. def pvariance(data, mu=None):
  466. """Return the population variance of ``data``.
  467. data should be an iterable of Real-valued numbers, with at least one
  468. value. The optional argument mu, if given, should be the mean of
  469. the data. If it is missing or None, the mean is automatically calculated.
  470. Use this function to calculate the variance from the entire population.
  471. To estimate the variance from a sample, the ``variance`` function is
  472. usually a better choice.
  473. Examples:
  474. >>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
  475. >>> pvariance(data)
  476. 1.25
  477. If you have already calculated the mean of the data, you can pass it as
  478. the optional second argument to avoid recalculating it:
  479. >>> mu = mean(data)
  480. >>> pvariance(data, mu)
  481. 1.25
  482. This function does not check that ``mu`` is actually the mean of ``data``.
  483. Giving arbitrary values for ``mu`` may lead to invalid or impossible
  484. results.
  485. Decimals and Fractions are supported:
  486. >>> from decimal import Decimal as D
  487. >>> pvariance([D("27.5"), D("30.25"), D("30.25"), D("34.5"), D("41.75")])
  488. Decimal('24.815')
  489. >>> from fractions import Fraction as F
  490. >>> pvariance([F(1, 4), F(5, 4), F(1, 2)])
  491. Fraction(13, 72)
  492. """
  493. if iter(data) is data:
  494. data = list(data)
  495. n = len(data)
  496. if n < 1:
  497. raise StatisticsError('pvariance requires at least one data point')
  498. T, ss = _ss(data, mu)
  499. return _convert(ss/n, T)
  500. def stdev(data, xbar=None):
  501. """Return the square root of the sample variance.
  502. See ``variance`` for arguments and other details.
  503. >>> stdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  504. 1.0810874155219827
  505. """
  506. var = variance(data, xbar)
  507. try:
  508. return var.sqrt()
  509. except AttributeError:
  510. return math.sqrt(var)
  511. def pstdev(data, mu=None):
  512. """Return the square root of the population variance.
  513. See ``pvariance`` for arguments and other details.
  514. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75])
  515. 0.986893273527251
  516. """
  517. var = pvariance(data, mu)
  518. try:
  519. return var.sqrt()
  520. except AttributeError:
  521. return math.sqrt(var)