2017-08-23 46 views
1

我有一個矩陣A = [x1, x2, ..., xm]其中每個xi是大小爲[n, 1]的列向量。所以A已經形成[n, m]。我試圖找到每個列向量的協方差矩陣,以便如果結果是另一個矩陣C,C的形狀爲[n, n, m]C[:,:,i] = np.outer(xi, xi)向量外積的泛化:將其應用於矩陣的每一列

有人可以告訴我如何在numpy中完成上述操作,或者指向我應該檢查的張量操作嗎?

+0

這是最近在另一個SO指出的,'np.outer'變平其輸入,而'np.multiply.outer'不。 – hpaulj

回答

1

所以你outer環路產生:

In [1147]: A = np.arange(12).reshape(3,4) 
In [1148]: [np.outer(A[:,i],A[:,i]) for i in range(4)] 
Out[1148]: 
[array([[ 0, 0, 0], 
     [ 0, 16, 32], 
     [ 0, 32, 64]]), array([[ 1, 5, 9], 
     [ 5, 25, 45], 
     [ 9, 45, 81]]), array([[ 4, 12, 20], 
     [ 12, 36, 60], 
     [ 20, 60, 100]]), array([[ 9, 21, 33], 
     [ 21, 49, 77], 
     [ 33, 77, 121]])] 

stacking,關於新的第一維生產:

In [1149]: np.stack(_) 
Out[1149]: 
array([[[ 0, 0, 0], 
     [ 0, 16, 32], 
     [ 0, 32, 64]], 
    .... 
     [ 21, 49, 77], 
     [ 33, 77, 121]]]) 
In [1150]: _.shape 
Out[1150]: (4, 3, 3) # wrong order - can be transposed. 

stack讓我們指定一個不同的軸:

In [1153]: np.stack([np.outer(A[:,i],A[:,i]) for i in range(4)],2) 
Out[1153]: 
array([[[ 0, 1, 4, 9], 
     [ 0, 5, 12, 21], 
     [ 0, 9, 20, 33]], 

     [[ 0, 5, 12, 21], 
     [ 16, 25, 36, 49], 
     [ 32, 45, 60, 77]], 

     [[ 0, 9, 20, 33], 
     [ 32, 45, 60, 77], 
     [ 64, 81, 100, 121]]]) 

np.einsum這很好嗎?一報還一:

In [1151]: np.einsum('mi,ni->mni',A,A) 
Out[1151]: 
array([[[ 0, 1, 4, 9], 
     [ 0, 5, 12, 21], 
     [ 0, 9, 20, 33]], 

     [[ 0, 5, 12, 21], 
     [ 16, 25, 36, 49], 
     [ 32, 45, 60, 77]], 

     [[ 0, 9, 20, 33], 
     [ 32, 45, 60, 77], 
     [ 64, 81, 100, 121]]]) 
In [1152]: _.shape 
Out[1152]: (3, 3, 4) 

乘法廣播也是不錯

In [1156]: A[:,None,:]*A[None,:,:] 
Out[1156]: 
array([[[ 0, 1, 4, 9], 
     [ 0, 5, 12, 21], 
     ... 
     [ 32, 45, 60, 77], 
     [ 64, 81, 100, 121]]]) 
相關問題