_histograms_impl.py 38 KB

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