【问题标题】:Efficient list operations高效的列表操作
【发布时间】:2016-02-13 00:22:27
【问题描述】:

我有一个大矩阵(1,017,209 行),我需要从中读出元素,对它们进行操作,并将结果收集到列表中。当我在 10,000 行甚至 100,000 行上执行此操作时,它会在合理的时间内完成,但 1,000,000 不会。这是我的代码:

import pandas as pd

data = pd.read_csv('scaled_train.csv', index_col=False, header=0)
new = data.as_matrix()

def vectorized_id(j):
    """Return a 1115-dimensional unit vector with a 1.0 in the j-1'th position
    and zeroes elsewhere.  This is used to convert the store ids (1...1115)
    into a corresponding desired input for the neural network.
    """
    j = j - 1    
    e = [0] * 1115
    e[j] = 1.0
    return e

def vectorized_day(j):
    """Return a 7-dimensional unit vector with a 1.0 in the j-1'th position
    and zeroes elsewhere.  This is used to convert the days (1...7)
    into a corresponding desired input for the neural network.
    """
    j = j - 1
    e = [0] * 7
    e[j] = 1.0
    return e

list_b = []
list_a = []

for x in xrange(0,1017209):
    a1 = vectorized_id(new[x][0])
    a2 = vectorized_day(new[x][1])
    a3 = [new[x][5]]
    a = a1 + a2 + a3
    b = new[x][3]
    list_a.append(a)
    list_b.append(b)

是什么让它在这种规模上变慢(瓶颈是什么)?有办法优化吗?

【问题讨论】:

  • 你查看new[x]四次。
  • 你有多少内存?你用了很多。
  • 您一次只需要一行,但似乎将整个文件读入内存。
  • 正如@user2357112 所说,您正在使用大量内存。 list_a 的每个元素长度为 1115 + 7 + 1 = 1123,list_a 有 1017209 个元素。因此,您尝试存储大约 1k x 1m = 1g 个数字。因此,内存消耗很容易在 4 GB、8 GB 左右。而且大部分只是零,所以你应该以某种方式利用这种稀疏性。

标签: python list function append


【解决方案1】:

有几点:

  1. 不要一次读入整个文件,你似乎没有做任何需要多行的事情。
  2. 看看使用csv.reader 加载您的数据。
  3. 真的停止在巨大的new 列表中建立索引。

【讨论】:

  • @Rishi 确实,我遇到了内存问题。我开始使用 csv.reader 但它仍然无法正常工作,在第 320,000 行左右,我的内存使用率为 95%,它基本上停止了。我认为 vectorized_id() 会导致问题,因为它为每一行提供了一个 1115 长度的向量。所以它会产生一个 Rishi 提到的几个 GB 的列表,对吗?然后我想我应该将中间结果保存在硬盘上,并清空内存。关于如何做到这一点的任何提示?
  • 正如@Rishi 提到的,您正在使用大量内存。如果您确实需要拥有正在生成的所有记录,则可能需要将它们写入文件并稍后在需要时重新加载文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-07
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多