我在用核动力广播观察一些奇怪的行为。问题如下所示,其中运行第一段代码会产生错误:

A = np.ones((10))
B = np.ones((10, 4))
C = np.ones((10))
np.asarray([A, B, C])

ValueError: could not broadcast input array from shape (10,4) into shape (10)

如果我改为使用B = np.expand_dims(B, axis=0)扩展b的维度,它将成功创建数组,但它现在(毫不奇怪)有错误的维度:
array([array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
   array([[[1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.]]]),
   array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])], dtype=float32)

为什么它无法广播第一个示例,我如何才能以下面这样的数组结束(注意第二个数组周围只有双括号)非常感谢您的反馈。
array([array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]),
   array([[1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.],
    [1., 1., 1., 1.]]),
   array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])], dtype=object)

最佳答案

包括,比方说,None阻止广播,因此此解决方案是一个选项:

np.asarray([A, B, C, None])[:-1]

结果如下:
array([array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.]),
       array([[ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.],
       [ 1.,  1.,  1.,  1.]]),
       array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])], dtype=object)

关于python - Numpy ValueError将元组列表广播到数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53376823/

10-08 22:17
查看更多