[英]Figuring out broadcasting shape in numpy
我了解numpy
(Pandas)廣播的基礎知識,但被這個簡單的示例所困擾:
x = np.arange(5)
y = np.random.uniform(size = (2,5))
z = x*y
print(z.shape) #(2,5)
我對z形狀的理解是,您有一個(1,5)
數組乘以(2,5)
數組,5的尾隨尺寸相等,因此最終得到2x5
數組。 好吧,聽起來不錯。 我的問題是為什么x.shape = (5,)
? 它不是一維的,所以實際上是1x5
嗎?
像x
一樣的NumPy
1D數組可以使您獲得(5,)
這樣的形狀(5,)
而無需重塑形狀。 如果你想要把它當作形狀的1列矩陣1x5
然后做np.arange(5).reshape(1,5)
廣播規則是:
Add leading singleton dimensions as needed to match number of dimensions
Scale any singleton dimensions to match dimension values
Raise error dimensions can't be matched
用你的x
和y
:
(5,) * (2,5)
(1,5) * (2,5) # add the leading 1
(2,5) * (2,5) # scale the 1
=> (2,5)
如果y
為(5,2),則將引發錯誤,因為(1,5)
無法與(5,2)
配對。 但是(5,1)
可以,因為(1,5) * (5,1) => (5,5)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.