Python 基于队列张量流的列车模型

Python 基于队列张量流的列车模型,python,multithreading,machine-learning,queue,tensorflow,Python,Multithreading,Machine Learning,Queue,Tensorflow,通过遵循和修改tensorflow教程,我在tensorflow中为我的回归问题设计了一个神经网络。然而,由于我的问题的结构(约300000个数据点和昂贵的FTRL优化器的使用),即使使用32个CPU机器(我没有GPU),我的问题也花了太长时间才得以执行 根据htop的快速确认,似乎我有一些单线程操作,应该是feed_dict 因此,正如前面提到的,我尝试使用队列来多线程处理我的程序 我编写了一个带有queue的简单代码文件来训练模型,如下所示: import numpy as np impor

通过遵循和修改tensorflow教程,我在tensorflow中为我的回归问题设计了一个神经网络。然而,由于我的问题的结构(约300000个数据点和昂贵的FTRL优化器的使用),即使使用32个CPU机器(我没有GPU),我的问题也花了太长时间才得以执行

根据htop的快速确认,似乎我有一些单线程操作,应该是feed_dict

因此,正如前面提到的,我尝试使用队列来多线程处理我的程序

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

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_批时,一个y_批也会退出队列,反之亦然。然后,我不会将特征与相应的“结果”进行比较


有什么简单的方法可以避免这个问题吗?

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

尽管您的问题已经解决,但我还是想向您展示代码中的一点低效。当您创建随机随机序列时,您指定了
capacity=2**20
。在所有队列中:

可存储在此数据库中的元素数上限 排队

队列将尝试在队列中放入尽可能多的元素,直到达到此限制。所有这些元素都在吞噬你的公羊。如果每个元素仅由1个字节组成,那么队列将占用1Mb的数据。如果您的队列中有10Kb的图像,您将消耗10Gb的RAM

这是非常浪费的,尤其是因为队列中不需要这么多元素。您需要确保的是您的队列永远不会为空。所以,找到一个合理的队列容量,不要使用大量的数据