规范Scipy稀疏矩阵的有效方法 [英] Efficient way to normalize a Scipy Sparse Matrix

查看:60
本文介绍了规范Scipy稀疏矩阵的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个函数来规范大型稀疏矩阵的行(这样它们的总和就为一).

I'd like to write a function that normalizes the rows of a large sparse matrix (such that they sum to one).

from pylab import *
import scipy.sparse as sp

def normalize(W):
    z = W.sum(0)
    z[z < 1e-6] = 1e-6
    return W / z[None,:]

w = (rand(10,10)<0.1)*rand(10,10)
w = sp.csr_matrix(w)
w = normalize(w)

但是,这给出了以下异常:

However this gives the following exception:

File "/usr/lib/python2.6/dist-packages/scipy/sparse/base.py", line 325, in __div__
     return self.__truediv__(other)
File "/usr/lib/python2.6/dist-packages/scipy/sparse/compressed.py", line 230, in  __truediv__
   raise NotImplementedError

有没有合理简单的解决方案?我已经看过,但仍不清楚如何实际做分裂.

Are there any reasonably simple solutions? I have looked at this, but am still unclear on how to actually do the division.

推荐答案

这已在 axis=1应按行归一化,axis=0应按列归一化.使用可选参数copy=False修改矩阵.

axis=1 should normalize by rows, axis=0 to normalize by column. Use the optional argument copy=False to modify the matrix in place.

这篇关于规范Scipy稀疏矩阵的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆