[英]Difference between these array shapes in numpy
2個陣列的形狀有什么區別 -
(442,1)和(442,) ?
打印這兩個產生相同的輸出,但當我檢查相等==時 ,我得到一個這樣的2D矢量 -
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)
有人可以解釋這個區別嗎?
形狀陣列(442, 1)
是二維的。 它有442行和1列。
形狀陣列(442, )
是1維的並且由442個元素組成。
請注意,他們的代表也應該看起來不同。 括號的數量和位置有所不同:
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的軸:
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)
。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.