Scipy.sparse.csr_matrix:如何获取十大值和索引? [英] Scipy.sparse.csr_matrix: How to get top ten values and indices?

查看:702
本文介绍了Scipy.sparse.csr_matrix:如何获取十大值和索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的csr_matrix,并且我对前十个值及其每行的索引感兴趣.但是我没有找到一种操纵矩阵的合适方法.

I have a large csr_matrix and I am interested in the top ten values and their indices each row. But I did not find a decent way to manipulate the matrix.

这是我当前的解决方案,主要思想是逐行处理它们:

Here is my current solution and the main idea is to process them row by row:

row = csr_matrix.getrow(row_number).toarray()[0].ravel()
top_ten_indicies = row.argsort()[-10:]
top_ten_values = row[row.argsort()[-10:]]

通过这样做,csr_matrix的优点没有得到充分利用.它更像是一种蛮力解决方案.

By doing this, the advantages of csr_matrix is not fully used. It's more like a brute force solution.

推荐答案

在这种情况下,我看不到csr格式的优点是什么.当然,所有非零值都收集在一个.data数组中,而对应的列索引在.indices中.但是它们处于不同长度的块中.这意味着它们不能并行处理,也不能使用numpy数组步幅进行处理.

I don't see what the advantages of csr format are in this case. Sure, all the nonzero values are collected in one .data array, with the corresponding column indexes in .indices. But they are in blocks of varying length. And that means they can't be processed in parallel or with numpy array strides.

一种解决方案是将这些块填充到公共长度的块中.这就是.toarray()所做的.然后,您可以使用argsort(axis=1) or with argpartition`找到最大值.

One solution is the pad those blocks into common length blocks. That's what .toarray() does. Then you can find the maximum values with argsort(axis=1) or withargpartition`.

另一种方法是将它们分成行大小的块,并处理每个块.这就是您使用.getrow所做的事情.分解它们的另一种方法是转换为lil格式,并处理.data.rows数组的子列表.

Another is to break them into row sized blocks, and process each of those. That's what you are doing with the .getrow. Another way of breaking them up is convert to lil format, and process the sublists of the .data and .rows arrays.

第三个可能的选择是使用ufunc reduceat方法.这使您可以将ufunc reduction方法应用于数组的顺序块.已经建立了像np.add这样的ufunc来利用此优势. argsort不是这样的功能.但是,有一种方法可以从Python函数构造ufunc,并在常规Python迭代中获得适度的速度. [我需要查看一个最近的SO问题来说明这一点.]

A possible third option is to use the ufunc reduceat method. This lets you apply ufunc reduction methods to sequential blocks of an array. There are established ufunc like np.add that take advantage of this. argsort is not such a function. But there is a way of constructing a ufunc from a Python function, and gain some modest speed over regular Python iteration. [I need to look up a recent SO question that illustrates this.]

我将通过一个简单的函数来说明其中的一些问题,即按行求和.

I'll illustrate some of this with a simpler function, sum over rows.

如果A2是csr矩阵.

A2.sum(axis=1)  # the fastest compile csr method
A2.A.sum(axis=1)  # same, but with a dense intermediary
[np.sum(l.data) for l in A2]  # iterate over the rows of A2
[np.sum(A2.getrow(i).data) for i in range(A2.shape[0])]  # iterate with index
[np.sum(l) for l in A2.tolil().data]  # sum the sublists of lil format
np.add.reduceat(A2.data, A2.indptr[:-1])  # with reduceat

A2.sum(axis=1)被实现为矩阵乘法.这与排序问题无关,但仍然是一种求和问题的有趣方式.请记住,csr格式是为有效乘法而开发的.

A2.sum(axis=1) is implemented as a matrix multiplication. That's not relevant to the sort problem, but still an interesting way of looking at the summation problem. Remember csr format was developed for efficient multiplication.

对于我当前的样本矩阵(为另一个SO稀疏问题创建)

For a my current sample matrix (created for another SO sparse question)

<8x47752 sparse matrix of type '<class 'numpy.float32'>'
     with 32 stored elements in Compressed Sparse Row format>

一些比较时间是

In [694]: timeit np.add.reduceat(A2.data, A2.indptr[:-1])
100000 loops, best of 3: 7.41 µs per loop

In [695]: timeit A2.sum(axis=1)
10000 loops, best of 3: 71.6 µs per loop

In [696]: timeit [np.sum(l) for l in A2.tolil().data]
1000 loops, best of 3: 280 µs per loop

其他所有条件都是1毫秒或更长.

Everything else is 1ms or more.

我建议着重开发单行功能,例如:

I suggest focusing on developing your one-row function, something like:

def max_n(row_data, row_indices, n):
    i = row_data.argsort()[-n:]
    # i = row_data.argpartition(-n)[-n:]
    top_values = row_data[i]
    top_indices = row_indices[i]  # do the sparse indices matter?
    return top_values, top_indices, i

然后查看if是否适合这些迭代方法之一. tolil()看起来最有前途.

Then see how if fits in one of these iteration methods. tolil() looks most promising.

我还没有解决如何收集这些结果的问题.它们应该是列表列表,具有10列的数组,另一个具有每行10个值的稀疏矩阵等吗?

I haven't addressed the question of how to collect these results. Should they be lists of lists, array with 10 columns, another sparse matrix with 10 values per row, etc.?

对每一行进行排序稀疏的保存前K个值&列索引-几年前的问题类似,但尚未得到答案.

sorting each row of a large sparse & saving top K values & column index - Similar question from several years back, but unanswered.

scipy稀疏中的每一行或每一列的Argmax矩阵-最近查询argmaxcsr行的问题.我讨论了一些相同的问题.

Argmax of each row or column in scipy sparse matrix - Recent question seeking argmax for rows of csr. I discuss some of the same issues.

如何加快numpy中的循环速度?-如何使用np.frompyfunc创建ufunc的示例.我不知道结果函数是否具有.reduceat方法.

how to speed up loop in numpy? - example of how to use np.frompyfunc to create a ufunc. I don't know if the resulting function has the .reduceat method.

增加前k个元素的值稀疏矩阵-获取csr的前k个元素(不是按行). argpartition的情况.

Increasing value of top k elements in sparse matrix - get the top k elements of csr (not by row). Case for argpartition.

np.frompyfunc实现的行求和:

In [741]: def foo(a,b):
    return a+b  
In [742]: vfoo=np.frompyfunc(foo,2,1)
In [743]: timeit vfoo.reduceat(A2.data,A2.indptr[:-1],dtype=object).astype(float)
10000 loops, best of 3: 26.2 µs per loop

那是可观的速度.但是我想不出一种写二进制函数(带2个参数)的方法,该函数可以通过归约实现argsort.所以这可能是这个问题的死路.

That's respectable speed. But I can't think of a way of writing a binary function (takes to 2 arguments) that would implement argsort via reduction. So this is probably a deadend for this problem.

这篇关于Scipy.sparse.csr_matrix:如何获取十大值和索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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