在将numpy数组与其他两个numpy数组组成元素时出现广播错误 [英] Broadcasting error when forming numpy array with elements as two other numpy arrays

查看:117
本文介绍了在将numpy数组与其他两个numpy数组组成元素时出现广播错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一个具有与其他两个numpy数组相同的元素的numpy数组,如下所示.

I am trying to generate a numpy array with elements as two other numpy arrays, as below.

W1b1 = np.zeros((256, 161))
W2b2 = np.zeros((256, 257))
Wx = np.array([W1b1, W2b2], dtype=np.object)

这给出了一个错误:

ValueError: could not broadcast input array from shape (256,161) into shape (256).

但是,如果我对W1b1和W2b2采取完全不同的尺寸,那么我不会得到错误,如下所示.

However, if I take entirely different dimensions for of W1b1 and W2b2 then I do not get an error, as below.

A1 = np.zeros((256, 161))
A2 = np.zeros((257, 257))
A3 = np.array([A1, A2], dtype=np.object)

我没有理解第一个代码中的错误,为什么numpy数组试图广播一个输入数组.

I do not get what is wrong in the first code and why is numpy array trying to broadcast one of the input arrays.

我尝试使用以下版本(Python 2.7.6,Numpy 1.13.1)和(Python 3.6.4,Numpy 1.14.1).

I have tried on below versions (Python 2.7.6, Numpy 1.13.1) and (Python 3.6.4, Numpy 1.14.1).

推荐答案

不要指望np.array(..., object)建立正确的对象数组.目前,我们无法控制其制作的尺寸.可以想象它可以制作一个(2,)数组或(2,256)(具有1d内容).有时会起作用,有时会引发错误.有某种模式,但是我还没有看到对代码的分析以显示出正在发生的事情.

Don't count on np.array(..., object) making the right object array. At the moment we don't have control over how many dimensions it makes. Conceivably it could make a (2,) array, or (2, 256) (with 1d contents). Sometimes it works, sometimes raises an error. There's something of a pattern, but I haven't seen an analysis of the code that shows exactly what is happening.

现在,分配数组并填充它更安全:

For now it is safer to allocate the array, and fill it:

In [57]: arr = np.empty(2, object)
In [58]: arr[:] = [W1b1, W2b2]

np.array([np.zeros((3,2)),np.ones((3,4))], object)也会引发此错误.因此,当第一个尺寸匹配但第二个尺寸不匹配时,就会出现错误.现在,我开始思考,我之前已经看到过此错误.

np.array([np.zeros((3,2)),np.ones((3,4))], object) also raises this error. So the error arises when the first dimensions match, but the later ones don't. Now that I think about, I've seen this error before.

有关此主题的早期问题

numpy数组1.9.2出现ValueError:无法将输入数组从形状(4,2)广播到形状(4)

创建数组第一个维度的第一个大小匹配时,数组的数组失败

在numpy中创建具有不同维数的数组的数组

这篇关于在将numpy数组与其他两个numpy数组组成元素时出现广播错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆