A__*_*__A 3 python memory-management numpy 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])
Run Code Online (Sandbox Code Playgroud)
b tf.Variable在TensorFlow运行时为对象分配900MB这使得3600MB的内存分配.为了节省内存,你可以做这样的事情
a_holder = tf.placeholder(np.float32)
b = tf.Variable(a_holder)
sess.run(b.initializer, feed_dict={a_holder: np.arange(100000000)})
Run Code Online (Sandbox Code Playgroud)
TLDR; 避免创建大常量.