【问题标题】:How to create iterate through a large list of list in python efficiently?如何有效地在python中创建一个大列表的迭代?
【发布时间】:2014-07-07 23:43:12
【问题描述】:

我的数据是这样的:

data = {'x':Counter({'a':1,'b':45}), 'y':Counter({'b':1, 'c':212})}

我的标签是data 的键,而内部字典的键是特征:

all_features = ['a','b','c']
all_labels = ['x','y']

我需要这样创建列表列表:

[[data[label][feat] for feat in all_features] for label in all_labels]

[出]:

[[1, 45, 0], [0, 1, 212]]

我的 len(all_features) 约为 5,000,000,len(all_labels) 约为 100,000

最终目的是创建scipy稀疏矩阵,例如:

from collections import Counter
from scipy.sparse import csc_matrix
import numpy as np


all_features = ['a','b','c']
all_labels = ['x','y']

csc_matrix(np.array([[data[label][feat] for feat in all_features] for label in all_labels]))

但是循环遍历一个大列表是相当低效的。

那么如何有效地查看大列表?

是否有其他方法可以从 data 创建 scipy 矩阵,而无需遍历所有特征和标签?

【问题讨论】:

  • 我看不出如果您使用纯 python,列表创建本身会更快,因为字典查找已经是常数时间。您是否尝试过使用元素的静态类型(例如 Cython?)这样,您可能可以在初始化 numpy 数组时避免对列表元素进行类型检查(但我不确定这是否是第一个瓶颈地点)
  • 我对@9​​87654331@/scipy 的了解不够多,无法评论如何正确“矢量化”您的操作,但您正在实现一个包含 500 十亿个的列表> 元素之前将其提供给 numpy.看看给 np.fromiter 一个生成器表达式是否对你来说更快。
  • 使用operator.itemgetter 获得了一个快 100 毫秒的解决方案,但我认为这对于非常大的数据集来说是不够的。 db.tt/jMDAxs7i

标签: python list matrix scipy nested-lists


【解决方案1】:

根据您的经验,将字典转换为 numpy 或 scipy 数组并不太有趣。如果您事先知道all_featuresall_labels,则最好从一开始就使用scipy 稀疏COO 矩阵来保持计数。

无论是否可行,您都希望按排序顺序保留要素和标签列表,以加快查找速度。所以我将假设以下内容不会改变任何一个数组:

all_features = np.array(all_features)
all_labels = np.array(all_labels)
all_features.sort()
all_labels.sort()

让我们按照它们在字典中的存储顺序提取data 中的标签,并查看all_labels 中的每个项目落在哪里:

labels = np.fromiter(data.iterkeys(), all_labels.dtype, len(data))
label_idx = np.searchsorted(all_labels, labels)

现在让我们计算每个标签有多少特征,并从中计算出稀疏数组中非零项的数量:

label_features = np.fromiter((len(c) for c in data.iteritems()), np.intp,
                             len(data))
indptr = np.concatenate(([0], np.cumsum(label_features)))
nnz = indptr[-1]

现在,我们提取每个标签的特征,以及它们对应的计数

import itertools
features_it = itertools.chain(*(c.iterkeys() for c in data.itervalues()))
features = np.fromiter(features_it, all_features.dtype, nnz)
feature_idx = np.searchsorted(all_features, features)
counts_it = itertools.chain(*(c.itervalues() for c in data.itervalues()))
counts = np.fromiter(counts_it, np.intp, nnz)

有了我们所拥有的,我们可以直接创建一个CSR矩阵,标签为行,特征为列:

sps_data = csr_matrix((counts, feature_idx, indptr),
                      shape=(len(all_labels), len(all_features)))

唯一的问题是这个稀疏数组的行不是按照all_labels 的顺序,而是按照它们在迭代data 时出现的顺序。但是我们有 feature_idx 告诉我们每个标签在哪里结束,我们可以通过以下方式重新排列行:

sps_data = sps_data[np.argsort(label_idx)]

是的,它很混乱,令人困惑,而且可能不是很快,但它确实有效,并且比您在问题中提出的内存效率要高得多:

>>> sps_data.A
array([[  1,  45,   0],
       [  0,   1, 212]], dtype=int64)
>>> all_labels
array(['x', 'y'], 
      dtype='<S1')
>>> all_features
array(['a', 'b', 'c'], 
      dtype='<S1')

【讨论】:

  • 注意itertools.chain.from_iterable的存在。
【解决方案2】:

数据集非常大,所以我认为构造一个临时的 numpy 数组是不切实际的(如果使用 32 位整数,则 1e5 x 5e6 矩阵将需要约 2 TB 的内存)。

我假设您知道标签数量的上限。

代码可能如下所示:

import scipy.sparse
n_rows = len(data.keys())
max_col = int(5e6)
temp_sparse = scipy.sparse.lil_matrix((n_rows, max_col), dtype='int')

for i, (features, counts) in enumerate(data.iteritems()):
    for label, n in counts.iteritem():
        j = label_pos[label]
        temp_sparse[i, j] = n
csc_matrix = temp_sparse.csc_matrix(temp_matrix)

label_pos 返回标签的列索引。 如果结果证明使用字典来存储硬盘数据库应该做的 500 万个标签的索引是不切实际的。 字典可以在线创建,因此不需要事先了解所有标签。

遍历 100,000 个特征需要合理的时间,所以我认为如果数据集足够稀疏,这个解决方案可以工作。祝你好运!

【讨论】:

    【解决方案3】:

    还有其他方法可以从数据中创建 scipy 矩阵而无需循环 通过所有功能和标签?

    我认为没有任何捷径可以减少查找的总数。您从 Counters 字典(一个 dict 子类)开始,因此两个嵌套级别都是无序集合。将它们按所需顺序放回的唯一方法是对每个数据点进行data[label][feat] 查找。

    通过确保每个标签只执行一次data[label] 查找,您可以将时间大致缩短一半:

    >>> counters = [data[label] for label in all_labels]
    >>> [[counter[feat] for feat in all_features] for counter in counters]
    [[1, 45, 0], [0, 1, 212]]
    

    您也可以尝试通过使用 map() 而不是列表推导来加快运行时间(映射可以利用内部 length_hint 来预先调整结果数组的大小):

    >>> [map(counter.__getitem__, all_features) for counter in counters]
    [[1, 45, 0], [0, 1, 212]]
    

    最后,确保在函数内运行代码(CPython 中的局部变量查找比全局变量查找更快):

    def f(data, all_features, all_labels):
        counters = [data[label] for label in all_labels]
        return [map(counter.__getitem__, all_features) for counter in counters]
    

    【讨论】:

      猜你喜欢
      • 2020-10-20
      • 1970-01-01
      • 2012-01-05
      • 1970-01-01
      • 2013-09-03
      • 2015-07-07
      • 1970-01-01
      • 2021-08-09
      • 2019-09-22
      相关资源
      最近更新 更多