【问题标题】:Unshape and reshape a numpy array?变形和重塑一个 numpy 数组?
【发布时间】:2016-05-23 00:44:41
【问题描述】:

我有一个包含 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()

【问题讨论】:

  • Y 的形状为(1200, 800, 2, 52),但l 的形状为(1200, 800, 52, 2),两者不相等,因为形状不匹配。
  • 哎呀。我已经更新了问题和代码。发生不同的错误,但重塑似乎仍然不起作用

标签: python numpy


【解决方案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()

因为不清楚__bool__ 是否应该在所有 元素为True 时返回True,或者当任何 元素为True 时返回True

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

assert (Y == l).all()

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

assert np.allclose(Y, l)

注意np.allclose接受相对容差和绝对容差参数 处理浮点不精确。

【讨论】:

  • 这是正确的。对于我的情况,我想添加 Y = np.transpose(Y,(3,0,1,2)) 来制作形状 (52,1200,800,2)。这对我来说更直观,因为 52 例 1200 行 800 列,每列 2 个通道。然后 .any、.all 和 .allclose 都断言很好
【解决方案2】:

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

也许你应该试试

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

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

【讨论】:

  • 我想要扁平化的像素值。 “2”用于 a 和 b 颜色通道。我认为在这种情况下会丢失。
猜你喜欢
  • 1970-01-01
  • 2017-08-15
  • 2011-10-01
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2019-12-05
相关资源
最近更新 更多