【问题标题】:Efficient way to decompress and multiply sparse arrays in python在python中解压缩和乘以稀疏数组的有效方法
【发布时间】:2013-11-09 01:39:16
【问题描述】:

在数据库中,我有一个压缩频率数组。第一个值表示完整的数组索引,第二个值表示频率。这被压缩为仅非 0 值,因为它非常稀疏 - 少于 5% 的非 0 值。我正在尝试解压缩数组,然后我需要该数组的点积与权重数组来获得总权重。对于较大的阵列,这非常低效。有没有人有更有效的方法来做到这一点?例如,我应该使用 scipy.sparse 并保持compressedfreqs 数组原样吗?或者也许我应该做一个更有效的列表理解而不是循环遍历每个项目?

这是我正在做的一个较小的例子:

import numpy as np

compressedfreqs = [(1,4),(3,2),(9,8)]
weights = np.array([4,4,4,3,3,3,2,2,2,1])

freqs = np.array([0] * 10)
for item in compressedfreqs:
    freqs[item[0]] = item[1]

totalweight =  np.dot(freqs,weights)
print totalweight

【问题讨论】:

    标签: python arrays numpy scipy sparse-matrix


    【解决方案1】:

    您可以使用scipy.sparse 为您处理所有这些:

    >>> import scipy.sparse as sps
    >>> cfq = np.array([(1,4),(3,2),(9,8)])
    >>> cfq_sps = sps.coo_matrix((cfq[:,1], ([0]*len(cfq), cfq[:,0])))
    >>> cfq_sps
    <1x10 sparse matrix of type '<type 'numpy.int32'>'
        with 3 stored elements in COOrdinate format>
    >>> cfq_sps.A # convert to dense array
    array([[0, 4, 0, 2, 0, 0, 0, 0, 0, 8]])
    >>> weights = np.array([4,4,4,3,3,3,2,2,2,1])
    >>> cfq_sps.dot(weights)
    array([30])
    

    如果您不想使用稀疏模块,您可以使用生成器表达式使其工作,尽管可能会更慢:

    >>> sum(k*weights[j] for j,k in cfq)
    30
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-27
      • 2015-12-05
      • 1970-01-01
      • 2013-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多