tensorflow中next_batch的具体使用


Posted in Python onFebruary 02, 2018

本文介绍了tensorflow中next_batch的具体使用,分享给大家,具体如下:

此处给出了几种不同的next_batch方法,该文章只是做出代码片段的解释,以备以后查看:

def next_batch(self, batch_size, fake_data=False):
  """Return the next `batch_size` examples from this data set."""
  if fake_data:
   fake_image = [1] * 784
   if self.one_hot:
    fake_label = [1] + [0] * 9
   else:
    fake_label = 0
   return [fake_image for _ in xrange(batch_size)], [
     fake_label for _ in xrange(batch_size)
   ]
  start = self._index_in_epoch
  self._index_in_epoch += batch_size
  if self._index_in_epoch > self._num_examples: # epoch中的句子下标是否大于所有语料的个数,如果为True,开始新一轮的遍历
   # Finished epoch
   self._epochs_completed += 1
   # Shuffle the data
   perm = numpy.arange(self._num_examples) # arange函数用于创建等差数组
   numpy.random.shuffle(perm) # 打乱
   self._images = self._images[perm]
   self._labels = self._labels[perm]
   # Start next epoch
   start = 0
   self._index_in_epoch = batch_size
   assert batch_size <= self._num_examples
  end = self._index_in_epoch
  return self._images[start:end], self._labels[start:end]

该段代码摘自mnist.py文件,从代码第12行start = self._index_in_epoch开始解释,_index_in_epoch-1是上一次batch个图片中最后一张图片的下边,这次epoch第一张图片的下标是从 _index_in_epoch开始,最后一张图片的下标是_index_in_epoch+batch, 如果 _index_in_epoch 大于语料中图片的个数,表示这个epoch是不合适的,就算是完成了语料的一遍的遍历,所以应该对图片洗牌然后开始新一轮的语料组成batch开始

def ptb_iterator(raw_data, batch_size, num_steps):
 """Iterate on the raw PTB data.

 This generates batch_size pointers into the raw PTB data, and allows
 minibatch iteration along these pointers.

 Args:
  raw_data: one of the raw data outputs from ptb_raw_data.
  batch_size: int, the batch size.
  num_steps: int, the number of unrolls.

 Yields:
  Pairs of the batched data, each a matrix of shape [batch_size, num_steps].
  The second element of the tuple is the same data time-shifted to the
  right by one.

 Raises:
  ValueError: if batch_size or num_steps are too high.
 """
 raw_data = np.array(raw_data, dtype=np.int32)

 data_len = len(raw_data)
 batch_len = data_len // batch_size #有多少个batch
 data = np.zeros([batch_size, batch_len], dtype=np.int32) # batch_len 有多少个单词
 for i in range(batch_size): # batch_size 有多少个batch
  data[i] = raw_data[batch_len * i:batch_len * (i + 1)]

 epoch_size = (batch_len - 1) // num_steps # batch_len 是指一个batch中有多少个句子
 #epoch_size = ((len(data) // model.batch_size) - 1) // model.num_steps # // 表示整数除法
 if epoch_size == 0:
  raise ValueError("epoch_size == 0, decrease batch_size or num_steps")

 for i in range(epoch_size):
  x = data[:, i*num_steps:(i+1)*num_steps]
  y = data[:, i*num_steps+1:(i+1)*num_steps+1]
  yield (x, y)

第三种方式:

def next(self, batch_size):
    """ Return a batch of data. When dataset end is reached, start over.
    """
    if self.batch_id == len(self.data):
      self.batch_id = 0
    batch_data = (self.data[self.batch_id:min(self.batch_id +
                         batch_size, len(self.data))])
    batch_labels = (self.labels[self.batch_id:min(self.batch_id +
                         batch_size, len(self.data))])
    batch_seqlen = (self.seqlen[self.batch_id:min(self.batch_id +
                         batch_size, len(self.data))])
    self.batch_id = min(self.batch_id + batch_size, len(self.data))
    return batch_data, batch_labels, batch_seqlen

第四种方式:

def batch_iter(sourceData, batch_size, num_epochs, shuffle=True):
  data = np.array(sourceData) # 将sourceData转换为array存储
  data_size = len(sourceData)
  num_batches_per_epoch = int(len(sourceData) / batch_size) + 1
  for epoch in range(num_epochs):
    # Shuffle the data at each epoch
    if shuffle:
      shuffle_indices = np.random.permutation(np.arange(data_size))
      shuffled_data = sourceData[shuffle_indices]
    else:
      shuffled_data = sourceData

    for batch_num in range(num_batches_per_epoch):
      start_index = batch_num * batch_size
      end_index = min((batch_num + 1) * batch_size, data_size)

      yield shuffled_data[start_index:end_index]

迭代器的用法,具体学习Python迭代器的用法

另外需要注意的是,前三种方式只是所有语料遍历一次,而最后一种方法是,所有语料遍历了num_epochs次

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
django通过ajax发起请求返回JSON格式数据的方法
Jun 04 Python
Fabric 应用案例
Aug 28 Python
python多进程中的内存复制(实例讲解)
Jan 05 Python
Tensorflow实现卷积神经网络的详细代码
May 24 Python
python bmp转换为jpg 并删除原图的方法
Oct 25 Python
在python2.7中用numpy.reshape 对图像进行切割的方法
Dec 05 Python
pandas 把数据写入txt文件每行固定写入一定数量的值方法
Dec 28 Python
对django中foreignkey的简单使用详解
Jul 28 Python
解决Python中报错TypeError: must be str, not bytes问题
Apr 07 Python
在jupyter notebook 添加 conda 环境的操作详解
Apr 10 Python
Django视图、传参和forms验证操作
Jul 15 Python
Python如何创建装饰器时保留函数元信息
Aug 07 Python
Python输出各行命令详解
Feb 01 #Python
Python输出由1,2,3,4组成的互不相同且无重复的三位数
Feb 01 #Python
Python实现的视频播放器功能完整示例
Feb 01 #Python
Python线性回归实战分析
Feb 01 #Python
Python使用matplotlib简单绘图示例
Feb 01 #Python
Python解决抛小球问题 求小球下落经历的距离之和示例
Feb 01 #Python
Python 判断 有向图 是否有环的实例讲解
Feb 01 #Python
You might like
php通过function_exists检测函数是否存在的方法
2015/03/18 PHP
Mootools 1.2教程 事件处理
2009/09/15 Javascript
基于Jquery实现的一个图片滚动切换
2012/06/21 Javascript
父节点获取子节点的字符串示例代码
2014/02/26 Javascript
jquery中获得元素尺寸和坐标的方法整理
2014/05/18 Javascript
javascript实现无限级select联动菜单
2015/01/02 Javascript
js获取滚动距离的方法
2015/05/30 Javascript
基于jQuery实现多层次的手风琴效果附源码
2015/09/21 Javascript
理解JavaScript中Promise的使用
2016/01/18 Javascript
jQuery展示表格点击变色、全选、删除
2017/01/05 Javascript
如何正确理解javascript的模块化
2017/03/02 Javascript
分享vue.js devtools遇到一系列问题
2017/10/24 Javascript
three.js中文文档学习之创建场景
2017/11/20 Javascript
element ui里dialog关闭后清除验证条件方法
2018/02/26 Javascript
微信小程序之swiper轮播图中的图片自适应高度的方法
2018/04/23 Javascript
小程序实现列表删除功能
2018/10/30 Javascript
如何在Vue中使用CleaveJS格式化你的输入内容
2018/12/14 Javascript
bootstrap 日期控件 datepicker被弹出框dialog覆盖的解决办法
2019/07/09 Javascript
微信小程序wxs实现吸顶效果
2020/01/08 Javascript
[07:59]2014DOTA2叨叨刀塔 林熊猫称被邀请赛现场盛况震撼
2014/07/21 DOTA
让Python更加充分的使用Sqlite3
2017/12/11 Python
python3中的md5加密实例
2018/05/29 Python
python跳过第一行快速读取文件内容的实例
2018/07/12 Python
Python面向对象进阶学习
2019/05/21 Python
flask框架jinja2模板与模板继承实例分析
2019/08/01 Python
Python  Django 母版和继承解析
2019/08/09 Python
Pretty Little Thing爱尔兰:时尚女性服饰
2017/03/27 全球购物
expedia比利时:预订航班+酒店并省钱
2018/07/13 全球购物
String s = new String(“xyz”);创建了几个String Object?
2015/08/05 面试题
我为自己代言广告词
2014/03/18 职场文书
大学生学习新党章思想汇报
2014/10/25 职场文书
清明节寄语2015
2015/03/23 职场文书
2015年资料员工作总结
2015/04/25 职场文书
2015年幼儿园德育工作总结
2015/05/25 职场文书
详解GaussDB for MySQL性能优化
2021/05/18 MySQL
Python编解码问题及文本文件处理方法详解
2021/06/20 Python