2012-04-17 88 views
0

我是numpy廣播的newby。我定義三個numpy的陣列如下:Python,numpy:3維廣播

from numpy import * 
a=array([10,20]).reshape(2,1) 
b=array([100,200,300]).reshape(1,3) 
c=arange(1,11).reshape(1,1,10) 

a + b爲一個(2,1)與(1,3)之和,因此被認爲是broadcastable(2vs1在昏暗1,1VS3在昏暗2,廣播規則被滿足)。事實上,這是:

>>> a+b 
array([[110, 210, 310], 
     [120, 220, 320]]) 

A + C是一(2,1)與(1,1,10)總和所以它應該是broadcastable(2vs1在昏暗1,1VS1在昏暗2和1vs10在暗淡3,廣播規則被實現)。事實上,這是:

>>> a+c 
array([[[11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 
     [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]]) 

B + C是一(1,3)與(1,1,10)總和所以它應該是broadcastable(1VS1在昏暗1,3VS1在昏暗2,1vs10在3.暗淡,但現在看來,這是不是:

>>> b+c 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ValueError: shape mismatch: objects cannot be broadcast to a single shape 

的解釋是certainely明顯...但是請大家幫我

回答

1
b[:,:,None] + c 

返回(1,3,10)陣列您!來定義缺失的軸(第三個)。

您還可以使用

b[:,:,newaxis] + c 

因爲你進口* from numpy,這是通常不是一個好主意。

import numpy as np更好。這樣,你將永遠知道這些方法都來自(如果導入多個包):

import numpy as np 
a = np.array([10,20]).reshape(2,1) 
b = np.array([100,200,300]).reshape(1,3) 
c = np.arange(1,11).reshape(1,1,10) 

print a + b 
print a + c 
print b[:,:,np.newaxis] + c 
+0

非常感謝!我知道'從numpy導入*',我用它來清楚,但你是對的,這應該是無處不在。 – 2012-04-17 09:37:41

1

A + C是(2,1)VS(1,1,10)和故應該是可廣播的 (dim1中的2vs1,1 dim2中的1vs1和dim3中的1vs10,廣播規則爲 )。事實上,這是:

>>> a+c array([[[11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 
       [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]]]) 

不太,注意A + C是(1,2,10)不(2,1,10)。

>>> from numpy import array, arange, newaxis 
>>> a=array([10,20]).reshape(2,1) 
>>> b=array([100,200,300]).reshape(1,3) 
>>> c=arange(1,11).reshape(1,1,10) 
>>> (a + c).shape 
(1, 2, 10).shape 

當廣播具有不同尺寸的陣列,用更少的尺寸一送以1s之初,more info here填充,所以b + c就像是試圖增加一個(1,1,3)與(1,1 ,10)。 @ eumiro的建議,b[:,:,np.newaxis] + c,可能是將b重構爲(1,3,1)的最簡單方法,所以你可以得到你所期望的。

+0

謝謝Bago,的確我沒注意到(a + c)是(1,2,10)。事實上(如eumiro所建議的),爲了獲得(2,1,10)我需要寫'a [:,:,np.newaxis] + c'。 – 2012-04-17 15:04:54