问题描述
两个形状为-的数组之间有什么区别?
What is the difference between 2 arrays whose shapes are-
(442,1)和(442,)?
同时打印这两个命令会产生相同的输出,但是当我检查相等性 == 时,会得到一个像这样的2D矢量-
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. Sowhen 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!