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

时间:2013-01-22 22:20:33

标签: 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_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))

有谁知道为什么会这样?这个价值来自哪里?

1 个答案:

答案 0 :(得分:3)

你有重复的坐标,构造函数正在添加它们。执行以下操作:

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

编辑以下丑陋的代码可以很好地处理重复条目的小例子,其中一些代码是从this other question借来的,试一试:

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))