2014-12-03 66 views
1

我擔心這可能是一個非常愚蠢的問題。但是我找不到解決方案。 我想在不使用循環的情況下在python中執行以下操作,因爲我正在處理大尺寸數組。 有什麼建議嗎?如何使1d數組乘以2d數組導致python的3d數組

import numpy as np 
a = np.array([1,2,3,..., N]) # arbitrary 1d array 
b = np.array([[1,2,3],[4,5,6],[7,8,9]]) # arbitrary 2d array 
c = np.zeros((N,3,3)) 
c[0,:,:] = a[0]*b 
c[1,:,:] = a[1]*b 
c[2,:,:] = a[2]*b 
c[3,:,:] = ... 
... 
... 
c[N-1,:,:] = a[N-1]*b 
+0

魔法.....你想幹什麼?爲什麼一個矩陣乘以一個矢量應該是一個3d矩陣......你會用什麼樣的數學? – 2014-12-03 11:27:05

+0

在疊加1d和2d陣列後,您不會得到3d陣列 只需進行2d變換,如果該乘法有效 – nishparadox 2014-12-03 11:28:29

+0

它不是矩陣乘法。但我想避免使用循環,也想要一個簡單的數組結構。 – Heungson 2014-12-03 23:57:10

回答

1

爲了避免Python的層次循環,你可以使用np.newaxis擴大a (或無,這是同樣的事情):

>>> a = np.arange(1,5) 
>>> b = np.arange(1,10).reshape((3,3)) 
>>> a[:,None,None]*b 
array([[[ 1, 2, 3], 
     [ 4, 5, 6], 
     [ 7, 8, 9]], 

     [[ 2, 4, 6], 
     [ 8, 10, 12], 
     [14, 16, 18]], 

     [[ 3, 6, 9], 
     [12, 15, 18], 
     [21, 24, 27]], 

     [[ 4, 8, 12], 
     [16, 20, 24], 
     [28, 32, 36]]]) 

或者np.einsum,這是矯枉過正這裏,但經常是得心應手,使得它非常明確你想要什麼用的座標發生:

>>> c2 = np.einsum('i,jk->ijk', a, b) 
>>> np.allclose(c2, a[:,None,None]*b) 
True 
+0

看起來非常簡單和容易。現在我也明白了「a [:,None,None]」。謝謝。 – Heungson 2014-12-04 00:06:07

0

沒看明白乘法..但在這裏是一種使用numpy的,以使蟒蛇矩陣乘法:

import numpy as np 
a = np.matrix([1, 2]) 
b = np.matrix([[1, 2], [3, 4]]) 
result = a*b 
print(result) 

>>>result 
matrix([7, 10]) 
+0

謝謝。但這不是我想要的。 – Heungson 2014-12-04 00:06:59

1

我的回答只使用numpy元,特別是對數組乘法(你想要做什麼都有一個名字,它是一個外積)。

由於numpy的外乘法功能的限制,我們必須重塑的結果,但這是非常便宜的,因爲ndarray的數據塊不參與。

% python 
Python 2.7.8 (default, Oct 18 2014, 12:50:18) 
[GCC 4.9.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import numpy as np 
>>> a = np.array((1,2)) 
>>> b = np.array([[n*m for m in (1,2,3,4,5,6)] for n in (10,100,1000)]) 
>>> print b 
[[ 10 20 30 40 50 60] 
[ 100 200 300 400 500 600] 
[1000 2000 3000 4000 5000 6000]] 
>>> print np.outer(a,b) 
[[ 10 20 30 40 50 60 100 200 300 400 500 600 
    1000 2000 3000 4000 5000 6000] 
[ 20 40 60 80 100 120 200 400 600 800 1000 1200 
    2000 4000 6000 8000 10000 12000]] 
>>> print "Almost there!" 
Almost there! 
>>> print np.outer(a,b).reshape(a.shape[0],b.shape[0], b.shape[1]) 
[[[ 10 20 30 40 50 60] 
    [ 100 200 300 400 500 600] 
    [ 1000 2000 3000 4000 5000 6000]] 

[[ 20 40 60 80 100 120] 
    [ 200 400 600 800 1000 1200] 
    [ 2000 4000 6000 8000 10000 12000]]] 
>>> 
+0

謝謝。這真的很有幫助。 – Heungson 2014-12-04 00:01:44