histograms.py 38 KB

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