【问题标题】:Scipy: Sparse Matrix giving incorrect valuesScipy:稀疏矩阵给出不正确的值
【发布时间】:2013-01-23 08:25:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: numpy scipy sparse-matrix


    【解决方案1】:

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

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

    【讨论】:

    • 好眼光,@Jamie...这将是一个问题。您是否知道一种对重复项进行平均而不是求和的方法?
    • @NoobSaibot 试试我编辑的代码,看看它在你的真实案例中的运行速度有多慢。
    • @Jamie,它完美地工作!我不知道如果没有这个网站我会做什么......说真的。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2017-03-31
    • 2023-04-10
    • 2017-07-21
    • 2011-11-28
    • 2017-07-02
    相关资源
    最近更新 更多