【发布时间】: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