python-2.7 - 用户、项目对的稀疏矩阵实现

标签 python-2.7 numpy matrix scipy sparse-matrix

我有一个包含数百万条记录的数据集,其中包含购买了 20,000 件商品子集的 100,000 名用户,其形式为:

<user1, item1>
<user1, item12>
...
<user100,000, item>

我需要跟踪大小矩阵(商品 x 用户)= (20,000 x 100,000),如果用户购买了商品,则为 1,否则为 0。目前我使用的是传统的 numpy 数组,但在后面的步骤中处理它需要很长时间。任何人都可以推荐一种使用 SciPy 稀疏矩阵的有效方法,它仍然允许基于索引搜索矩阵吗?

最佳答案

这是一个解决方案,它构建一个包含 0 和 1 的密集数据透视表,然后创建等效的稀疏矩阵。我选择了lil_matrix ,但存在其他选项。

import numpy as np
from scipy import sparse

ar = np.array([['user1', 'product1'], ['user2', 'product2'], ['user3', 'product3'], ['user3', 'product1']])

rows, r_pos = np.unique(ar[:,0], return_inverse=True)
cols, c_pos = np.unique(ar[:,1], return_inverse=True)

pivot_table = np.zeros((len(rows), len(cols)))
pivot_table[r_pos, c_pos] = 1

print(pivot_table)

# Convert the dense pivot table to a sparse matrix
s = sparse.lil_matrix(pivot_table)

# I can access the non-nul indices using nonzero
print(s.nonzero())

这给出了:

[[ 1.  0.  0.]
 [ 0.  1.  0.]
 [ 1.  0.  1.]]
(array([0, 1, 2, 2], dtype=int32), array([0, 1, 0, 2], dtype=int32))

附录

如果相关,这是另一个不使用 scipy 的解决方案,而是 pandas :

In [34]: import pandas as pd

In [35]: df = pd.DataFrame([['user1', 'product1'], ['user2', 'product2'], ['user3', 'product3'], ['user3', 'product1']], columns = ['user', 'product'])

In [36]: df
Out[36]: 
    user   product
0  user1  product1
1  user2  product2
2  user3  product3
3  user3  product1

In [37]: df.groupby(['user', 'product']).size().unstack(fill_value=0)
Out[37]: 
product  product1  product2  product3
user                                 
user1           1         0         0
user2           0         1         0
user3           1         0         1

此外,请注意这不会计算每个客户购买的产品数量(这可能很有趣,具体取决于您的用例和数据集)。

您仍然可以使用此库搜索您的数据。

关于python-2.7 - 用户、项目对的稀疏矩阵实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40042829/

相关文章:

c# - 如何在 Python 中将所有方法调用委托(delegate)给 C# DLL

python - 用于重复连续元素 block 的 Numpy 向量化函数

python - 使用 .all() 和 any() 获取搜索数组的索引

javascript - 矩阵的 WebGl 内存表示法

c - 如何还原对角读取的 NxN 矩阵?

java - 使用 JTextFields 或 JTextAreas 创建矩阵

python - 无法写入文件

python-2.7 - 如何在Python中准备多级多值训练数据集

Python嵌套if-else只执行else

python - Math.log() 处理数组