python - 使用队列 Tensorflow 训练模型

标签 python multithreading machine-learning queue tensorflow

我遵循并改编了 tensorflow 教程,在 tensorflow 中为我的回归问题设计了一个神经网络。但是,由于我的问题的结构(约 300.000 个数据点和使用昂贵的 FTRLOptimizer),即使我的 32 CPU 机器(我没有 GPU)我的问题执行时间也太长。

根据 this comment并通过 htop 快速确认,看来我有一些单线程操作,应该是 feed_dict。

因此,按照建议here ,我尝试使用队列对我的程序进行多线程处理。

我用队列编写了一个简单的代码文件来训练一个模型,如下所示:

import numpy as np
import tensorflow as tf
import threading

#Function for enqueueing in parallel my data
def enqueue_thread():
    sess.run(enqueue_op, feed_dict={x_batch_enqueue: x, y_batch_enqueue: y})

#Set the number of couples (x, y) I use for "training" my model
BATCH_SIZE = 5

#Generate my data where y=x+1+little_noise
x = np.random.randn(10, 1).astype('float32')
y = x+1+np.random.randn(10, 1)/100

#Create the variables for my model y = x*W+b, then W and b should both converge to 1.
W = tf.get_variable('W', shape=[1, 1], dtype='float32')
b = tf.get_variable('b', shape=[1, 1], dtype='float32')

#Prepare the placeholdeers for enqueueing
x_batch_enqueue = tf.placeholder(tf.float32, shape=[None, 1])
y_batch_enqueue = tf.placeholder(tf.float32, shape=[None, 1])

#Create the queue
q = tf.RandomShuffleQueue(capacity=2**20, min_after_dequeue=BATCH_SIZE, dtypes=[tf.float32, tf.float32], seed=12, shapes=[[1], [1]])

#Enqueue operation
enqueue_op = q.enqueue_many([x_batch_enqueue, y_batch_enqueue])

#Dequeue operation
x_batch, y_batch = q.dequeue_many(BATCH_SIZE)

#Prediction with linear model + bias
y_pred=tf.add(tf.mul(x_batch, W), b)

#MAE cost function
cost = tf.reduce_mean(tf.abs(y_batch-y_pred))

learning_rate = 1e-3
train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
available_threads = 1024

#Feed the queue
for i in range(available_threads):
    threading.Thread(target=enqueue_thread).start()

#Train the model
for step in range(1000):
    _, cost_step = sess.run([train_op, cost])
    print(cost_step)
Wf=sess.run(W)
bf=sess.run(b)

此代码不起作用,因为每次调用 x_batch 时,一个 y_batch 也会出队,反之亦然。然后,我不将特征与相应的“结果”进行比较。

有没有简单的方法可以避免这个问题?

最佳答案

我的错误,一切正常。 我被误导了,因为我在算法的每一步都估计了我在不同批处理上的表现,还因为我的模型对于虚拟模型来说太复杂了(我应该有类似 y=W*x 或 y=x+b 的东西)。 然后,当我尝试在控制台中打印时,我在不同的变量上执行了几次 sess.run 并得到了明显不一致的结果。

关于python - 使用队列 Tensorflow 训练模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38633539/

相关文章:

.net - SqlDataReader 抛出 NullReferenceException!什么可能导致此问题以及如何调试?

c++ - 线程处理不同类时,条件变量、互斥量应该在哪里声明?

python - PySpark:如何评估机器学习推荐算法的 AUC?

java - 哪些库已移植到不同的编程语言?

c# - 如何使事件回调进入我的 win 表单线程安全?

machine-learning - 在 Keras 中为序列到序列自动编码器制作解码器模型

machine-learning - 斯坦福NER分类器是如何构建的

python - 为什么我无法在Python中获取sql语句?

python - 迭代 numpy 数组以在字典中使用

matlab - 你如何解决 "undefined function or variable ' mamfis'”?