我使用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,但是我遇到了同样的问题。
发布于 2013-09-27 17:04:27
正如@seberg在注释中所指出的,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)https://stackoverflow.com/questions/19052757
复制相似问题