温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tensorflow tf.train.batch之数据批量读取的示例分析

发布时间:2021-07-26 10:26:10 来源:亿速云 阅读:111 作者:小新 栏目:开发技术

这篇文章给大家分享的是有关tensorflow tf.train.batch之数据批量读取的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

在进行大量数据训练神经网络的时候,可能需要批量读取数据。于是参考了这篇文章的代码,结果发现数据一直批量循环输出,不会在数据的末尾自动停止。

然后发现这篇博文说slice_input_producer()这个函数有一个形参num_epochs,通过设置它的值就可以控制全部数据循环输出几次。

于是我设置之后出现以下的报错:

tensorflow.python.framework.errors_impl.FailedPreconditionError: Attempting to use uninitialized value input_producer/input_producer/limit_epochs/epochs

     [[Node: input_producer/input_producer/limit_epochs/CountUpTo = CountUpTo[T=DT_INT64, _class=["loc:@input_producer/input_producer/limit_epochs/epochs"], limit=2, _device="/job:localhost/replica:0/task:0/cpu:0"](input_producer/input_producer/limit_epochs/epochs)]]

找了好久,都不知道为什么会错,于是只好去看看slice_input_producer()函数的源码,结果在源码中发现作者说这个num_epochs如果不是空的话,就是一个局部变量,需要先调用global_variables_initializer()函数初始化。

于是我调用了之后,一切就正常了,特此记录下来,希望其他人遇到的时候能够及时找到原因。

哈哈,这是笔者第一次通过阅读源码解决了问题,心情还是有点小激动。啊啊,扯远了,上最终成功的代码:

import pandas as pd
import numpy as np
import tensorflow as tf


def generate_data():
  num = 25
  label = np.asarray(range(0, num))
  images = np.random.random([num, 5])
  print('label size :{}, image size {}'.format(label.shape, images.shape))
  return images,label

def get_batch_data():
  label, images = generate_data()
  input_queue = tf.train.slice_input_producer([images, label], shuffle=False,num_epochs=2)
  image_batch, label_batch = tf.train.batch(input_queue, batch_size=5, num_threads=1, capacity=64,allow_smaller_final_batch=False)
  return image_batch,label_batch


images,label = get_batch_data()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(tf.local_variables_initializer())#就是这一行
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess,coord)
try:
  while not coord.should_stop():
    i,l = sess.run([images,label])
    print(i)
    print(l)
except tf.errors.OutOfRangeError:
  print('Done training')
finally:
  coord.request_stop()
coord.join(threads)
sess.close()

感谢各位的阅读!关于“tensorflow tf.train.batch之数据批量读取的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI