我認爲這是最容易獲得coo
格式矩陣的上三角:
首先做一個小的對稱矩陣:
In [876]: A = sparse.random(5,5,.3,'csr')
In [877]: A = A+A.T
In [878]: A
Out[878]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 11 stored elements in Compressed Sparse Row format>
In [879]: A.A
Out[879]:
array([[ 0. , 0. , 0.81388978, 0. , 0. ],
[ 0. , 0. , 0.73944395, 0.20736975, 0.98968617],
[ 0.81388978, 0.73944395, 0. , 0. , 0. ],
[ 0. , 0.20736975, 0. , 0.05581152, 0.04448881],
[ 0. , 0.98968617, 0. , 0.04448881, 0. ]])
轉換爲coo
,並設置較低的三角形數據值設爲0
In [880]: Ao = A.tocoo()
In [881]: mask = (Ao.row>Ao.col)
In [882]: mask
Out[882]:
array([False, False, False, False, True, True, True, False, False,
True, True], dtype=bool)
In [883]: Ao.data[mask]=0
轉換回0,並使用eliminate_zeros
修剪矩陣。
In [890]: A1 = Ao.tocsr()
In [891]: A1
Out[891]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 11 stored elements in Compressed Sparse Row format>
In [892]: A1.eliminate_zeros()
In [893]: A1
Out[893]:
<5x5 sparse matrix of type '<class 'numpy.float64'>'
with 6 stored elements in Compressed Sparse Row format>
In [894]: A1.A
Out[894]:
array([[ 0. , 0. , 0.81388978, 0. , 0. ],
[ 0. , 0. , 0.73944395, 0.20736975, 0.98968617],
[ 0. , 0. , 0. , 0. , 0. ],
[ 0. , 0. , 0. , 0.05581152, 0.04448881],
[ 0. , 0. , 0. , 0. , 0. ]])
兩者coo
和csr
格式具有就地eliminate_zeros
方法。
def eliminate_zeros(self):
"""Remove zero entries from the matrix
This is an *in place* operation
"""
mask = self.data != 0
self.data = self.data[mask]
self.row = self.row[mask]
self.col = self.col[mask]
而不是使用Ao.data[mask]=0
,可以將這個代碼作爲消除只是lower_triangle值的模型。
'vectorize_words'和'cosine_similarity'從哪裏來?在生成'cos_similarity'時刪除'duplicates'可能比在之後從矩陣中刪除它們更容易。'稀疏'矩陣不是爲單個元素操作而設計的。 – hpaulj
'scipy.spatial.distance.squareform'轉換爲/從一個緊湊的upper_triangle形式消除重複。我不知道是否有一個適用於稀疏矩陣的版本。 – hpaulj
@hpaulj cosine_similarity來自sklearn,矢量化單詞是我的函數來獲得每個單詞矢量 – nitheism