tensorflow tf.train.batch之数据批量读取方式

yipeiwu_com6年前Python基础

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

然后发现这篇博文说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之数据批量读取方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

解读! Python在人工智能中的作用

人工智能是一种未来性的技术,目前正在致力于研究自己的一套工具。一系列的进展在过去的几年中发生了:无事故驾驶超过300000英里并在三个州合法行驶迎来了自动驾驶的一个里程碑;IBM Was...

详解如何利用Cython为Python代码加速

引言 通常,在 Python 中写循环(特别是多重循环)非常的慢,在文章 /post/133807.htm中,我们的元胞自动机的状态更新函数 update_state 使用了两重循环,所...

浅谈python中真正关闭socket的方法

close方法可以释放一个连接的资源,但是不是立即释放,如果想立即释放,那么在close之前使用shutdown方法 shut_rd() -------关闭接受消息通道 shut_wr(...

Python的设计模式编程入门指南

Python的设计模式编程入门指南

有没有想过设计模式到底是什么?通过本文可以看到设计模式为什么这么重要,通过几个Python的示例展示为什么需要设计模式,以及如何使用。 设计模式是什么? 设计模式是经过总结、优化的,对我...

Python实现短网址ShortUrl的Hash运算实例讲解

本文实例讲述了Python实现短网址ShortUrl的Hash运算方法。分享给大家供大家参考。具体如下: shorturl实现常见的做法都是将原始Url存储到数据库,由数据库返回一个对应...