Scipy coo_matrix.max() 改变数据属性

Scipy coo_matrix.max() alters data attribute

我正在使用开源库 LightFM 构建推荐系统。该库要求某些数据采用稀疏矩阵格式,特别是 scipy coo_matrix。正是在这里,我遇到了奇怪的行为。好像是个bug,但更有可能是我做错了什么。

基本上,我让 LightFM.Dataset 为我构建一个稀疏矩阵,如下所示:

interactions, weights = dataset.build_interactions(data=_get_interactions_data())

方法,build_interactions,returns“两个 COO 矩阵:交互矩阵和相应的权重矩阵”——LightFM Official Doc

当我检查这个稀疏矩阵的内容时(实际上,我使用调试器),像这样:

for i in interactions.data:
    print(i, end=', ')

1, 1, 1, 1, 1, ....

打印了一长串1,说明稀疏矩阵的非零元素只有1

但是,当我第一次检查稀疏矩阵的最大值时,它表明稀疏矩阵中的最大值不是 1,而是 3。此外,在检查之后打印矩阵将打印一长串1s、2s 和 3s。这是代码:

print(interactions.max())
for i in interactions.data:
    print(i, end=', ')

3
1, 1, 3, 2, 1, 2, ...

知道这里发生了什么吗? Python 是 3.6.8。 Scipy 是 1.5.4。 CentOS7.

谢谢。

A​​ 'raw' coo_matrix 可以有重复元素(相同行和列值的重复),但是当转换为 csr 格式进行计算时,这些重复项将被求和。它必须做同样的事情,但就地,为了找到最大值。

In [9]: from scipy import sparse
In [10]: M = sparse.coo_matrix(([1,1,1,1,1,1],([0,0,0,0,0,0],[0,0,1,0,1,2])))
In [11]: M.data
Out[11]: array([1, 1, 1, 1, 1, 1])
In [12]: M.max()
Out[12]: 3
In [13]: M.data
Out[13]: array([3, 2, 1])
In [14]: M
Out[14]: 
<1x3 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in COOrdinate format>

追踪 max 代码我发现它使用 sum_duplicates

In [33]: M = sparse.coo_matrix(([1,1,1,1,1,1],([0,0,0,0,0,0],[0,0,1,0,1,2])))
In [34]: M.data
Out[34]: array([1, 1, 1, 1, 1, 1])
In [35]: M.sum_duplicates?
Signature: M.sum_duplicates()
Docstring:
Eliminate duplicate matrix entries by adding them together

This is an *in place* operation
File:      /usr/local/lib/python3.8/dist-packages/scipy/sparse/coo.py
Type:      method
In [36]: M.sum_duplicates()
In [37]: M.data
Out[37]: array([3, 2, 1])