Python 标准化稀疏行概率矩阵
我有一个稀疏矩阵,有几个元素。现在我想把它正常化。但是,当我这样做时,它会被转换为一个numpy数组,这从性能角度来看是不可接受的 为了使事情更具体,请考虑下面的例子:Python 标准化稀疏行概率矩阵,python,numpy,scipy,sparse-matrix,Python,Numpy,Scipy,Sparse Matrix,我有一个稀疏矩阵,有几个元素。现在我想把它正常化。但是,当我这样做时,它会被转换为一个numpy数组,这从性能角度来看是不可接受的 为了使事情更具体,请考虑下面的例子: x = csr_matrix([[0, 1, 1], [2, 3, 0]]) # sparse normalization = x.sum(axis=1) # dense, this is OK x / normalization # this is dense, not OK, can be huge 有没有一种优雅
x = csr_matrix([[0, 1, 1], [2, 3, 0]]) # sparse
normalization = x.sum(axis=1) # dense, this is OK
x / normalization # this is dense, not OK, can be huge
有没有一种优雅的方法可以做到这一点,而不必求助于for循环
编辑
是的,这可以使用
sklearn.preprocessing.normalize
使用“l1”规范化来完成,但是,我不希望依赖sklearn 您可以始终使用csr
内部构件:
>>> import numpy as np
>>> from scipy import sparse
>>>
>>> x = sparse.csr_matrix([[0, 1, 1], [2, 3, 0]])
>>>
>>> x.data = x.data / np.repeat(np.add.reduceat(x.data, x.indptr[:-1]), np.diff(x.indptr))
>>> x
<2x3 sparse matrix of type '<class 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> x.A
array([[0. , 0.5, 0.5],
[0.4, 0.6, 0. ]])
>>将numpy作为np导入
>>>从scipy导入稀疏
>>>
>>>x=sparse.csr_矩阵([[0,1,1],[2,3,0]]
>>>
>>>x.data=x.data/np.repeat(np.add.reduceat(x.data,x.indptr[:-1]),np.diff(x.indptr))
>>>x
>>>x.A
数组([[0,0.5,0.5],
[0.4, 0.6, 0. ]])
您可以始终使用csr
内部构件:
>>> import numpy as np
>>> from scipy import sparse
>>>
>>> x = sparse.csr_matrix([[0, 1, 1], [2, 3, 0]])
>>>
>>> x.data = x.data / np.repeat(np.add.reduceat(x.data, x.indptr[:-1]), np.diff(x.indptr))
>>> x
<2x3 sparse matrix of type '<class 'numpy.float64'>'
with 4 stored elements in Compressed Sparse Row format>
>>> x.A
array([[0. , 0.5, 0.5],
[0.4, 0.6, 0. ]])
>>将numpy作为np导入
>>>从scipy导入稀疏
>>>
>>>x=sparse.csr_矩阵([[0,1,1],[2,3,0]]
>>>
>>>x.data=x.data/np.repeat(np.add.reduceat(x.data,x.indptr[:-1]),np.diff(x.indptr))
>>>x
>>>x.A
数组([[0,0.5,0.5],
[0.4, 0.6, 0. ]])
请参见。。。我不希望依赖scikit learn或networkx。这不是很有帮助。“我不希望依赖于scikit learn或networkx。”好吧,如果你把它放在问题中,那么我们就会知道这些建议没有帮助。我们无法读懂你的心思!你说得对,我应该说清楚的。看。。。我不希望依赖scikit learn或networkx。这不是很有帮助。“我不希望依赖于scikit learn或networkx。”好吧,如果你把它放在问题中,那么我们就会知道这些建议没有帮助。我们无法读懂你的心思!你说得对,我应该说清楚的。谢谢你!这正是我要找的!很高兴知道这一点。谢谢+1.在1000x800随机矩阵上,您的答案甚至比sklearn.preprocessing.normalize
更快。谢谢!这正是我要找的!很高兴知道这一点。谢谢+1.在1000x800随机矩阵上,您的答案甚至比sklearn.preprocessing.normalize
更快。