Numpy/Scipy:内存消耗每次迭代线性增加

3

当运行以下代码时:

import numpy as np
import scipy.sparse
import time

def test():
    m = 10000
    n = 10000 
    for i in range(5):
        A = scipy.sparse.random(m, n, density=0.1, format='csr')
        x = np.random.randn(n)
        Ax = A.dot(x)
        time.sleep(2)

if __name__ == "__main__":
    test()

我观察到内存消耗呈线性增长,达到了>4.8GB!

我用以下函数进行了再次测试:

def test2():
    m = 10000
    n = 10000
    for i in range(5):
        print(i)
        A = np.random.rand(m, n)
        x = np.random.randn(A.shape[1])
        Ax = A.dot(x)
        time.sleep(2)

内存消耗呈线性增长,达到了> 800Mb。

我有两个问题:

  1. 为什么每次迭代内存消耗会呈线性增长?没有声明新变量……

  2. 为什么在第一个测试中,即使矩阵是稀疏的(只有0.1密度),内存消耗也比第二个测试高得多?

感谢您的回答!

1个回答

1

1. 因为所有的变量声明都在一个未嵌套的for...循环中,所以它们会在每次迭代中重新运行,每行代码对总内存使用量产生不同的线性增量(O(n))。另外,由于没有释放内存的操作,如在迭代后进行delete操作,因此内存使用量会从之前的迭代中递增。下面是def test()的内存分析结果。

|Line|  |Mem usage|    |Increment|   |Line Contents|
-----------------------------------------------------
     5   1844.9 MiB   1844.9 MiB   def test():
     6   1844.9 MiB      0.0 MiB       m = 10000
     7   1844.9 MiB      0.0 MiB       n = 10000 
     8   4518.7 MiB      0.0 MiB       for i in range(5):
     9   4518.7 MiB    763.7 MiB           A = scipy.sparse.random(m, n, density=0.1, format='csr')
    10   4518.7 MiB      0.0 MiB           x = np.random.randn(n)
    11   4518.7 MiB      0.0 MiB           Ax = A.dot(x)
    12   4518.7 MiB      0.0 MiB           time.sleep(2)

我认为两个函数占用内存不同的原因在于numpy数据结构相比于scipy更加优化,即它们占用的空间更少。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接