【问题标题】:Histogram in N dimensions with numpyN维直方图与numpy
【发布时间】:2014-11-07 11:38:58
【问题描述】:

我正在尝试使用 numpy.histogramdd 生成两个 2D 直方图(我知道 histogram2d,但我最终需要这个来实现 N 维的可扩展性)

两个直方图应该使用相同的范围,所以我在获取它们之前定义它。

问题是我无法让我的代码工作,我使用不同的配置得到ValueError: too many values to unpackValueError: sequence too large; must be smaller than 32 错误。

这是 MWE:

import numpy as np

def rand_data(N):
    return np.random.uniform(low=1., high=2000., size=(N,))

# Some random 2D data.
N = 100
P = [rand_data(N), rand_data(N)]
Q = [rand_data(N), rand_data(N)]

# Number of bins.
b = np.sqrt(len(P[0])) * 2

# Max and min values for x and y
x_min = np.sort(np.minimum(P[0], Q[0]))[0]
x_max = np.sort(np.minimum(P[0], Q[0]))[-1]
y_min = np.sort(np.minimum(P[1], Q[1]))[0]
y_max = np.sort(np.minimum(P[1], Q[1]))[-1]
# Range for the histograms.
rang = [np.linspace(x_min, x_max, b), np.linspace(y_min, y_max, b)]

# Histograms
d_1 = np.histogramdd(zip(*[P[0], P[1]]), range=rang)[0]
d_2 = np.histogramdd(zip(*[Q[0], Q[1]]), range=rang)[0]

我做错了什么?

【问题讨论】:

  • 我想知道为什么您首先要为 histogrammdd 输入构建这些元组。这就是文档对输入的看法:It must be an (N,D) array or data that can be converted to such.docs.scipy.org/doc/numpy/reference/generated/…
  • @cel 这是一个更大的代码的一部分,PQ 都被定义为每个包含两个元素的列表,因为这就是它们被赋予这个函数的方式。我已经阅读了文档并检查了输入数组的形状(zip(*[P[0], P[1]])Q 相同)是(100, 2) (100, 2)。为什么这不正确?
  • 转换成元组列表对我来说根本不起作用。但是,在调用 histogramdd 之前转换为 numpy 数组确实有效。第二件事是,您的范围代码。会不会是您混淆了 binsrange 参数?
  • 只需从您的压缩表达式创建一个 numpy 数组:在 python3 中它将是 samples1 = np.array(list(*[P[0], P[1]]))。然后你可以使用hist, edges = histogramdd(samples1)。在我看来,您正在将垃圾箱的边缘传递给 range 参数。如果你想这样做,显然必须将这些边缘传递给bins 参数,正如文档所建议的那样。
  • 应该是samples1 = np.array(list(zip(*[P[0], P[1]])))

标签: python arrays numpy histogram


【解决方案1】:

以下代码应该适合您。有两个问题:垃圾箱的边缘被传递给bins 参数,而不是range 参数。此外,传递元组列表似乎不起作用。如果将这些元组转换为 numpy 数组并传递该数组,它应该可以按预期工作。

此代码适用于我:

import numpy as np

def rand_data(N):
    return np.random.uniform(low=1., high=2000., size=(N,))

# Some random 2D data.
N = 100
P = [rand_data(N), rand_data(N)]
Q = [rand_data(N), rand_data(N)]

# Number of bins.
b = np.sqrt(len(P[0])) * 2

# Max and min values for x and y
x_min = np.sort(np.minimum(P[0], Q[0]))[0]
x_max = np.sort(np.minimum(P[0], Q[0]))[-1]
y_min = np.sort(np.minimum(P[1], Q[1]))[0]
y_max = np.sort(np.minimum(P[1], Q[1]))[-1]
# Range for the histograms.
rang = [np.linspace(x_min, x_max, b), np.linspace(y_min, y_max, b)]

# Histograms
sample1 = np.array(list(zip(*[P[0], P[1]])))
sample2 = np.array(list(zip(*[Q[0], Q[1]])))
d_1 = np.histogramdd(sample1, bins=rang)[0]
d_2 = np.histogramdd(sample2, bins=rang)[0]

【讨论】:

  • 我认为你不需要在zip() 周围使用list()
  • 是的,python2.x 是这样。在 python3.x zip 返回一个生成器对象而不是一个列表。这就是为什么我使用显式转换为list
猜你喜欢
  • 1970-01-01
  • 2021-08-05
  • 2013-09-21
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 2013-07-26
相关资源
最近更新 更多