Python数组大小差异

2024-10-01 17:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

问题是关于Python数组的。在

数组大小(2, )和{}之间有什么区别?在

我试着把这两个数组相加。但是,我得到了如下错误:

Non-broadcastable output operant with shape (2, ) doesn't match the broadcast shape (2, 2)


Tags: theoutputmatch错误with数组broadcastnon
3条回答

原始内存没有区别。但从逻辑上讲,一个是由两个值组成的一维数组,另一个是二维数组(其中一个维度恰好是大小为1)。在

逻辑区别对于numpy很重要;当您尝试添加它们时,它希望创建一个新的2x2数组,其中最上面的一行是(2, 1)数组顶部“row”与{}数组中每个值的和。但是,如果使用+=来执行此操作,则表明您希望能够在适当的位置修改(2,)数组,如果不调整大小,这是不可能的(而numpy不会这样做)。如果您从以下位置更改代码:

arr1 += arr2

收件人:

^{pr2}$

它将愉快地创建一个新的(2, 2)数组。或者,如果目标是2x1数组应该像平面1D数组一样,那么您可以flatten它:

alreadyflatarray += twodarray.flatten()

(2,)是一维数组,(2,1)是只有一列的矩阵

通过使用np.zero传递所需形状,您可以很容易地看到差异:

>>> np.zeros((2,))
array([0., 0.])

>>> np.zeros((2,1))
array([[0.],
       [0.]])

@yx131,您可以查看下面的代码,以清楚地了解元组及其在定义numpy数组的形状时的用法。在

Note: Do not forget to see the code below as it has explanation of the problems related to Broadcasting in numpy.

同时查看纽比的广播规则 https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html。在

There's a difference between (2) and (2,). The first one is a literal value 2 where as the 2nd one is a tuple.

(2,) is 1 item tuple and (2, 2) is 2 items tuple. It is clear in the code example.

Note: In case of numpy arrays, (2,) denotes shape of 1 dimensional array of 2 items and (2, 2) denotes the shape of 2 dimensional array (matrix) with 2 rows and 2 colums. If you want to add 2 arrays then their shape should be same.

v = (2)   # Assignment of value 2
t = (2,)  # Comma is necessary at the end of item to define 1 item tuple, it is not required in case of list
t2 = (2, 1)  # 2 item tuple
t3 = (3, 4)  # 2 item tuple

print(v, type(v))
print(t, type(t))
print(t2, type(t2))
print(t3, type(t3))

print(t + t2)
print(t2 + t3)

"""
2 <class 'int'>
(2,) <class 'tuple'>
(2, 1) <class 'tuple'>
(3, 4) <class 'tuple'>
(2, 2, 1)
(2, 1, 3, 4)
"""

现在,让我们看看下面的代码,找出与广播相关的错误。都和维度有关。在

^{pr2}$

所以在您的例子中,问题与要添加的不匹配维度(根据numpy's broadcasting)有关。谢谢。在

相关问题 更多 >

    热门问题