【发布时间】:2017-03-30 17:55:03
【问题描述】:
我有一个应用程序,它应该每 5 秒对图像进行一次并行分类。我想绕过全局解释器锁,所以我尝试使用多处理库而不是多线程。或多或少,我的代码如下所示:
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("/home/aneksteind/tensorflowSource/output_labels.txt")]
# Unpersists graph from file
f = tf.gfile.FastGFile("/home/aneksteind/tensorflowSource/output_graph.pb", 'rb')
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
sess = tf.Session()
mainGraph = sess.graph
# a function that starts a thread for each region of interest to classify
def checkFrames():
timer = threading.Timer(5.0, checkFrames)
timer.daemon = True
timer.start()
if(started):
index = 0
threads = []
for roi in rois:
p = Process(target=containsPlane, args=(frame, roi, index))
p.daemon = True
p.start()
index += 1
def containsPlane(frame, roi, index):
tempGraph = mainGraph
tempSession = tf.Session(graph=tempGraph)
tempTensor = tempSession.graph.get_tensor_by_name('final_result:0')
predictions = tempSession.run(tempTensor, \
{'DecodeJpeg:0': subframe})
...
当我使用线程运行此代码时,它运行得很好。它在第一次分类之前打印出每个初步消息/警告,并且只对每个图像进行分类,但不是并行的。
当我更改为进程时,初步消息/警告会反复出现,并且图像永远不会分类。这可能是由于会话共享某种状态吗?我可以做些什么不同的事情来并行分类多个图像?
【问题讨论】:
-
您不能将
globalvars 与processes一起使用。 Vars 必须在process内,否则您必须使用shared memory。 -
@stovfl 我怎么知道哪个变量是需要成为 multiprocess.Value 的变量?
-
因为 TensorFlow 内部使用 pthreads 我不认为它会与 python 处理包兼容(在存在分叉的情况下线程代码的行为很难调试和理解)。
-
@AlexandrePassos 有没有办法使用 tensorflow 并行运行作业(每个作业都必须运行会话)?
-
如果您启动许多 python 进程并使用相同的集群规范将它们连接到同一设备,它们将共享状态。否则你可以使用 C++ 线程来调用 session.run。
标签: python multithreading python-3.x parallel-processing tensorflow