【问题标题】:how the left side of the code assign values to counts and bin_edges ?? can anyone please explain this code briefly代码的左侧如何为计数和 bin_edges 赋值?谁能简要解释一下这段代码
【发布时间】:2020-12-31 12:03:18
【问题描述】:

我想知道 np.histogram 一次分配 count 和 bin_edges 值的方式。

counts,bin_edges=np.histogram(iris_setosa['sepal_length'],bins=10,density=True)

【问题讨论】:

  • 您的问题是关于np.histogram 的工作原理,还是关于将其输出分配给两个变量的问题?分配只是 Python 'unpacking' 的一个例子。
  • 两个都可以回答吗

标签: python numpy matplotlib machine-learning


【解决方案1】:

假设data 是一维numpy 数组,bins 是严格正整数,代码大致如下:

import numpy as np

def numpy_histogram(data, bins=10, density=False):
    xmin = data.min()
    xmax = data.max()
    bin_edges = np.linspace(xmin, xmax, bins + 1)
    counts = np.zeros(bins, dtype=int)
    bin_indices = ((data - xmin) / (xmax - xmin) * bins * 0.999999).astype(int)
    for i in bin_indices:
        counts[i] += 1
    if density:
        counts = counts / sum(counts) / (bin_edges[1] - bin_edges[0])
    return counts, bin_edges

counts, bin_edges = numpy_histogram(np.random.uniform(1, 10, 20), density=True)
print(sum(counts), counts)

因此,数据的最小值和最大值用于定义 bin 边界。 (边界比垃圾箱多一个)。然后从每个数据值中减去xmin,然后除以数据的总范围。然后乘以箱数。这标识了该值应该去的 bin 的索引。需要通过一个略小于 1 的因子进行校正,以便最右边的值不会落入以下(未定义的)bin。

density=True 时,计数被归一化,使得所有条形的面积之和为1。条形的宽度为两个连续的bin_edges 之间的差异。

PS:关于Python同时赋值多个元素,this question很有意思。

【讨论】:

  • 非常感谢
猜你喜欢
  • 2017-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 2021-11-20
相关资源
最近更新 更多