histograms.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122
  1. """
  2. Histogram-related functions
  3. """
  4. from __future__ import division, absolute_import, print_function
  5. import functools
  6. import operator
  7. import warnings
  8. import numpy as np
  9. from numpy.compat.py3k import basestring
  10. from numpy.core import overrides
  11. __all__ = ['histogram', 'histogramdd', 'histogram_bin_edges']
  12. array_function_dispatch = functools.partial(
  13. overrides.array_function_dispatch, module='numpy')
  14. # range is a keyword argument to many functions, so save the builtin so they can
  15. # use it.
  16. _range = range
  17. def _ptp(x):
  18. """Peak-to-peak value of x.
  19. This implementation avoids the problem of signed integer arrays having a
  20. peak-to-peak value that cannot be represented with the array's data type.
  21. This function returns an unsigned value for signed integer arrays.
  22. """
  23. return _unsigned_subtract(x.max(), x.min())
  24. def _hist_bin_sqrt(x, range):
  25. """
  26. Square root histogram bin estimator.
  27. Bin width is inversely proportional to the data size. Used by many
  28. programs for its simplicity.
  29. Parameters
  30. ----------
  31. x : array_like
  32. Input data that is to be histogrammed, trimmed to range. May not
  33. be empty.
  34. Returns
  35. -------
  36. h : An estimate of the optimal bin width for the given data.
  37. """
  38. del range # unused
  39. return _ptp(x) / np.sqrt(x.size)
  40. def _hist_bin_sturges(x, range):
  41. """
  42. Sturges histogram bin estimator.
  43. A very simplistic estimator based on the assumption of normality of
  44. the data. This estimator has poor performance for non-normal data,
  45. which becomes especially obvious for large data sets. The estimate
  46. depends only on size of the data.
  47. Parameters
  48. ----------
  49. x : array_like
  50. Input data that is to be histogrammed, trimmed to range. May not
  51. be empty.
  52. Returns
  53. -------
  54. h : An estimate of the optimal bin width for the given data.
  55. """
  56. del range # unused
  57. return _ptp(x) / (np.log2(x.size) + 1.0)
  58. def _hist_bin_rice(x, range):
  59. """
  60. Rice histogram bin estimator.
  61. Another simple estimator with no normality assumption. It has better
  62. performance for large data than Sturges, but tends to overestimate
  63. the number of bins. The number of bins is proportional to the cube
  64. root of data size (asymptotically optimal). The estimate depends
  65. only on size of the data.
  66. Parameters
  67. ----------
  68. x : array_like
  69. Input data that is to be histogrammed, trimmed to range. May not
  70. be empty.
  71. Returns
  72. -------
  73. h : An estimate of the optimal bin width for the given data.
  74. """
  75. del range # unused
  76. return _ptp(x) / (2.0 * x.size ** (1.0 / 3))
  77. def _hist_bin_scott(x, range):
  78. """
  79. Scott histogram bin estimator.
  80. The binwidth is proportional to the standard deviation of the data
  81. and inversely proportional to the cube root of data size
  82. (asymptotically optimal).
  83. Parameters
  84. ----------
  85. x : array_like
  86. Input data that is to be histogrammed, trimmed to range. May not
  87. be empty.
  88. Returns
  89. -------
  90. h : An estimate of the optimal bin width for the given data.
  91. """
  92. del range # unused
  93. return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x)
  94. def _hist_bin_stone(x, range):
  95. """
  96. Histogram bin estimator based on minimizing the estimated integrated squared error (ISE).
  97. The number of bins is chosen by minimizing the estimated ISE against the unknown true distribution.
  98. The ISE is estimated using cross-validation and can be regarded as a generalization of Scott's rule.
  99. https://en.wikipedia.org/wiki/Histogram#Scott.27s_normal_reference_rule
  100. This paper by Stone appears to be the origination of this rule.
  101. http://digitalassets.lib.berkeley.edu/sdtr/ucb/text/34.pdf
  102. Parameters
  103. ----------
  104. x : array_like
  105. Input data that is to be histogrammed, trimmed to range. May not
  106. be empty.
  107. range : (float, float)
  108. The lower and upper range of the bins.
  109. Returns
  110. -------
  111. h : An estimate of the optimal bin width for the given data.
  112. """
  113. n = x.size
  114. ptp_x = _ptp(x)
  115. if n <= 1 or ptp_x == 0:
  116. return 0
  117. def jhat(nbins):
  118. hh = ptp_x / nbins
  119. p_k = np.histogram(x, bins=nbins, range=range)[0] / n
  120. return (2 - (n + 1) * p_k.dot(p_k)) / hh
  121. nbins_upper_bound = max(100, int(np.sqrt(n)))
  122. nbins = min(_range(1, nbins_upper_bound + 1), key=jhat)
  123. if nbins == nbins_upper_bound:
  124. warnings.warn("The number of bins estimated may be suboptimal.", RuntimeWarning, stacklevel=2)
  125. return ptp_x / nbins
  126. def _hist_bin_doane(x, range):
  127. """
  128. Doane's histogram bin estimator.
  129. Improved version of Sturges' formula which works better for
  130. non-normal data. See
  131. stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning
  132. Parameters
  133. ----------
  134. x : array_like
  135. Input data that is to be histogrammed, trimmed to range. May not
  136. be empty.
  137. Returns
  138. -------
  139. h : An estimate of the optimal bin width for the given data.
  140. """
  141. del range # unused
  142. if x.size > 2:
  143. sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3)))
  144. sigma = np.std(x)
  145. if sigma > 0.0:
  146. # These three operations add up to
  147. # g1 = np.mean(((x - np.mean(x)) / sigma)**3)
  148. # but use only one temp array instead of three
  149. temp = x - np.mean(x)
  150. np.true_divide(temp, sigma, temp)
  151. np.power(temp, 3, temp)
  152. g1 = np.mean(temp)
  153. return _ptp(x) / (1.0 + np.log2(x.size) +
  154. np.log2(1.0 + np.absolute(g1) / sg1))
  155. return 0.0
  156. def _hist_bin_fd(x, range):
  157. """
  158. The Freedman-Diaconis histogram bin estimator.
  159. The Freedman-Diaconis rule uses interquartile range (IQR) to
  160. estimate binwidth. It is considered a variation of the Scott rule
  161. with more robustness as the IQR is less affected by outliers than
  162. the standard deviation. However, the IQR depends on fewer points
  163. than the standard deviation, so it is less accurate, especially for
  164. long tailed distributions.
  165. If the IQR is 0, this function returns 1 for the number of bins.
  166. Binwidth is inversely proportional to the cube root of data size
  167. (asymptotically optimal).
  168. Parameters
  169. ----------
  170. x : array_like
  171. Input data that is to be histogrammed, trimmed to range. May not
  172. be empty.
  173. Returns
  174. -------
  175. h : An estimate of the optimal bin width for the given data.
  176. """
  177. del range # unused
  178. iqr = np.subtract(*np.percentile(x, [75, 25]))
  179. return 2.0 * iqr * x.size ** (-1.0 / 3.0)
  180. def _hist_bin_auto(x, range):
  181. """
  182. Histogram bin estimator that uses the minimum width of the
  183. Freedman-Diaconis and Sturges estimators if the FD bandwidth is non zero
  184. and the Sturges estimator if the FD bandwidth is 0.
  185. The FD estimator is usually the most robust method, but its width
  186. estimate tends to be too large for small `x` and bad for data with limited
  187. variance. The Sturges estimator is quite good for small (<1000) datasets
  188. and is the default in the R language. This method gives good off the shelf
  189. behaviour.
  190. .. versionchanged:: 1.15.0
  191. If there is limited variance the IQR can be 0, which results in the
  192. FD bin width being 0 too. This is not a valid bin width, so
  193. ``np.histogram_bin_edges`` chooses 1 bin instead, which may not be optimal.
  194. If the IQR is 0, it's unlikely any variance based estimators will be of
  195. use, so we revert to the sturges estimator, which only uses the size of the
  196. dataset in its calculation.
  197. Parameters
  198. ----------
  199. x : array_like
  200. Input data that is to be histogrammed, trimmed to range. May not
  201. be empty.
  202. Returns
  203. -------
  204. h : An estimate of the optimal bin width for the given data.
  205. See Also
  206. --------
  207. _hist_bin_fd, _hist_bin_sturges
  208. """
  209. fd_bw = _hist_bin_fd(x, range)
  210. sturges_bw = _hist_bin_sturges(x, range)
  211. del range # unused
  212. if fd_bw:
  213. return min(fd_bw, sturges_bw)
  214. else:
  215. # limited variance, so we return a len dependent bw estimator
  216. return sturges_bw
  217. # Private dict initialized at module load time
  218. _hist_bin_selectors = {'stone': _hist_bin_stone,
  219. 'auto': _hist_bin_auto,
  220. 'doane': _hist_bin_doane,
  221. 'fd': _hist_bin_fd,
  222. 'rice': _hist_bin_rice,
  223. 'scott': _hist_bin_scott,
  224. 'sqrt': _hist_bin_sqrt,
  225. 'sturges': _hist_bin_sturges}
  226. def _ravel_and_check_weights(a, weights):
  227. """ Check a and weights have matching shapes, and ravel both """
  228. a = np.asarray(a)
  229. # Ensure that the array is a "subtractable" dtype
  230. if a.dtype == np.bool_:
  231. warnings.warn("Converting input from {} to {} for compatibility."
  232. .format(a.dtype, np.uint8),
  233. RuntimeWarning, stacklevel=2)
  234. a = a.astype(np.uint8)
  235. if weights is not None:
  236. weights = np.asarray(weights)
  237. if weights.shape != a.shape:
  238. raise ValueError(
  239. 'weights should have the same shape as a.')
  240. weights = weights.ravel()
  241. a = a.ravel()
  242. return a, weights
  243. def _get_outer_edges(a, range):
  244. """
  245. Determine the outer bin edges to use, from either the data or the range
  246. argument
  247. """
  248. if range is not None:
  249. first_edge, last_edge = range
  250. if first_edge > last_edge:
  251. raise ValueError(
  252. 'max must be larger than min in range parameter.')
  253. if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
  254. raise ValueError(
  255. "supplied range of [{}, {}] is not finite".format(first_edge, last_edge))
  256. elif a.size == 0:
  257. # handle empty arrays. Can't determine range, so use 0-1.
  258. first_edge, last_edge = 0, 1
  259. else:
  260. first_edge, last_edge = a.min(), a.max()
  261. if not (np.isfinite(first_edge) and np.isfinite(last_edge)):
  262. raise ValueError(
  263. "autodetected range of [{}, {}] is not finite".format(first_edge, last_edge))
  264. # expand empty range to avoid divide by zero
  265. if first_edge == last_edge:
  266. first_edge = first_edge - 0.5
  267. last_edge = last_edge + 0.5
  268. return first_edge, last_edge
  269. def _unsigned_subtract(a, b):
  270. """
  271. Subtract two values where a >= b, and produce an unsigned result
  272. This is needed when finding the difference between the upper and lower
  273. bound of an int16 histogram
  274. """
  275. # coerce to a single type
  276. signed_to_unsigned = {
  277. np.byte: np.ubyte,
  278. np.short: np.ushort,
  279. np.intc: np.uintc,
  280. np.int_: np.uint,
  281. np.longlong: np.ulonglong
  282. }
  283. dt = np.result_type(a, b)
  284. try:
  285. dt = signed_to_unsigned[dt.type]
  286. except KeyError:
  287. return np.subtract(a, b, dtype=dt)
  288. else:
  289. # we know the inputs are integers, and we are deliberately casting
  290. # signed to unsigned
  291. return np.subtract(a, b, casting='unsafe', dtype=dt)
  292. def _get_bin_edges(a, bins, range, weights):
  293. """
  294. Computes the bins used internally by `histogram`.
  295. Parameters
  296. ==========
  297. a : ndarray
  298. Ravelled data array
  299. bins, range
  300. Forwarded arguments from `histogram`.
  301. weights : ndarray, optional
  302. Ravelled weights array, or None
  303. Returns
  304. =======
  305. bin_edges : ndarray
  306. Array of bin edges
  307. uniform_bins : (Number, Number, int):
  308. The upper bound, lowerbound, and number of bins, used in the optimized
  309. implementation of `histogram` that works on uniform bins.
  310. """
  311. # parse the overloaded bins argument
  312. n_equal_bins = None
  313. bin_edges = None
  314. if isinstance(bins, basestring):
  315. bin_name = bins
  316. # if `bins` is a string for an automatic method,
  317. # this will replace it with the number of bins calculated
  318. if bin_name not in _hist_bin_selectors:
  319. raise ValueError(
  320. "{!r} is not a valid estimator for `bins`".format(bin_name))
  321. if weights is not None:
  322. raise TypeError("Automated estimation of the number of "
  323. "bins is not supported for weighted data")
  324. first_edge, last_edge = _get_outer_edges(a, range)
  325. # truncate the range if needed
  326. if range is not None:
  327. keep = (a >= first_edge)
  328. keep &= (a <= last_edge)
  329. if not np.logical_and.reduce(keep):
  330. a = a[keep]
  331. if a.size == 0:
  332. n_equal_bins = 1
  333. else:
  334. # Do not call selectors on empty arrays
  335. width = _hist_bin_selectors[bin_name](a, (first_edge, last_edge))
  336. if width:
  337. n_equal_bins = int(np.ceil(_unsigned_subtract(last_edge, first_edge) / width))
  338. else:
  339. # Width can be zero for some estimators, e.g. FD when
  340. # the IQR of the data is zero.
  341. n_equal_bins = 1
  342. elif np.ndim(bins) == 0:
  343. try:
  344. n_equal_bins = operator.index(bins)
  345. except TypeError:
  346. raise TypeError(
  347. '`bins` must be an integer, a string, or an array')
  348. if n_equal_bins < 1:
  349. raise ValueError('`bins` must be positive, when an integer')
  350. first_edge, last_edge = _get_outer_edges(a, range)
  351. elif np.ndim(bins) == 1:
  352. bin_edges = np.asarray(bins)
  353. if np.any(bin_edges[:-1] > bin_edges[1:]):
  354. raise ValueError(
  355. '`bins` must increase monotonically, when an array')
  356. else:
  357. raise ValueError('`bins` must be 1d, when an array')
  358. if n_equal_bins is not None:
  359. # gh-10322 means that type resolution rules are dependent on array
  360. # shapes. To avoid this causing problems, we pick a type now and stick
  361. # with it throughout.
  362. bin_type = np.result_type(first_edge, last_edge, a)
  363. if np.issubdtype(bin_type, np.integer):
  364. bin_type = np.result_type(bin_type, float)
  365. # bin edges must be computed
  366. bin_edges = np.linspace(
  367. first_edge, last_edge, n_equal_bins + 1,
  368. endpoint=True, dtype=bin_type)
  369. return bin_edges, (first_edge, last_edge, n_equal_bins)
  370. else:
  371. return bin_edges, None
  372. def _search_sorted_inclusive(a, v):
  373. """
  374. Like `searchsorted`, but where the last item in `v` is placed on the right.
  375. In the context of a histogram, this makes the last bin edge inclusive
  376. """
  377. return np.concatenate((
  378. a.searchsorted(v[:-1], 'left'),
  379. a.searchsorted(v[-1:], 'right')
  380. ))
  381. def _histogram_bin_edges_dispatcher(a, bins=None, range=None, weights=None):
  382. return (a, bins, weights)
  383. @array_function_dispatch(_histogram_bin_edges_dispatcher)
  384. def histogram_bin_edges(a, bins=10, range=None, weights=None):
  385. r"""
  386. Function to calculate only the edges of the bins used by the `histogram` function.
  387. Parameters
  388. ----------
  389. a : array_like
  390. Input data. The histogram is computed over the flattened array.
  391. bins : int or sequence of scalars or str, optional
  392. If `bins` is an int, it defines the number of equal-width
  393. bins in the given range (10, by default). If `bins` is a
  394. sequence, it defines the bin edges, including the rightmost
  395. edge, allowing for non-uniform bin widths.
  396. If `bins` is a string from the list below, `histogram_bin_edges` will use
  397. the method chosen to calculate the optimal bin width and
  398. consequently the number of bins (see `Notes` for more detail on
  399. the estimators) from the data that falls within the requested
  400. range. While the bin width will be optimal for the actual data
  401. in the range, the number of bins will be computed to fill the
  402. entire range, including the empty portions. For visualisation,
  403. using the 'auto' option is suggested. Weighted data is not
  404. supported for automated bin size selection.
  405. 'auto'
  406. Maximum of the 'sturges' and 'fd' estimators. Provides good
  407. all around performance.
  408. 'fd' (Freedman Diaconis Estimator)
  409. Robust (resilient to outliers) estimator that takes into
  410. account data variability and data size.
  411. 'doane'
  412. An improved version of Sturges' estimator that works better
  413. with non-normal datasets.
  414. 'scott'
  415. Less robust estimator that that takes into account data
  416. variability and data size.
  417. 'stone'
  418. Estimator based on leave-one-out cross-validation estimate of
  419. the integrated squared error. Can be regarded as a generalization
  420. of Scott's rule.
  421. 'rice'
  422. Estimator does not take variability into account, only data
  423. size. Commonly overestimates number of bins required.
  424. 'sturges'
  425. R's default method, only accounts for data size. Only
  426. optimal for gaussian data and underestimates number of bins
  427. for large non-gaussian datasets.
  428. 'sqrt'
  429. Square root (of data size) estimator, used by Excel and
  430. other programs for its speed and simplicity.
  431. range : (float, float), optional
  432. The lower and upper range of the bins. If not provided, range
  433. is simply ``(a.min(), a.max())``. Values outside the range are
  434. ignored. The first element of the range must be less than or
  435. equal to the second. `range` affects the automatic bin
  436. computation as well. While bin width is computed to be optimal
  437. based on the actual data within `range`, the bin count will fill
  438. the entire range including portions containing no data.
  439. weights : array_like, optional
  440. An array of weights, of the same shape as `a`. Each value in
  441. `a` only contributes its associated weight towards the bin count
  442. (instead of 1). This is currently not used by any of the bin estimators,
  443. but may be in the future.
  444. Returns
  445. -------
  446. bin_edges : array of dtype float
  447. The edges to pass into `histogram`
  448. See Also
  449. --------
  450. histogram
  451. Notes
  452. -----
  453. The methods to estimate the optimal number of bins are well founded
  454. in literature, and are inspired by the choices R provides for
  455. histogram visualisation. Note that having the number of bins
  456. proportional to :math:`n^{1/3}` is asymptotically optimal, which is
  457. why it appears in most estimators. These are simply plug-in methods
  458. that give good starting points for number of bins. In the equations
  459. below, :math:`h` is the binwidth and :math:`n_h` is the number of
  460. bins. All estimators that compute bin counts are recast to bin width
  461. using the `ptp` of the data. The final bin count is obtained from
  462. ``np.round(np.ceil(range / h))``.
  463. 'Auto' (maximum of the 'Sturges' and 'FD' estimators)
  464. A compromise to get a good value. For small datasets the Sturges
  465. value will usually be chosen, while larger datasets will usually
  466. default to FD. Avoids the overly conservative behaviour of FD
  467. and Sturges for small and large datasets respectively.
  468. Switchover point is usually :math:`a.size \approx 1000`.
  469. 'FD' (Freedman Diaconis Estimator)
  470. .. math:: h = 2 \frac{IQR}{n^{1/3}}
  471. The binwidth is proportional to the interquartile range (IQR)
  472. and inversely proportional to cube root of a.size. Can be too
  473. conservative for small datasets, but is quite good for large
  474. datasets. The IQR is very robust to outliers.
  475. 'Scott'
  476. .. math:: h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}}
  477. The binwidth is proportional to the standard deviation of the
  478. data and inversely proportional to cube root of ``x.size``. Can
  479. be too conservative for small datasets, but is quite good for
  480. large datasets. The standard deviation is not very robust to
  481. outliers. Values are very similar to the Freedman-Diaconis
  482. estimator in the absence of outliers.
  483. 'Rice'
  484. .. math:: n_h = 2n^{1/3}
  485. The number of bins is only proportional to cube root of
  486. ``a.size``. It tends to overestimate the number of bins and it
  487. does not take into account data variability.
  488. 'Sturges'
  489. .. math:: n_h = \log _{2}n+1
  490. The number of bins is the base 2 log of ``a.size``. This
  491. estimator assumes normality of data and is too conservative for
  492. larger, non-normal datasets. This is the default method in R's
  493. ``hist`` method.
  494. 'Doane'
  495. .. math:: n_h = 1 + \log_{2}(n) +
  496. \log_{2}(1 + \frac{|g_1|}{\sigma_{g_1}})
  497. g_1 = mean[(\frac{x - \mu}{\sigma})^3]
  498. \sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}
  499. An improved version of Sturges' formula that produces better
  500. estimates for non-normal datasets. This estimator attempts to
  501. account for the skew of the data.
  502. 'Sqrt'
  503. .. math:: n_h = \sqrt n
  504. The simplest and fastest estimator. Only takes into account the
  505. data size.
  506. Examples
  507. --------
  508. >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
  509. >>> np.histogram_bin_edges(arr, bins='auto', range=(0, 1))
  510. array([0. , 0.25, 0.5 , 0.75, 1. ])
  511. >>> np.histogram_bin_edges(arr, bins=2)
  512. array([0. , 2.5, 5. ])
  513. For consistency with histogram, an array of pre-computed bins is
  514. passed through unmodified:
  515. >>> np.histogram_bin_edges(arr, [1, 2])
  516. array([1, 2])
  517. This function allows one set of bins to be computed, and reused across
  518. multiple histograms:
  519. >>> shared_bins = np.histogram_bin_edges(arr, bins='auto')
  520. >>> shared_bins
  521. array([0., 1., 2., 3., 4., 5.])
  522. >>> group_id = np.array([0, 1, 1, 0, 1, 1, 0, 1, 1])
  523. >>> hist_0, _ = np.histogram(arr[group_id == 0], bins=shared_bins)
  524. >>> hist_1, _ = np.histogram(arr[group_id == 1], bins=shared_bins)
  525. >>> hist_0; hist_1
  526. array([1, 1, 0, 1, 0])
  527. array([2, 0, 1, 1, 2])
  528. Which gives more easily comparable results than using separate bins for
  529. each histogram:
  530. >>> hist_0, bins_0 = np.histogram(arr[group_id == 0], bins='auto')
  531. >>> hist_1, bins_1 = np.histogram(arr[group_id == 1], bins='auto')
  532. >>> hist_0; hist1
  533. array([1, 1, 1])
  534. array([2, 1, 1, 2])
  535. >>> bins_0; bins_1
  536. array([0., 1., 2., 3.])
  537. array([0. , 1.25, 2.5 , 3.75, 5. ])
  538. """
  539. a, weights = _ravel_and_check_weights(a, weights)
  540. bin_edges, _ = _get_bin_edges(a, bins, range, weights)
  541. return bin_edges
  542. def _histogram_dispatcher(
  543. a, bins=None, range=None, normed=None, weights=None, density=None):
  544. return (a, bins, weights)
  545. @array_function_dispatch(_histogram_dispatcher)
  546. def histogram(a, bins=10, range=None, normed=None, weights=None,
  547. density=None):
  548. r"""
  549. Compute the histogram of a set of data.
  550. Parameters
  551. ----------
  552. a : array_like
  553. Input data. The histogram is computed over the flattened array.
  554. bins : int or sequence of scalars or str, optional
  555. If `bins` is an int, it defines the number of equal-width
  556. bins in the given range (10, by default). If `bins` is a
  557. sequence, it defines a monotonically increasing array of bin edges,
  558. including the rightmost edge, allowing for non-uniform bin widths.
  559. .. versionadded:: 1.11.0
  560. If `bins` is a string, it defines the method used to calculate the
  561. optimal bin width, as defined by `histogram_bin_edges`.
  562. range : (float, float), optional
  563. The lower and upper range of the bins. If not provided, range
  564. is simply ``(a.min(), a.max())``. Values outside the range are
  565. ignored. The first element of the range must be less than or
  566. equal to the second. `range` affects the automatic bin
  567. computation as well. While bin width is computed to be optimal
  568. based on the actual data within `range`, the bin count will fill
  569. the entire range including portions containing no data.
  570. normed : bool, optional
  571. .. deprecated:: 1.6.0
  572. This is equivalent to the `density` argument, but produces incorrect
  573. results for unequal bin widths. It should not be used.
  574. .. versionchanged:: 1.15.0
  575. DeprecationWarnings are actually emitted.
  576. weights : array_like, optional
  577. An array of weights, of the same shape as `a`. Each value in
  578. `a` only contributes its associated weight towards the bin count
  579. (instead of 1). If `density` is True, the weights are
  580. normalized, so that the integral of the density over the range
  581. remains 1.
  582. density : bool, optional
  583. If ``False``, the result will contain the number of samples in
  584. each bin. If ``True``, the result is the value of the
  585. probability *density* function at the bin, normalized such that
  586. the *integral* over the range is 1. Note that the sum of the
  587. histogram values will not be equal to 1 unless bins of unity
  588. width are chosen; it is not a probability *mass* function.
  589. Overrides the ``normed`` keyword if given.
  590. Returns
  591. -------
  592. hist : array
  593. The values of the histogram. See `density` and `weights` for a
  594. description of the possible semantics.
  595. bin_edges : array of dtype float
  596. Return the bin edges ``(length(hist)+1)``.
  597. See Also
  598. --------
  599. histogramdd, bincount, searchsorted, digitize, histogram_bin_edges
  600. Notes
  601. -----
  602. All but the last (righthand-most) bin is half-open. In other words,
  603. if `bins` is::
  604. [1, 2, 3, 4]
  605. then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
  606. the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
  607. *includes* 4.
  608. Examples
  609. --------
  610. >>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
  611. (array([0, 2, 1]), array([0, 1, 2, 3]))
  612. >>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
  613. (array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
  614. >>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
  615. (array([1, 4, 1]), array([0, 1, 2, 3]))
  616. >>> a = np.arange(5)
  617. >>> hist, bin_edges = np.histogram(a, density=True)
  618. >>> hist
  619. array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
  620. >>> hist.sum()
  621. 2.4999999999999996
  622. >>> np.sum(hist * np.diff(bin_edges))
  623. 1.0
  624. .. versionadded:: 1.11.0
  625. Automated Bin Selection Methods example, using 2 peak random data
  626. with 2000 points:
  627. >>> import matplotlib.pyplot as plt
  628. >>> rng = np.random.RandomState(10) # deterministic random data
  629. >>> a = np.hstack((rng.normal(size=1000),
  630. ... rng.normal(loc=5, scale=2, size=1000)))
  631. >>> plt.hist(a, bins='auto') # arguments are passed to np.histogram
  632. >>> plt.title("Histogram with 'auto' bins")
  633. >>> plt.show()
  634. """
  635. a, weights = _ravel_and_check_weights(a, weights)
  636. bin_edges, uniform_bins = _get_bin_edges(a, bins, range, weights)
  637. # Histogram is an integer or a float array depending on the weights.
  638. if weights is None:
  639. ntype = np.dtype(np.intp)
  640. else:
  641. ntype = weights.dtype
  642. # We set a block size, as this allows us to iterate over chunks when
  643. # computing histograms, to minimize memory usage.
  644. BLOCK = 65536
  645. # The fast path uses bincount, but that only works for certain types
  646. # of weight
  647. simple_weights = (
  648. weights is None or
  649. np.can_cast(weights.dtype, np.double) or
  650. np.can_cast(weights.dtype, complex)
  651. )
  652. if uniform_bins is not None and simple_weights:
  653. # Fast algorithm for equal bins
  654. # We now convert values of a to bin indices, under the assumption of
  655. # equal bin widths (which is valid here).
  656. first_edge, last_edge, n_equal_bins = uniform_bins
  657. # Initialize empty histogram
  658. n = np.zeros(n_equal_bins, ntype)
  659. # Pre-compute histogram scaling factor
  660. norm = n_equal_bins / _unsigned_subtract(last_edge, first_edge)
  661. # We iterate over blocks here for two reasons: the first is that for
  662. # large arrays, it is actually faster (for example for a 10^8 array it
  663. # is 2x as fast) and it results in a memory footprint 3x lower in the
  664. # limit of large arrays.
  665. for i in _range(0, len(a), BLOCK):
  666. tmp_a = a[i:i+BLOCK]
  667. if weights is None:
  668. tmp_w = None
  669. else:
  670. tmp_w = weights[i:i + BLOCK]
  671. # Only include values in the right range
  672. keep = (tmp_a >= first_edge)
  673. keep &= (tmp_a <= last_edge)
  674. if not np.logical_and.reduce(keep):
  675. tmp_a = tmp_a[keep]
  676. if tmp_w is not None:
  677. tmp_w = tmp_w[keep]
  678. # This cast ensures no type promotions occur below, which gh-10322
  679. # make unpredictable. Getting it wrong leads to precision errors
  680. # like gh-8123.
  681. tmp_a = tmp_a.astype(bin_edges.dtype, copy=False)
  682. # Compute the bin indices, and for values that lie exactly on
  683. # last_edge we need to subtract one
  684. f_indices = _unsigned_subtract(tmp_a, first_edge) * norm
  685. indices = f_indices.astype(np.intp)
  686. indices[indices == n_equal_bins] -= 1
  687. # The index computation is not guaranteed to give exactly
  688. # consistent results within ~1 ULP of the bin edges.
  689. decrement = tmp_a < bin_edges[indices]
  690. indices[decrement] -= 1
  691. # The last bin includes the right edge. The other bins do not.
  692. increment = ((tmp_a >= bin_edges[indices + 1])
  693. & (indices != n_equal_bins - 1))
  694. indices[increment] += 1
  695. # We now compute the histogram using bincount
  696. if ntype.kind == 'c':
  697. n.real += np.bincount(indices, weights=tmp_w.real,
  698. minlength=n_equal_bins)
  699. n.imag += np.bincount(indices, weights=tmp_w.imag,
  700. minlength=n_equal_bins)
  701. else:
  702. n += np.bincount(indices, weights=tmp_w,
  703. minlength=n_equal_bins).astype(ntype)
  704. else:
  705. # Compute via cumulative histogram
  706. cum_n = np.zeros(bin_edges.shape, ntype)
  707. if weights is None:
  708. for i in _range(0, len(a), BLOCK):
  709. sa = np.sort(a[i:i+BLOCK])
  710. cum_n += _search_sorted_inclusive(sa, bin_edges)
  711. else:
  712. zero = np.zeros(1, dtype=ntype)
  713. for i in _range(0, len(a), BLOCK):
  714. tmp_a = a[i:i+BLOCK]
  715. tmp_w = weights[i:i+BLOCK]
  716. sorting_index = np.argsort(tmp_a)
  717. sa = tmp_a[sorting_index]
  718. sw = tmp_w[sorting_index]
  719. cw = np.concatenate((zero, sw.cumsum()))
  720. bin_index = _search_sorted_inclusive(sa, bin_edges)
  721. cum_n += cw[bin_index]
  722. n = np.diff(cum_n)
  723. # density overrides the normed keyword
  724. if density is not None:
  725. if normed is not None:
  726. # 2018-06-13, numpy 1.15.0 (this was not noisily deprecated in 1.6)
  727. warnings.warn(
  728. "The normed argument is ignored when density is provided. "
  729. "In future passing both will result in an error.",
  730. DeprecationWarning, stacklevel=2)
  731. normed = None
  732. if density:
  733. db = np.array(np.diff(bin_edges), float)
  734. return n/db/n.sum(), bin_edges
  735. elif normed:
  736. # 2018-06-13, numpy 1.15.0 (this was not noisily deprecated in 1.6)
  737. warnings.warn(
  738. "Passing `normed=True` on non-uniform bins has always been "
  739. "broken, and computes neither the probability density "
  740. "function nor the probability mass function. "
  741. "The result is only correct if the bins are uniform, when "
  742. "density=True will produce the same result anyway. "
  743. "The argument will be removed in a future version of "
  744. "numpy.",
  745. np.VisibleDeprecationWarning, stacklevel=2)
  746. # this normalization is incorrect, but
  747. db = np.array(np.diff(bin_edges), float)
  748. return n/(n*db).sum(), bin_edges
  749. else:
  750. if normed is not None:
  751. # 2018-06-13, numpy 1.15.0 (this was not noisily deprecated in 1.6)
  752. warnings.warn(
  753. "Passing normed=False is deprecated, and has no effect. "
  754. "Consider passing the density argument instead.",
  755. DeprecationWarning, stacklevel=2)
  756. return n, bin_edges
  757. def _histogramdd_dispatcher(sample, bins=None, range=None, normed=None,
  758. weights=None, density=None):
  759. if hasattr(sample, 'shape'): # same condition as used in histogramdd
  760. yield sample
  761. else:
  762. for s in sample:
  763. yield s
  764. try:
  765. for b in bins:
  766. yield b
  767. except TypeError:
  768. pass
  769. yield weights
  770. @array_function_dispatch(_histogramdd_dispatcher)
  771. def histogramdd(sample, bins=10, range=None, normed=None, weights=None,
  772. density=None):
  773. """
  774. Compute the multidimensional histogram of some data.
  775. Parameters
  776. ----------
  777. sample : (N, D) array, or (D, N) array_like
  778. The data to be histogrammed.
  779. Note the unusual interpretation of sample when an array_like:
  780. * When an array, each row is a coordinate in a D-dimensional space -
  781. such as ``histogramgramdd(np.array([p1, p2, p3]))``.
  782. * When an array_like, each element is the list of values for single
  783. coordinate - such as ``histogramgramdd((X, Y, Z))``.
  784. The first form should be preferred.
  785. bins : sequence or int, optional
  786. The bin specification:
  787. * A sequence of arrays describing the monotonically increasing bin
  788. edges along each dimension.
  789. * The number of bins for each dimension (nx, ny, ... =bins)
  790. * The number of bins for all dimensions (nx=ny=...=bins).
  791. range : sequence, optional
  792. A sequence of length D, each an optional (lower, upper) tuple giving
  793. the outer bin edges to be used if the edges are not given explicitly in
  794. `bins`.
  795. An entry of None in the sequence results in the minimum and maximum
  796. values being used for the corresponding dimension.
  797. The default, None, is equivalent to passing a tuple of D None values.
  798. density : bool, optional
  799. If False, the default, returns the number of samples in each bin.
  800. If True, returns the probability *density* function at the bin,
  801. ``bin_count / sample_count / bin_volume``.
  802. normed : bool, optional
  803. An alias for the density argument that behaves identically. To avoid
  804. confusion with the broken normed argument to `histogram`, `density`
  805. should be preferred.
  806. weights : (N,) array_like, optional
  807. An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`.
  808. Weights are normalized to 1 if normed is True. If normed is False,
  809. the values of the returned histogram are equal to the sum of the
  810. weights belonging to the samples falling into each bin.
  811. Returns
  812. -------
  813. H : ndarray
  814. The multidimensional histogram of sample x. See normed and weights
  815. for the different possible semantics.
  816. edges : list
  817. A list of D arrays describing the bin edges for each dimension.
  818. See Also
  819. --------
  820. histogram: 1-D histogram
  821. histogram2d: 2-D histogram
  822. Examples
  823. --------
  824. >>> r = np.random.randn(100,3)
  825. >>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
  826. >>> H.shape, edges[0].size, edges[1].size, edges[2].size
  827. ((5, 8, 4), 6, 9, 5)
  828. """
  829. try:
  830. # Sample is an ND-array.
  831. N, D = sample.shape
  832. except (AttributeError, ValueError):
  833. # Sample is a sequence of 1D arrays.
  834. sample = np.atleast_2d(sample).T
  835. N, D = sample.shape
  836. nbin = np.empty(D, int)
  837. edges = D*[None]
  838. dedges = D*[None]
  839. if weights is not None:
  840. weights = np.asarray(weights)
  841. try:
  842. M = len(bins)
  843. if M != D:
  844. raise ValueError(
  845. 'The dimension of bins must be equal to the dimension of the '
  846. ' sample x.')
  847. except TypeError:
  848. # bins is an integer
  849. bins = D*[bins]
  850. # normalize the range argument
  851. if range is None:
  852. range = (None,) * D
  853. elif len(range) != D:
  854. raise ValueError('range argument must have one entry per dimension')
  855. # Create edge arrays
  856. for i in _range(D):
  857. if np.ndim(bins[i]) == 0:
  858. if bins[i] < 1:
  859. raise ValueError(
  860. '`bins[{}]` must be positive, when an integer'.format(i))
  861. smin, smax = _get_outer_edges(sample[:,i], range[i])
  862. edges[i] = np.linspace(smin, smax, bins[i] + 1)
  863. elif np.ndim(bins[i]) == 1:
  864. edges[i] = np.asarray(bins[i])
  865. if np.any(edges[i][:-1] > edges[i][1:]):
  866. raise ValueError(
  867. '`bins[{}]` must be monotonically increasing, when an array'
  868. .format(i))
  869. else:
  870. raise ValueError(
  871. '`bins[{}]` must be a scalar or 1d array'.format(i))
  872. nbin[i] = len(edges[i]) + 1 # includes an outlier on each end
  873. dedges[i] = np.diff(edges[i])
  874. # Compute the bin number each sample falls into.
  875. Ncount = tuple(
  876. # avoid np.digitize to work around gh-11022
  877. np.searchsorted(edges[i], sample[:, i], side='right')
  878. for i in _range(D)
  879. )
  880. # Using digitize, values that fall on an edge are put in the right bin.
  881. # For the rightmost bin, we want values equal to the right edge to be
  882. # counted in the last bin, and not as an outlier.
  883. for i in _range(D):
  884. # Find which points are on the rightmost edge.
  885. on_edge = (sample[:, i] == edges[i][-1])
  886. # Shift these points one bin to the left.
  887. Ncount[i][on_edge] -= 1
  888. # Compute the sample indices in the flattened histogram matrix.
  889. # This raises an error if the array is too large.
  890. xy = np.ravel_multi_index(Ncount, nbin)
  891. # Compute the number of repetitions in xy and assign it to the
  892. # flattened histmat.
  893. hist = np.bincount(xy, weights, minlength=nbin.prod())
  894. # Shape into a proper matrix
  895. hist = hist.reshape(nbin)
  896. # This preserves the (bad) behavior observed in gh-7845, for now.
  897. hist = hist.astype(float, casting='safe')
  898. # Remove outliers (indices 0 and -1 for each dimension).
  899. core = D*(slice(1, -1),)
  900. hist = hist[core]
  901. # handle the aliasing normed argument
  902. if normed is None:
  903. if density is None:
  904. density = False
  905. elif density is None:
  906. # an explicit normed argument was passed, alias it to the new name
  907. density = normed
  908. else:
  909. raise TypeError("Cannot specify both 'normed' and 'density'")
  910. if density:
  911. # calculate the probability density function
  912. s = hist.sum()
  913. for i in _range(D):
  914. shape = np.ones(D, int)
  915. shape[i] = nbin[i] - 2
  916. hist = hist / dedges[i].reshape(shape)
  917. hist /= s
  918. if (hist.shape != nbin - 2).any():
  919. raise RuntimeError(
  920. "Internal Shape Error")
  921. return hist, edges