2016-08-30 47 views
-2

我試圖遵循documentationnp.linalg.svd中提供的一些示例代碼,以比較TDM矩陣上的SVD之後的術語和文檔相似性。下面是我得到了什麼:無法將形狀(1285)中的輸入數組廣播成形(1285,5344)

results_t = np.linalg.svd(tdm_t) 
results_t[1].shape 

產生

(1285,) 

而且

results_t[2].shape 
(5334, 5334) 

所以後來試圖播放這些結果來創建每個經典的SVD投影方式真正S矩陣,我得到了:

S = np.zeros((results_t[0].shape[0], results_t[2].shape[0]), dtype = float) 
S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1] 

最後一行產生錯誤:

--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-329-16e79bc97c4b> in <module>() 
----> 1 S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1] 

ValueError: could not broadcast input array from shape (1285) into shape (1285,5334) 

我在做什麼錯在這裏?

+1

嘗試'results_t [1] [:,無]' – Joel

+0

如果下面的答案沒有幫助,您能否明確說明錯誤行將被執行? – Joel

+0

你想分配一個塊還是對角線? – hpaulj

回答

0

(注意,在看畢波多黎各的回答,看起來也許是正確的解釋是,你實際上並沒有試圖與該命令播出?這個答案顯示瞭如何真正做到廣播)。

X = scipy.zeros((5,4)) 
X 
> array([[ 0., 0., 0., 0.], 
     [ 0., 0., 0., 0.], 
     [ 0., 0., 0., 0.], 
     [ 0., 0., 0., 0.], 
     [ 0., 0., 0., 0.]]) 

Y = scipy.arange(5) 
Y 
> array([0, 1, 2, 3, 4]) 
X[:,:]=Y 
> could not broadcast input array from shape (5) into shape (5,4) 

因此,而不是試圖

X[:,:]=Y[:,None] 
X 
> array([[ 0., 0., 0., 0.], 
    [ 1., 1., 1., 1.], 
    [ 2., 2., 2., 2.], 
    [ 3., 3., 3., 3.], 
    [ 4., 4., 4., 4.]]) 

您可以從以下

Z = scipy.arange(4) 
Z 
> array([0, 1, 2, 3]) 
X[:,:]=Z 
X 
>array([[ 0., 1., 2., 3.], 
     [ 0., 1., 2., 3.], 
     [ 0., 1., 2., 3.], 
     [ 0., 1., 2., 3.], 
     [ 0., 1., 2., 3.]]) 
得到問題多一點理解10

這裏的問題是,它確信你正在將Y(或Z)當作數組的一行處理,而你試圖將它放入列中。做Y[:,None]基本上迫使它將Y解釋爲一列。

0

您在使用索引時正在使用切片。舉個例子:

A = np.zeros((4, 5)) 
end0, end1 = A.shape 

# These are both true 
A == A[:, :] 
A[:, :] == A[:end0, :end1] 

# To get the diagonal of an array you want to use range or np.arange 
A[range(end0), range(end0)] == A.diagonal() 

一些其他的東西,你可能會發現有用:

# If U.shape is (a, b) and S.shape is (b,) 
U.dot(np.diag(S)) == (U * S) 

# IF V.shape (b, a) and S.shape is (b,) 
np.diag(S).dot(V) == (S.reshape(b, 1) * V) 
1

所以根據錯誤信息,目標

S[:results_t[2].shape[0], :results_t[2].shape[0]] 

(1285,5334),而源

results_t[1] 

(1285,)

因此,它必須將源廣播到與目標匹配的形狀,然後才能進行分配。如果試圖用這些形狀或者乘以等來對兩個數組進行求和,那麼這也適用。

  • 第一個廣播步驟使維數匹配。來源是1d,所以它需要2d。 numpy將嘗試results_t[1][np.newaxis,:],產生(1, 1285)

  • 第二步是擴大所有尺寸1尺寸以匹配其他尺寸。但這不可能發生在這裏 - 因此錯誤。 (1285,5334)+(1,1285)?

======

如果你想分配給塊(或全部S),然後使用:

S[:results_t[2].shape[0], :results_t[2].shape[0]] = results_t[1][:,np.newaxis] 

要指定r1對角的S,使用列表索引(而不是切片):

S[range(results_t[1].shape[0]), range(results_t[1].shape[0])] = results_t[1] 

S[np.diag_indices(results_t[1].shape[0])] = results_t[1] 

在這種情況下,那些ranges的長度必須匹配results_t[1]

相關問題