首页 文章

不成形和重塑一个numpy阵列?

提问于
浏览
2

我有一个56个图像的阵列,每个图像有2个像素通道 . 因此它的形状是(1200,800,52,2) . 我需要做一个KNeighborsClassifier,它需要被展平,以便所有52个图像中的所有像素都在一列中 . 形状(1200 * 800 * 52,2) . 然后在执行分类之后 - 我需要知道我可以按照正确的顺序对它们进行整形 .

作为第一步,我试图只是变形和重塑同一个数组,并尝试使它与原始数组相同 .

这是我尝试过的似乎不起作用的东西:

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()

2 回答

  • 1

    (Y == l) 是一个与 Yl 形状相同的布尔数组 .

    assert expression 在布尔上下文中计算 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 ,或者当任何元素是 True 时, __bool__ 是否应返回 True 并不清楚 .

    您可以通过调用 allany 方法来避免错误,具体取决于您的意图 . 在您的情况下,您希望断言所有值都相等:

    assert (Y == l).all()
    

    由于浮点运算的不精确性,比较浮点数的相等性有时会返回意外的结果,因此比较浮点数组的相等性也可以更安全地完成

    assert np.allclose(Y, l)
    

    请注意,np.allclose接受相对容差和绝对容差参数以应对浮点不精确 .

  • 1

    看起来你的错误在第56行,你使用的 reshape 不遵循 Y 的原始尺寸(最后一个轴是52,但你重塑为2) .

    也许你应该试试

    k = np.reshape(Y,(1200*800*2,52))
    

    因为它似乎更好地反映了“52张扁平图像”的想法 .

相关问题