numpy.histogram()如何工作?

Auf*_*ind 110 python numpy histogram

在阅读numpy时,我遇到了这个功能numpy.histogram().

它是什么,它是如何工作的?在文档中他们提到了垃圾箱:它们是什么?

一些谷歌搜索引导我一般的直方图定义.我明白了.但不幸的是,我无法将这些知识与文档中给出的示例联系起来.

Bru*_*uno 156

bin是表示沿X轴的直方图的单个条的宽度的范围.你也可以称之为间隔.(维基百科将它们更正式地定义为"不相交的类别".)

该numpy的histogram功能不绘制直方图,但它计算输入数据的落入每个仓,其进而确定该区域(不一定如果仓具有相同的宽度不是高度),每个杆的内的发生.

在这个例子中:

 np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
Run Code Online (Sandbox Code Playgroud)

有3个箱,值分别为0到1(不包括1),1到2(不包括2)和2到3(包括3).Numpy定义这些bin的方式是通过[0, 1, 2, 3]在这个例子中给出一个delimiters()列表,虽然它也返回结果中的bin,因为它可以从输入中自动选择它们,如果没有指定的话.如果bins=5,例如,它会使用5桶传播最小输入值和最高输入值之间相等的宽度.

输入值为1,2和1.因此,bin"1到2"包含两次出现(两个1值),bin"2到3"包含一次出现(the 2).这些结果位于返回元组的第一项中:array([0, 2, 1]).

由于此处的箱柜宽度相等,因此您可以使用每个栏的高度出现次数.绘制时,您将拥有:

  • X轴上的范围/ bin [0,1]的高度为0的条形,
  • 范围/箱[1,2]的高度为2的杆,
  • 范围/箱[2,3]的高度为1的栏.

您可以使用Matplotlib直接绘制它(它的hist函数也返回bin和值):

>>> import matplotlib.pyplot as plt
>>> plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]), <a list of 3 Patch objects>)
>>> plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 如果你想绘制它们,你可能也对[这个答案](http://stackoverflow.com/a/5328669/372643)感兴趣.[Matplotlib也可以直接计算它们](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.hist).请参阅示例[此处](http://matplotlib.sourceforge.net/examples/api/histogram_demo.html)和[此处](http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html). (6认同)

unu*_*tbu 62

import numpy as np    
hist, bin_edges = np.histogram([1, 1, 2, 2, 2, 2, 3], bins = range(5))
Run Code Online (Sandbox Code Playgroud)

下面,hist表示bin#0中有0个项目,bin#1中有2个,bin#3中有4个,bin#4中有1个.

print(hist)
# array([0, 2, 4, 1])   
Run Code Online (Sandbox Code Playgroud)

bin_edges 表示bin#0是区间[0,1),bin#1是[1,2],...,bin#3是[3,4].

print (bin_edges)
# array([0, 1, 2, 3, 4]))  
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,更改输入np.histogram并查看其工作原理.


但是一张图片胜过千言万语:

import matplotlib.pyplot as plt
plt.bar(bin_edges[:-1], hist, width = 1)
plt.xlim(min(bin_edges), max(bin_edges))
plt.show()   
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 我认为这会更准确:'plt.bar(bin_edges [: - 1],hist,width = 1)`和`plt.xlim(min(bin_edges),max(bin_edges))`,以使条形适合它们的预期宽度(否则,可能只有一个较小的bin,中间没有值). (3认同)

Grr*_*Grr 8

另一个有用的事情numpy.histogram是将输出绘制为折线图上的 x 和 y 坐标。例如:

arr = np.random.randint(1, 51, 500)
y, x = np.histogram(arr, bins=np.arange(51))
fig, ax = plt.subplots()
ax.plot(x[:-1], y)
fig.show()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

这可能是一种可视化直方图的有用方法,您希望更高级别的粒度没有到处都是条形图。在图像直方图中识别极端像素值非常有用。