首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通流shuffle_batch速度

通流shuffle_batch速度
EN

Stack Overflow用户
提问于 2017-01-26 04:09:31
回答 3查看 1.7K关注 0票数 4

我注意到,如果我将训练数据加载到内存中,并将其作为numpy数组提供给图形,与使用相同大小的洗牌批次相比,我的数据有大约1000个实例,那么速度会有很大的差异。

使用内存1000次迭代所需的时间不到几秒钟,但使用一次洗牌批处理几乎需要10分钟。我得到的洗牌批应该是有点慢,但这似乎太慢了。为什么会这样呢?

增加了赏金。关于如何使洗牌的迷你批次更快一些,有什么建议吗?

以下是培训数据:training.csv (巴斯泰宾)

这是我的代码:

shuffle_batch

代码语言:javascript
复制
import numpy as np
import tensorflow as tf

data = np.loadtxt('bounty_training.csv',
    delimiter=',',skiprows=1,usecols = (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))

filename = "test.tfrecords"

with tf.python_io.TFRecordWriter(filename) as writer:
    for row in data:
        features, label = row[:-1], row[-1]
        example = tf.train.Example()
        example.features.feature['features'].float_list.value.extend(features)
        example.features.feature['label'].float_list.value.append(label)
        writer.write(example.SerializeToString())

def read_and_decode_single_example(filename):
    filename_queue = tf.train.string_input_producer([filename],
                                                   num_epochs=None)
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    features = tf.parse_single_example(
        serialized_example,
        features={
            'label': tf.FixedLenFeature([], np.float32),
            'features': tf.FixedLenFeature([14], np.float32)})

    pdiff = features['label']
    avgs = features['features']

    return avgs, pdiff

avgs, pdiff = read_and_decode_single_example(filename)


n_features = 14
batch_size = 1000
hidden_units = 7
lr = .001

avgs_batch, pdiff_batch = tf.train.shuffle_batch(
    [avgs, pdiff], batch_size=batch_size,
    capacity=5000,
    min_after_dequeue=2000)

X = tf.placeholder(tf.float32,[None,n_features])
Y = tf.placeholder(tf.float32,[None,1])

W = tf.Variable(tf.truncated_normal([n_features,hidden_units]))
b = tf.Variable(tf.zeros([hidden_units]))

Wout = tf.Variable(tf.truncated_normal([hidden_units,1]))
bout = tf.Variable(tf.zeros([1]))

hidden1 = tf.matmul(X,W) + b
pred = tf.matmul(hidden1,Wout) + bout

loss = tf.reduce_mean(tf.squared_difference(pred,Y))

optimizer = tf.train.AdamOptimizer(lr).minimize(loss)

with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)

    for step in range(1000):
        x_, y_ = sess.run([avgs_batch,pdiff_batch])

        _, loss_val = sess.run([optimizer,loss],
              feed_dict={X: x_, Y: y_.reshape(batch_size,1)} )

        if step % 100 == 0:
            print(loss_val)


    coord.request_stop()
    coord.join(threads)

整批通过numpy数组

代码语言:javascript
复制
"""
avgs and pdiff loaded into numpy arrays first...
Same model as above
"""
   with tf.Session() as sess:
        init = tf.global_variables_initializer()
        sess.run(init)

        for step in range(1000):
            _, loss_value = sess.run([optimizer,loss],
                    feed_dict={X: avgs,Y: pdiff.reshape(n_instances,1)} )
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-01-29 05:57:00

诀窍是,不要将单个示例输入shuffle_batch,而是使用enqueue_many=True向其提供一个n+1维张量的示例。我发现这条线索非常有用:

TFRecordReader看起来非常慢,多线程读取不起作用。

代码语言:javascript
复制
def get_batch(batch_size):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    batch_list = []
    for i in range(batch_size):
        batch_list.append(serialized_example)

    return [batch_list]

batch_serialized_example = tf.train.shuffle_batch(
 get_batch(batch_size), batch_size=batch_size,
    capacity=100*batch_size,
    min_after_dequeue=batch_size*10,
    num_threads=1, 
    enqueue_many=True)

features = tf.parse_example(
    batch_serialized_example,
    features={
        'label': tf.FixedLenFeature([], np.float32),
        'features': tf.FixedLenFeature([14], np.float32)})

batch_pdiff = features['label']
batch_avgs = features['features']

...
票数 2
EN

Stack Overflow用户

发布于 2017-01-26 04:38:14

在本例中,您每步运行一次会话3次--一次在avgs_batch.eval中,一次用于pdiff_batch.eval,一次用于实际的sess.run调用。这并不能解释减速的严重程度,但你一定要记住这一点。至少,前两个eval调用应该合并为一个sess.run调用。

我怀疑大部分的慢速都来自于TFRecordReader的使用。我并不假装理解tensorflow的内部运作,但您可能会发现我的答案这里很有帮助。

摘要

  • 创建与每个示例相关联的最小数据,即图像文件名、ids,而不是整个图像;
  • tensorflow.python.framework.ops.convert_to_tensor转换为tensorflow ops;
  • 使用tf.train.slice_input_producer获得单个例子的张量;
  • 对单个示例做一些预处理--例如从文件名加载图像;
  • 使用tf.train.batch对它们进行批处理,以将它们分组。
票数 3
EN

Stack Overflow用户

发布于 2017-03-22 13:38:18

当使用队列获取数据时,不应该使用feed_dict。相反,让图形直接依赖于输入数据,即:

  • 删除X和Y PlaceHolders
  • 直接使用您的特性批处理 hidden1 = tf.matmul(avgs_batch,W) +b
  • 同样,在计算损失时,使用标签批处理(pdiff_batch)而不是Y。
  • 最后,保留第二个session.run直接计算损失,不使用feed_dictx_,y_ = sess.run(avgs_batch,pdiff_batch) # _,loss_val =sess.run(优化器,损耗,feed_dict={X: x_,Y: y_.reshape(batch_size,1)} ) _,loss_val =sess.run(优化器,损失)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41866745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档