2017-04-15 87 views
0

我有一個numpy的csr矩陣,我想得到它的意思,但它包含了很多零,因爲我消除了所有在主對角線上的值,它只在上面的三角形值上面,現在我的csr矩陣當轉換爲數組看起來像這樣:numpy csr矩陣「均值」函數是否在所有矩陣上均值?我如何刪除某個值?

0.   0.   0.   0.   0.   0.   0. 
    0.   0.   0.   0.   0.   0.   0. 
    0.   0.   0.   0.   0.63646664 0.34827262 
    0.24316454 0.1362165 0.63646664 0.15762204 0.31692202 0.12114576 
    0.35917146 

據我瞭解這個零點在那裏,以便重要的是,企業社會責任矩陣工作,這樣顯示的東西:

(0,5) 0.5790418 
(3,10) 0.578210 
(5,20) 0.912370 
(67,5) 0.1093109 

我看到該csr矩陣有它自己的 mean function,但這是否意味着函數考慮到所有零,因此除以包含零的數組中元素的數量?因爲我只需要非零值的意思。我的矩陣包含多個向量之間的相似性和更像是矩陣類似的東西的清單:

[[ 0.   0.63646664 0.48492084 0.42134077 0.14366401 0.10909745 
    0.06172853 0.08116201 0.19100626 0.14517247 0.23814955 0.1899649 
    0.20181049 0.25663533 0.21003358 0.10436352 0.2038447 1. 
    0.63646664 0.34827262 0.24316454 0.1362165 0.63646664 0.15762204 
    0.31692202 0.12114576 0.35917146] 
[ 0.   0.   0.58644824 0.4977052 0.15953415 0.46110612 
    0.42580993 0.3236768 0.48874263 0.44671607 0.59153001 0.57868948 
    0.27357541 0.51645488 0.43317846 0.50985032 0.37317457 0.63646664 
    1.   0.51529235 0.56963948 0.51218525 1.   0.38345582 
    0.55396192 0.32287605 0.46700191] 
[ 0.   0.   0.   0.6089113 0.53873289 0.3367261 
    0.29264493 0.13232082 0.43288206 0.80079927 0.37842518 0.33658945 
    0.61990095 0.54372307 0.49982101 0.23555037 0.39283379 0.48492084 
    0.58644824 0.64524906 0.31279271 0.39476181 0.58644824 0.39028705 
    0.43856802 0.32296735 0.5541861 ]] 

所以,我怎麼能取均值僅在非零值?

我的另一個問題是如何刪除所有等於某事的值,正如我上面指出的,我可能必須將某個值變爲零?但我該怎麼做?例如,我想擺脫所有等於1.0或更大的值? 這裏是我的,直到這點使我的矩陣代碼:

vectorized_words = parse.csr_matrix(vectorize_words(nostopwords,glove_dict)) 

#calculating the distance/similarity between each vector in the matrix 
cos_similiarity = cosine_similarity(vectorized_words, dense_output=False) 
# since there are duplicates like (5,0) and (0,5) which we should remove, I use scipy's triu function 
coo_cossim = cos_similiarity.tocoo() 
vector_similarities = sparse.triu(coo_cossim, k = 1).tocsr() 
+0

您是否使用'scipy.sparse'中的'csr_matrix'? – James

+0

@詹姆斯是的我做 – nitheism

+0

我認爲'mean'不太可能忽略零。爲什麼不只是'sum(arr,axis = ...)/ sum(arr!= 0,axis = ...)'? – Eric

回答

3

是,csr_matrix.mean()計算平均值時不包括所有的零。舉個簡單的例子:

from scipy.sparse import csr_matrix 

m = csr_matrix(([1,1], ([2,3],[3,3])), shape=(5,5)) 
m.toarray() 

# returns: 
array([[0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 1, 0], 
     [0, 0, 0, 1, 0], 
     [0, 0, 0, 0, 0]], dtype=int32) 

# test the mean method 
m.mean(), m.mean(axis=0), m.mean(axis=1) 

# returns: 
0.080000000000000002, 
matrix([[ 0. , 0. , 0. , 0.4, 0. ]]), 
matrix([[ 0. ], 
     [ 0. ], 
     [ 0.2], 
     [ 0.2], 
     [ 0. ]]) 

如果你需要執行一個不包含零的計算,你將不得不用其他方法來生成結果。儘管如此,這並不難:

nonzero_mean = m.sum()/m.count_nonzero() 
+0

如果你不調用任何方法,不需要導入'numpy',是嗎? – Eric

+0

謝謝,那是一個複製/粘貼的單據。現在修復。 – James

+0

謝謝,這實際上解決了我的問題無論如何,我會循環槽 – nitheism