我认为这是最容易获得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