【问题标题】:Numpy choose: shape-mismatch errorNumpy 选择:形状不匹配错误
【发布时间】:2018-03-27 19:49:07
【问题描述】:

我希望在两对 numpy 数组之间随机播放,例如给定

a = [a1,a2,a3,a4]
a_next = [a2,a3,a4,a5]
b = [b1,b2,b3,b4]
b_next [b2,b3,b4,b5]

我想在 a 和 b 之间洗牌得到

x = [a1,b2,b3,a4]
x_next = [a2,b3,b4,a5]
y = [b1,a2,a3,b4]
y_next = [b2,a3,a4,b5]

我已经设法让这适用于一维 a 和 b,使用:

a = np.array([11,22,33,44])
a_next = np.array([22,33,44,55])
b = np.array([10,20,30,40])
b_next = np.array([20,30,40,50])

choices = [a,b]
choices_next = [a_next,b_next]
alternating_indices = np.random.randint(0, 2, len(a)) # Random 0s or 1s

x = np.choose(alternating_indices, choices)
x_next = np.choose(alternating_indices, choices_next)
y = np.choose(1-alternating_indices, choices)
y_next = np.choose(1-alternating_indices, choices_next)

但我真正的 a 和 b 实际上是 3D 数组(所以 a1、a2、...、b1、b2 的形状为 [width, height]),这会产生错误 ValueError: shape mismatch: objects cannot be broadcast to a single shape。这是一个给出相同错误的玩具示例:

a = np.array([[11,11],[22,22],[33,33],[44,44]])
a_next = np.array([[22,22],[33,33],[44,44],[55,55]])
b = np.array([[10,10],[20,20],[30,30],[40,40]])
b_next = np.array([[20,20],[30,30],[40,40],[50,50]])

那么,我怎样才能使它适用于具有非平凡形状元素的数组?实数数组 a、a_next、b 和 b_next 的形状相同 [M, width, height]

提前致谢!

【问题讨论】:

  • 我想过,但是使用布尔数组我可以在“a or nothing”和“b or nothing”之间进行选择,但我想选择“a or b”。有没有办法使用布尔数组来做到这一点?
  • 你是对的!我也没有考虑过在作业左侧使用布尔索引。谢谢!

标签: python numpy


【解决方案1】:

在第一个轴上使用布尔索引。以下

import numpy as np

a = np.array([[11,11],[22,22],[33,33],[44,44]])
b = np.array([[10,10],[20,20],[30,30],[40,40]])
ind = np.random.randint(0, 2, len(a), dtype=np.bool)

a[ind,...], b[ind,...] = b[ind,...], a[ind,...]

print(a)
print(b)

给予

[[10 10]
 [22 22]
 [33 33]
 [40 40]]
[[11 11]
 [20 20]
 [30 30]
 [44 44]]

对于,在这种情况下,

ind = [ True False False  True]

【讨论】:

    【解决方案2】:

    tl;dr:您可以连接您感兴趣的数组,然后将它们打乱并切片:

    c = np.concatenate((a, b))
    np.random.shuffle(c)
    x, y = c[:N], c[N:]
    

    稍微长一点的解释:

    您可以从数组ab 创建返回数组c = np.array([a1, a2, a3, a4, b1, b2, b3, b4])c = np.concatenate((a, b)),然后使用函数np.random.shuffle(c) 将其随机播放。现在 c 看起来像 c = np.array([a3, b1, a2, b2, a4, a1, b3, b4])。最后,您可以通过将 c 分成两部分来创建数组 x 和 y。假设您要创建的数组 x 的长度为 N x = c[:N] 和 y y = c[N:] 创建数组 x。

    【讨论】:

    • 实际上,在您的代码中,x 和 y 始终包含来自 a 的 2 个元素和来自 b 的 2 个元素。但是,您没有将其作为要求提及。请注意,我提出的解决方案并不能保证这一点。
    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2016-05-13
    • 2019-10-20
    • 2015-11-06
    • 2013-04-01
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多