如果你有一个稀疏矩阵X:
>> X = csr_matrix([[0,2,0,2],[0,2,0,1]])
>> print type(X)
>> print X.todense()
<class 'scipy.sparse.csr.csr_matrix'>
[[0 2 0 2]
[0 2 0 1]]
Run Code Online (Sandbox Code Playgroud)
矩阵Y:
>> print type(Y)
>> print text_scores
<class 'numpy.matrixlib.defmatrix.matrix'>
[[8]
[5]]
Run Code Online (Sandbox Code Playgroud)
...如何将X的每个元素乘以Y的行.例如:
[[0*8 2*8 0*8 2*8]
[0*5 2*5 0*5 1*5]]
Run Code Online (Sandbox Code Playgroud)
要么:
[[0 16 0 16]
[0 10 0 5]]
Run Code Online (Sandbox Code Playgroud)
我已经厌倦了这个,但显然它不起作用,因为尺寸不匹配:
Z = X.data * Y
我需要一种有效的方法来对稀疏矩阵进行行标准化.
特定
W = matrix([[0, 1, 0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 1, 0, 1, 0],
[0, 0, 1, 0, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1, 0, 1],
[0, 0, 0, 0, …Run Code Online (Sandbox Code Playgroud) 我有一个包含一些元素的稀疏矩阵。现在我想对其进行标准化。但是,当我这样做时,它会转换为 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
Run Code Online (Sandbox Code Playgroud)
有没有一种优雅的方法可以做到这一点而不必诉诸 for 循环?
编辑
是的,这可以使用“l1”标准化来完成sklearn.preprocessing.normalize,但是,我不想依赖 sklearn。