gpt4 book ai didi

python - scipy.sparse 矩阵 : subtract row mean to nonzero elements

转载 作者:太空宇宙 更新时间:2023-11-03 14:09:45 25 4
gpt4 key购买 nike

我在 csr_matrix 中有一个稀疏矩阵格式。对于每一行,我需要从非零元素中减去行均值。必须根据行的非零元素数(而不是行的长度)计算均值。我找到了一种使用以下代码快速计算行均值的方法:

# M is a csr_matrix
sums = np.squeeze(np.asarray(M.sum(1))) # sum of the nonzero elements, for each row
counts = np.diff(M.tocsr().indptr) # count of the nonzero elements, for each row


# for the i-th row the mean is just sums[i] / float(counts[i])

问题是更新部分。我需要一种快速的方法来做到这一点。实际上我正在做的是将 M 转换为 lil_matrix并以这种方式执行更新:

M = M.tolil()

for i in xrange(len(sums)):
for j in M.getrow(i).nonzero()[1]:
M[i, j] -= sums[i] / float(counts[i])

这很慢。对更快的解决方案有什么建议吗?

最佳答案

这个很棘手。我想我有。基本思想是我们尝试得到一个均值在对角线上的对角矩阵,以及一个类似于 M 的矩阵,但在 M 中的非零数据位置有一个矩阵。然后我们将它们相乘并从 M 中减去乘积。这里去……

>>> import numpy as np
>>> import scipy.sparse as sp
>>> a = sp.csr_matrix([[1., 0., 2.], [1.,2.,3.]])
>>> a.todense()
matrix([[ 1., 0., 2.],
[ 1., 2., 3.]])
>>> tot = np.array(a.sum(axis=1).squeeze())[0]
>>> tot
array([ 3., 6.])
>>> cts = np.diff(a.indptr)
>>> cts
array([2, 3], dtype=int32)
>>> mu = tot/cts
>>> mu
array([ 1.5, 2. ])
>>> d = sp.diags(mu, 0)
>>> d.todense()
matrix([[ 1.5, 0. ],
[ 0. , 2. ]])
>>> b = a.copy()
>>> b.data = np.ones_like(b.data)
>>> b.todense()
matrix([[ 1., 0., 1.],
[ 1., 1., 1.]])
>>> (d * b).todense()
matrix([[ 1.5, 0. , 1.5],
[ 2. , 2. , 2. ]])
>>> (a - d*b).todense()
matrix([[-0.5, 0. , 0.5],
[-1. , 0. , 1. ]])

祝你好运!希望对您有所帮助。

关于python - scipy.sparse 矩阵 : subtract row mean to nonzero elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39685168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com