Python 张量流与穿线
下面是来自Tensorflow网站的简单mnist教程(即单层softmax),我尝试通过多线程培训步骤扩展该教程:Python 张量流与穿线,python,multithreading,tensorflow,Python,Multithreading,Tensorflow,下面是来自Tensorflow网站的简单mnist教程(即单层softmax),我尝试通过多线程培训步骤扩展该教程: from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf import threading # Training loop executed in each thread def training_func(): while True: batch = m
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import threading
# Training loop executed in each thread
def training_func():
while True:
batch = mnist.train.next_batch(100)
global_step_val,_ = sess.run([global_step, train_step], feed_dict={x: batch[0], y_: batch[1]})
print("global step: %d" % global_step_val)
if global_step_val >= 4000:
break
# create session and graph
sess = tf.Session()
x = tf.placeholder(tf.float32, shape=[None, 784])
y_ = tf.placeholder(tf.float32, shape=[None, 10])
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
global_step = tf.Variable(0, name="global_step")
y = tf.matmul(x,W) + b
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))
inc = global_step.assign_add(1)
with tf.control_dependencies([inc]):
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# initialize graph and create mnist loader
sess.run(tf.global_variables_initializer())
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# create workers and execute threads
workers = []
for _ in range(8):
t = threading.Thread(target=training_func)
t.start()
workers.append(t)
for t in workers:
t.join()
# evaluate accuracy of the model
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels},
session=sess))
我一定是遗漏了什么,因为下面的8个线程会产生不一致的结果(精度约为0.1),而使用1个线程只能获得预期的精度(约为0.92)。有人知道我的错误吗?谢谢 请注意,不幸的是,使用python的
线程化
并没有创建真正的并行性,因为存在以下问题。所以这里发生的是,您将有多个线程,它们都在同一个CPU上运行,实际上它们是顺序运行的。因此,我建议在Tensorflow中使用协调器。有关协调员的更多信息,请参见:
最后,我建议你说:
with tf.device('/cpu:0'):
your code should go here... 'for the first thread'
然后将另一个cpu用于另一个线程,依此类推。。。
希望这个答案能让你感觉良好 您知道TF图是由高度并行的引擎编译和执行的。如果您在单线程培训期间查看CPU利用率,您将看到所有内核都在接受负载,而不仅仅是一个。您希望通过编写培训线程来完成什么?我希望你看到的问题来自多个线程在没有任何控制的情况下更新权重和覆盖彼此的更改。我的目标是加快昂贵的培训。我知道TF真正是并行的,但也可以通过多线程获得加速-例如在上面的示例中,范围(1)为所有内核提供15-20%的使用率,而范围(16)为60-80%的使用率。我怀疑我的问题确实来自不受控制的并发权重更新。然而,它与我的示例代码(l.319到l.340)类似,但我不明白为什么在他们的情况下可以这样做。也许他们的培训op(word2vec.neg_train)在内部管理这些并发更新?只是看到了答案,还没有测试它,但信息看起来很相关,谢谢回答:)我现在投票,如果它解决了问题,我会选择答案(当我有时间测试:)