我有一个包含 56 个图像的数组,每个图像都有 2 个像素 channel 。因此它的形状是 (1200, 800, 52, 2)。我需要做一个 KNeighborsClassifier,它需要被展平,以便所有 52 个图像中的所有像素都在一列中。所以形状 (1200*800*52,2)。然后在执行分类后 - 我需要知道我可以按照正确的顺序对它们进行整形。
作为第一步,我尝试对同一个数组进行变形和 reshape ,并尝试使其与原始数组相同。
这是我试过的,但似乎不起作用:
In [55]: Y.shape
Out[55]: (1200, 800, 2, 52)
In [56]: k = np.reshape(Y,(1200*800*52,2))
In [57]: k.shape
Out[57]: (49920000, 2)
In [58]: l = np.reshape(k,(1200,800,52,2))
In [59]: l.shape
Out[59]: (1200, 800, 52, 2)
In [60]: assert l == Y
/Users/alex/anaconda2/bin/ipython:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.
#!/bin/bash /Users/alex/anaconda2/bin/python.app
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-60-9faf5e8e20ba> in <module>()
编辑:我在 k 和 Y 的形状上犯了一个错误。这是更正后的版本,但仍然有错误
In [78]: Y.shape
Out[78]: (1200, 800, 2, 52)
In [79]: k = np.reshape(Y,(1200*800*52,2))
In [80]: k.shape
Out[80]: (49920000, 2)
In [81]: l = np.reshape(k,(1200,800,2,52))
In [82]: assert Y == l
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-82-6f6815930213> in <module>()
----> 1 assert Y == l
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
请您参考如下方法:
(Y == l) 是一个与 Y 和 l 形状相同的 bool 数组。
assert expression 在 bool 上下文中计算 expression。换句话说,调用了 expression.__bool__()。
根据设计,ndarray.__bool__ 方法引发
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
因为不清楚当所有元素为True时__bool__是否应该返回True,或者当< em>任何 元素都是True。
您可以通过调用 all 或 any 方法来避免错误,具体取决于您的意图。在您的情况下,您希望断言所有值都相等:
assert (Y == l).all()
由于浮点运算的不精确,比较 float 是否相等有时会返回意想不到的结果,比较 float 组是否相等也可以更安全地完成
assert np.allclose(Y, l)
请注意 np.allclose接受相对公差和绝对公差参数 以应对浮点不精确。
