python - 使用常量初始化时,Tensorflow 使用过多内存

标签 python numpy memory-management tensorflow

最近我发现一个奇怪的事情,Tensorflow 在用常量初始化变量时似乎占用了过多的内存。有人可以帮助我理解下面的示例吗?

$ python -m memory_profiler test.py 
[0 1 2 3 4 5 6 7 8 9]
Filename: test.py

Line #    Mem usage    Increment   Line Contents
================================================
 4  144.531 MiB    0.000 MiB   @profile
 5                             def go():
 6  907.312 MiB  762.781 MiB    a = np.arange(100000000)
 7  910.980 MiB    3.668 MiB    s = tf.Session()
 8 1674.133 MiB  763.152 MiB    b = tf.Variable(a)
 9 3963.000 MiB 2288.867 MiB    s.run(tf.variables_initializer([b]))
10 3963.145 MiB    0.145 MiB    print(s.run(b)[:10])

最佳答案

  • 您在 numpy 数组中存储了 900MB。
  • tf.Variable(a) 等同于 tf.Variable(tf.constant(a))。为了创建这个常量,Python 客户端在 Python 运行时将 900MB 常量附加到 Graph 对象
  • Session.run 触发 TF_ExtendGraph 将图形传输到 TensorFlow C 运行时,另外 900MB
  • session 在 TensorFlow 运行时为 b tf.Variable 对象分配 900MB

这会分配 3600MB 的内存。为了节省内存,您可以改为执行类似的操作

a_holder = tf.placeholder(np.float32)
b = tf.Variable(a_holder)
sess.run(b.initializer, feed_dict={a_holder: np.arange(100000000)})

TLDR;避免创建大常量。

关于python - 使用常量初始化时,Tensorflow 使用过多内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46774127/

相关文章:

numpy - numpy 是否自动针对 raspberry-pi 进行了优化

python/我觉得可以简单写一下,但是我不知道

python - 从 4D 阵列中裁剪图像的不同部分以进行数据增强

Python Fileinput openhook=fileinput.hook_compressed 语法使用

python - 如何在 one-hot 编码的 pandas 数据框中找到列的正索引?

memory-management - 性能顺便说一句。堆堆动态数组

python - numpy数组的多个元素具有相同的id

java - 字符串与字符 []

python - Pandas :选择具有特定月份和日期的所有日期

python - 安全地从 json 获取嵌套列表索引?