Numpy Scipy:稀疏矩阵给出的值不正确

Numpy Scipy:稀疏矩阵给出的值不正确,numpy,scipy,sparse-matrix,Numpy,Scipy,Sparse Matrix,下面是生成稀疏矩阵的代码: import numpy as np import scipy def sparsemaker(X, Y, Z): 'X, Y, and Z are 2D arrays of the same size' x_, row = np.unique(X, return_inverse=True) y_, col = np.unique(Y, return_inverse=True) return scipy.sparse.csr_matr

下面是生成稀疏矩阵的代码:

import numpy as np
import scipy

def sparsemaker(X, Y, Z):
    'X, Y, and Z are 2D arrays of the same size'
    x_, row = np.unique(X, return_inverse=True)
    y_, col = np.unique(Y, return_inverse=True)
    return scipy.sparse.csr_matrix( (Z.flat,(row,col)), shape=(x_.size, y_.size) )

>>> print sparsemaker(A, B, C) #A, B, and C are (220, 256) sized arrays.
(0, 0)  167064.269831
(0, 2)  56.6146564629
(0, 9)  53.8660340698
(0, 23) 80.6529717039
(0, 28) 0.0
(0, 33) 53.2379218326
(0, 40) 54.3868995375
 :          :
现在我的输入数组有点大,所以我不知道如何在这里发布它们(除非有人有任何想法);但即使看第一个值,我也可以看出有些地方不对劲:

>>> test = sparsemaker(A, B, C)
>>> np.max(test.toarray())
167064.26983076424

>>> np.where(C==np.max(test.toarray()))
(array([], dtype=int64), array([], dtype=int64))

有人知道为什么会这样吗?该值从何而来?

您有重复的坐标,构造函数正在将它们全部相加。请执行以下操作:

x_, row = np.unique(X, return_inverse=True)
y_, col = np.unique(Y, return_inverse=True)
print Z.flat[(row == 0) & (col == 0)].sum()
你应该把那神秘的
167064.26983076424
打印出来

编辑下面的难看代码在平均重复输入的小示例中效果很好,有些代码借用了,请尝试一下:

def sparsemaker(X, Y, Z):
    'X, Y, and Z are 2D arrays of the same size'
    x_, row = np.unique(X, return_inverse=True)
    y_, col = np.unique(Y, return_inverse=True)
    indices = np.array(zip(row, col))
    _, repeats = np.unique(indices.view([('', indices.dtype)]*2),
                           return_inverse=True)
    counts = 1. / np.bincount(repeats)
    factor = counts[repeats]

    return scipy.sparse.csr_matrix((Z.flat * factor,(row,col)),
                                   shape=(x_.size, y_.size))

好眼力,杰米……这会是个问题。你知道一种方法来计算重复项的平均值而不是求和吗?@NoobSaibot在我的编辑中尝试一下代码,看看它在你的真实案例中工作得有多慢。@Jamie,它工作得很好!我不知道没有这个网站我该怎么办…说真的。非常感谢。