【发布时间】:2014-11-07 11:38:58
【问题描述】:
我正在尝试使用 numpy.histogramdd 生成两个 2D 直方图(我知道 histogram2d,但我最终需要这个来实现 N 维的可扩展性)
两个直方图应该使用相同的范围,所以我在获取它们之前定义它。
问题是我无法让我的代码工作,我使用不同的配置得到ValueError: too many values to unpack 或ValueError: 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 这是一个更大的代码的一部分,
P和Q都被定义为每个包含两个元素的列表,因为这就是它们被赋予这个函数的方式。我已经阅读了文档并检查了输入数组的形状(zip(*[P[0], P[1]])和Q相同)是(100, 2) (100, 2)。为什么这不正确? -
转换成元组列表对我来说根本不起作用。但是,在调用
histogramdd之前转换为 numpy 数组确实有效。第二件事是,您的范围代码。会不会是您混淆了bins和range参数? -
只需从您的压缩表达式创建一个 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