我已经训练了3个模型,现在正在运行代码,依次加载3个检查点中的每一个并使用它们运行预测。我正在使用GPU。
加载第一个模型时,它会预先分配整个GPU内存(我希望通过它来处理第一批数据)。但是它不会在完成时卸载内存。加载第二个模型时,同时使用tf.reset_default_graph()
和with tf.Graph().as_default()
仍会从第一个模型中完全消耗GPU内存,然后第二个模型将内存不足。
除了使用Python子进程或多进程解决该问题(我通过Google搜索找到的唯一解决方案)以外,还有其他方法可以解决此问题吗?
python大神给出的解决方案
2016年6月的git问题(https://github.com/tensorflow/tensorflow/issues/1727)表示存在以下问题:
目前,GPUDevice中的分配器属于ProcessState,
本质上是全局单例。第一次使用GPU
初始化它,并在进程关闭时释放自身。
因此,唯一的解决方法是使用进程并在计算后将其关闭。
示例代码:
import tensorflow as tf
import multiprocessing
import numpy as np
def run_tensorflow():
n_input = 10000
n_classes = 1000
# Create model
def multilayer_perceptron(x, weight):
# Hidden layer with RELU activation
layer_1 = tf.matmul(x, weight)
return layer_1
# Store layers weight & bias
weights = tf.Variable(tf.random_normal([n_input, n_classes]))
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
pred = multilayer_perceptron(x, weights)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(100):
batch_x = np.random.rand(10, 10000)
batch_y = np.random.rand(10, 1000)
sess.run([optimizer, cost], feed_dict={x: batch_x, y: batch_y})
print "finished doing stuff with tensorflow!"
if __name__ == "__main__":
# option 1: execute code with extra process
p = multiprocessing.Process(target=run_tensorflow)
p.start()
p.join()
# wait until user presses enter key
raw_input()
# option 2: just execute the function
run_tensorflow()
# wait until user presses enter key
raw_input()
因此,如果您在创建的进程中调用函数run_tensorflow()
并关闭该进程(选项1),则会释放内存。如果仅运行run_tensorflow()
(选项2),则在函数调用后不会释放内存。
我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…
Python pytz时区函数返回的时区为9分钟 - python由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…
有没有一种方法可以有效地矢量化图像上的Tensorflow操作? - pythonTensorflow有大量的变换,可以应用于表示图像([高度,宽度,深度])(例如tf.image.rot90()或tf.image.random_flip_left_right())的3D张量。我知道它们应与队列一起使用,因此它们只能在一个图像上运行。但是,是否有一种方法可以对操作进行矢量化处理,以将4D张量([batch_size,height,widt…
用大写字母拆分字符串,但忽略AAA Python Regex - python我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…
如何打印浮点数的全精度[Python] - python我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…