numpy中这些数组形状之间的区别 [英] Difference between these array shapes in numpy
问题描述
形状为-的2个数组有什么区别
What is the difference between 2 arrays whose shapes are-
(442,1) 和 (442,) ?
打印这两个会产生相同的输出,但是当我检查相等==时,我得到一个像这样的二维向量-
Printing both of these produces an identical output, but when I check for equality ==, I get a 2D vector like this-
array([[ True, False, False, ..., False, False, False],
[False, True, False, ..., False, False, False],
[False, False, True, ..., False, False, False],
...,
[False, False, False, ..., True, False, False],
[False, False, False, ..., False, True, False],
[False, False, False, ..., False, False, True]], dtype=bool)
有人能解释一下区别吗?
Can someone explain the difference?
推荐答案
(442, 1)
形状的数组是二维的.它有 442 行和 1 列.
An array of shape (442, 1)
is 2-dimensional. It has 442 rows and 1 column.
形状为 (442, )
的数组是一维的,由 442 个元素组成.
An array of shape (442, )
is 1-dimensional and consists of 442 elements.
请注意,他们的代表也应该看起来不同.括号的数量和位置有区别:
Note that their reprs should look different too. There is a difference in the number and placement of parenthesis:
In [7]: np.array([1,2,3]).shape
Out[7]: (3,)
In [8]: np.array([[1],[2],[3]]).shape
Out[8]: (3, 1)
<小时>
请注意,您可以使用 np.squeeze
删除长度为 1 的轴:
Note that you could use np.squeeze
to remove axes of length 1:
In [13]: np.squeeze(np.array([[1],[2],[3]])).shape
Out[13]: (3,)
<小时>
NumPy 广播规则 允许自动添加新轴需要时在左侧.所以(442,)
可以广播到(1, 442)
.长度为 1 的轴可以广播到任何长度.所以当您测试形状数组 (442, 1)
和形状数组 (442, )
之间的相等性时,第二个数组被提升为形状 (1, 442)
然后两个数组展开它们长度为 1 的轴,使它们都变成形状为 (442, 442)
的广播数组.这就是为什么当您测试相等性时,结果是一个形状为 (442, 442)
的布尔数组.
NumPy broadcasting rules allow new axes to be automatically added on the left when needed. So (442,)
can broadcast to (1, 442)
. And axes of length 1 can broadcast to any length. So
when you test for equality between an array of shape (442, 1)
and an array of shape (442, )
, the second array gets promoted to shape (1, 442)
and then the two arrays expand their axes of length 1 so that they both become broadcasted arrays of shape (442, 442)
. This is why when you tested for equality the result was a boolean array of shape (442, 442)
.
In [15]: np.array([1,2,3]) == np.array([[1],[2],[3]])
Out[15]:
array([[ True, False, False],
[False, True, False],
[False, False, True]], dtype=bool)
In [16]: np.array([1,2,3]) == np.squeeze(np.array([[1],[2],[3]]))
Out[16]: array([ True, True, True], dtype=bool)
这篇关于numpy中这些数组形状之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!