【问题标题】:"Too many values to unpack" in numpy histogram2dnumpy histogram2d 中的“要解压的值太多”
【发布时间】:2013-10-03 20:51:09
【问题描述】:

我正在使用 numpy histogram2d 来计算两个变量的二维直方图的视觉表示值:

H, xedges, yedges = np.histogram2d(Z[:,0], Z[:,1], bins=100)

其中 Z 是一个 numpy 矩阵

我得到的错误是:

Traceback (most recent call last):
File "/home/.../pca_analysis.py", line 141, in <module>
   H, xedges, yedges = np.histogram2d(Z[:,0], Z[:,1], bins=100)
File "/usr/lib/python2.7/dist-packages/numpy/lib/twodim_base.py", line 615, in histogram2d
   hist, edges = histogramdd([x,y], bins, range, normed, weights)
File "/usr/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 281, in histogramdd
   N, D = sample.shape
ValueError: too many values to unpack

我真的不明白为什么我会收到这个错误。我尝试使用带有随机值的 histogram2d 函数,它工作正常。我也尝试在 numpy 数组和简单列表中转换 Z[:,0] 和 Z[:,1],但我遇到了同样的问题。

【问题讨论】:

  • Z是矩阵,做成数组
  • @seberg,我已经尝试过做 np.array(Z[...]),但我得到了同样的错误
  • 有吗? np.asarray(Z)[:,0]...
  • 成功了,非常感谢。我做错了
  • @seberg 请将此作为答案发布。

标签: python numpy histogram histogram2d


【解决方案1】:

正如@seberg 在 cmets 中指出的那样,Z 是一个矩阵,因此在切片之前必须将其转换为数组。

np.asarray(Z)[:,0]

之所以需要这样做是因为np.matrix即使在切片后仍保持其二维性,因此矩阵的列具有(N,1)的形状,而不是直方图函数所期望的(N,)

切片后不能转换成数组的原因是形状没有通过转换改变;切片的行为是不同的。

如果这没有意义,这里有一个插图:

In [4]: a = np.arange(9).reshape(3,3)

In [5]: a
Out[5]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [6]: m = np.matrix(a)

In [7]: m
Out[7]: 
matrix([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])

In [8]: m[:,0]
Out[8]: 
matrix([[0],
        [3],
        [6]])

In [9]: a[:,0]
Out[9]: array([0, 3, 6])

In [10]: m[:,0].shape
Out[10]: (3, 1)

In [11]: a[:,0].shape
Out[11]: (3,)

如果切片后施法,形状还是2d:

In [12]: np.array(m[:,0])
Out[12]: 
array([[0],
       [3],
       [6]])

In [13]: np.array(m[:,0]).shape
Out[13]: (3, 1)

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多