当前位置:   article > 正文

TF从文件中读取数据

fif文件读取

从文件中读取数据

在TensorFlow中进行模型训练时,在官网给出的三种读取方式,中最好的文件读取方式就是将利用队列进行文件读取,而且步骤有两步:

  1. 把样本数据写入TFRecords二进制文件
  2. 从队列中读取

TFRecords二进制文件,能够更好的利用内存,更方便的移动和复制,并且不需要单独的标记文件
下面官网给出的,对mnist文件进行操作的code,具体代码请参考:tensorflow-master\tensorflow\examples\how_tos\reading_data\convert_to_records.py
https://www.sogou.com/link?url=DSOYnZeCC_pKZzihDKzFgzQoUkRGi7SFyAyslJcA_SlXxobSKiNyJA..)

生成TFRecords文件

定义主函数,给训练、验证、测试数据集做转换:

  1. def main(unused_argv):
  2. # Get the data.
  3. data_sets = mnist.read_data_sets(FLAGS.directory,
  4. dtype=tf.uint8,
  5. reshape=False,
  6. validation_size=FLAGS.validation_size)
  7. # Convert to Examples and write the result to TFRecords.
  8. convert_to(data_sets.train, 'train')
  9. convert_to(data_sets.validation, 'validation')
  10. convert_to(data_sets.test, 'test')

转换函数的作用convert_to的主要功能是,将数据填入到协议缓冲区,并化为一个字符串,然后写入到TFRecords文件。

  1. def convert_to(data_set, name):
  2. """Converts a dataset to tfrecords."""
  3. images = data_set.images
  4. labels = data_set.labels
  5. num_examples = data_set.num_examples
  6. if images.shape[0] != num_examples:
  7. raise ValueError('Images size %d does not match label size %d.' %
  8. (images.shape[0], num_examples))
  9. rows = images.shape[1] # 28
  10. cols = images.shape[2] # 28
  11. depth = images.shape[3] # 1. 是黑白图像,所以是单通道
  12. filename = os.path.join(FLAGS.directory, name + '.tfrecords')
  13. print('Writing', filename)
  14. writer = tf.python_io.TFRecordWriter(filename)
  15. for index in range(num_examples):
  16. image_raw = images[index].tostring()
  17. # 写入协议缓存区,height,width,depth,label编码成int64类型,image_raw 编码成二进制
  18. example = tf.train.Example(features=tf.train.Features(feature={
  19. 'height': _int64_feature(rows),
  20. 'width': _int64_feature(cols),
  21. 'depth': _int64_feature(depth),
  22. 'label': _int64_feature(int(labels[index])),
  23. 'image_raw': _bytes_feature(image_raw)}))
  24. writer.write(example.SerializeToString()) # 序列化为字符串
  25. writer.close()

编码函数如下:

  1. def _int64_feature(value):
  2. return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
  3. def _bytes_feature(value):
  4. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

完整代码:

  1. import tensorflow as tf
  2. import os
  3. import argparse
  4. import sys
  5. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  6. #1.0 生成TFRecords 文件
  7. from tensorflow.contrib.learn.python.learn.datasets import mnist
  8. FLAGS = None
  9. # 编码函数如下:
  10. def _int64_feature(value):
  11. return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
  12. def _bytes_feature(value):
  13. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  14. def convert_to(data_set, name):
  15. """Converts a dataset to tfrecords."""
  16. images = data_set.images
  17. labels = data_set.labels
  18. num_examples = data_set.num_examples
  19. if images.shape[0] != num_examples:
  20. raise ValueError('Images size %d does not match label size %d.' %
  21. (images.shape[0], num_examples))
  22. rows = images.shape[1] # 28
  23. cols = images.shape[2] # 28
  24. depth = images.shape[3] # 1. 是黑白图像,所以是单通道
  25. filename = os.path.join(FLAGS.directory, name + '.tfrecords')
  26. print('Writing', filename)
  27. writer = tf.python_io.TFRecordWriter(filename)
  28. for index in range(num_examples):
  29. image_raw = images[index].tostring()
  30. # 写入协议缓存区,height,width,depth,label编码成int64类型,image_raw 编码成二进制
  31. example = tf.train.Example(features=tf.train.Features(feature={
  32. 'height': _int64_feature(rows),
  33. 'width': _int64_feature(cols),
  34. 'depth': _int64_feature(depth),
  35. 'label': _int64_feature(int(labels[index])),
  36. 'image_raw': _bytes_feature(image_raw)}))
  37. writer.write(example.SerializeToString()) # 序列化为字符串
  38. writer.close()
  39. def main(unused_argv):
  40. # Get the data.
  41. data_sets = mnist.read_data_sets(FLAGS.directory,
  42. dtype=tf.uint8,
  43. reshape=False,
  44. validation_size=FLAGS.validation_size)
  45. # Convert to Examples and write the result to TFRecords.
  46. convert_to(data_sets.train, 'train')
  47. convert_to(data_sets.validation, 'validation')
  48. convert_to(data_sets.test, 'test')
  49. if __name__ == '__main__':
  50. parser = argparse.ArgumentParser()
  51. parser.add_argument(
  52. '--directory',
  53. type=str,
  54. default='MNIST_data/',
  55. help='Directory to download data files and write the converted result'
  56. )
  57. parser.add_argument(
  58. '--validation_size',
  59. type=int,
  60. default=5000,
  61. help="""\
  62. Number of examples to separate from the training data for the validation
  63. set.\
  64. """
  65. )
  66. FLAGS, unparsed = parser.parse_known_args()
  67. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

运行结束后,在/tmp/data下生成3个文件,即train.tfrecords,validation.tfrecords和test.tfrecords.

从队列中读取

读取TFRecords文件步骤

使用队列读取数TFRecords 文件 数据的步骤

  1. 创建张量,从二进制文件读取一个样本数据
  2. 创建张量,从二进制文件随机读取一个mini-batch
  3. 把每一批张量传入网络作为输入点

TensorFlow使用TFRecords文件训练样本的步骤
在生成文件名的序列中,设定epoch数量
训练时,设定为无穷循环
在读取数据时,如果捕捉到错误,终止

source code:tensorflow-master\tensorflow\examples\how_tos\reading_data\fully_connected_reader.py(1.2.1)
https://blog.csdn.net/fontthrone/article/details/76728083

  1. import tensorflow as tf
  2. import os
  3. # from tensorflow.contrib.learn.python.learn.datasets import mnist
  4. # 注意上面的这个mnist 与 example 中的 mnist 是不同的,本文件中请使用下面的那个 mnist
  5. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
  6. import argparse
  7. import os.path
  8. import sys
  9. import time
  10. from tensorflow.examples.tutorials.mnist import mnist
  11. # Basic model parameters as external flags.
  12. FLAGS = None
  13. # This part of the code is added by FontTian,which comes from the source code of tensorflow.examples.tutorials.mnist
  14. # The MNIST images are always 28x28 pixels.
  15. # IMAGE_SIZE = 28
  16. # IMAGE_PIXELS = IMAGE_SIZE * IMAGE_SIZE
  17. # Constants used for dealing with the files, matches convert_to_records.
  18. TRAIN_FILE = 'train.tfrecords'
  19. VALIDATION_FILE = 'validation.tfrecords'
  20. def read_and_decode(filename_queue):
  21. reader = tf.TFRecordReader()
  22. _, serialized_example = reader.read(filename_queue)
  23. features = tf.parse_single_example(
  24. serialized_example,
  25. # Defaults are not specified since both keys are required.
  26. # 必须写明faetures 中的 key 的名称
  27. features={
  28. 'image_raw': tf.FixedLenFeature([], tf.string),
  29. 'label': tf.FixedLenFeature([], tf.int64),
  30. })
  31. # Convert from a scalar string tensor (whose single string has
  32. # length mnist.IMAGE_PIXELS) to a uint8 tensor with shape
  33. # [mnist.IMAGE_PIXELS].
  34. # 将一个标量字符串张量(其单个字符串的长度是mnist.image像素) # 0 维的Tensor
  35. # 转换为一个带有形状mnist.图像像素的uint8张量。 # 一维的Tensor
  36. image = tf.decode_raw(features['image_raw'], tf.uint8)
  37. # print(tf.shape(image)) # Tensor("input/Shape:0", shape=(1,), dtype=int32)
  38. image.set_shape([mnist.IMAGE_PIXELS])
  39. # print(tf.shape(image)) # Tensor("input/Shape_1:0", shape=(1,), dtype=int32)
  40. # OPTIONAL: Could reshape into a 28x28 image and apply distortions
  41. # here. Since we are not applying any distortions in this
  42. # example, and the next step expects the image to be flattened
  43. # into a vector, we don't bother.
  44. # Convert from [0, 255] -> [-0.5, 0.5] floats.
  45. image = tf.cast(image, tf.float32) * (1. / 255) - 0.5
  46. # print(tf.shape(image)) # Tensor("input/Shape_2:0", shape=(1,), dtype=int32)
  47. # Convert label from a scalar uint8 tensor to an int32 scalar.
  48. label = tf.cast(features['label'], tf.int32)
  49. # print(tf.shape(label)) # Tensor("input/Shape_3:0", shape=(0,), dtype=int32)
  50. return image, label
  51. # 使用 tf.train.shuffle_batch 将前面生成的样本随机化,获得一个最小批次的张量
  52. def inputs(train, batch_size, num_epochs):
  53. """Reads input data num_epochs times.
  54. Args:
  55. train: Selects between the training (True) and validation (False) data.
  56. batch_size: Number of examples per returned batch.
  57. num_epochs: Number of times to read the input data, or 0/None to
  58. train forever.
  59. Returns:
  60. A tuple (images, labels), where:
  61. * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
  62. in the range [-0.5, 0.5].
  63. * labels is an int32 tensor with shape [batch_size] with the true label,
  64. a number in the range [0, mnist.NUM_CLASSES).
  65. Note that an tf.train.QueueRunner is added to the graph, which
  66. must be run using e.g. tf.train.start_queue_runners().
  67. 输入参数:
  68. train: Selects between the training (True) and validation (False) data.
  69. batch_size: 训练的每一批有多少个样本
  70. num_epochs: 读取输入数据的次数, or 0/None 表示永远训练下去
  71. 返回结果:
  72. A tuple (images, labels), where:
  73. * images is a float tensor with shape [batch_size, mnist.IMAGE_PIXELS]
  74. 范围: [-0.5, 0.5].
  75. * labels is an int32 tensor with shape [batch_size] with the true label,
  76. 范围: [0, mnist.NUM_CLASSES).
  77. 注意 : tf.train.QueueRunner 被添加进 graph, 它必须用 tf.train.start_queue_runners() 来启动线程.
  78. """
  79. if not num_epochs: num_epochs = None
  80. filename = os.path.join(FLAGS.train_dir,
  81. TRAIN_FILE if train else VALIDATION_FILE)
  82. with tf.name_scope('input'):
  83. # tf.train.string_input_producer 返回一个 QueueRunner,里面有一个 FIFQueue
  84. filename_queue = tf.train.string_input_producer(
  85. [filename], num_epochs=num_epochs)
  86. # 如果样本数据很大,可以分成若干文件,把文件名列表传入
  87. # Even when reading in multiple threads, share the filename queue.
  88. image, label = read_and_decode(filename_queue)
  89. # Shuffle the examples and collect them into batch_size batches.
  90. # (Internally uses a RandomShuffleQueue.)
  91. # We run this in two threads to avoid being a bottleneck.
  92. images, sparse_labels = tf.train.shuffle_batch(
  93. [image, label], batch_size=batch_size, num_threads=2,
  94. capacity=1000 + 3 * batch_size,
  95. # Ensures a minimum amount of shuffling of examples.
  96. # 留下一部分队列,来保证每次有足够的数据做随机打乱
  97. min_after_dequeue=1000)
  98. return images, sparse_labels
  99. def run_training():
  100. """Train MNIST for a number of steps."""
  101. # Tell TensorFlow that the model will be built into the default Graph.
  102. with tf.Graph().as_default():
  103. # Input images and labels.
  104. images, labels = inputs(train=True, batch_size=FLAGS.batch_size,
  105. num_epochs=FLAGS.num_epochs)
  106. # 构建一个从推理模型来预测数据的图
  107. logits = mnist.inference(images,
  108. FLAGS.hidden1,
  109. FLAGS.hidden2)
  110. # Add to the Graph the loss calculation.
  111. # 定义损失函数
  112. loss = mnist.loss(logits, labels)
  113. # 将模型添加到图操作中
  114. train_op = mnist.training(loss, FLAGS.learning_rate)
  115. # 初始化变量的操作
  116. init_op = tf.group(tf.global_variables_initializer(),
  117. tf.local_variables_initializer())
  118. # Create a session for running operations in the Graph.
  119. # 在图中创建一个用于运行操作的会话
  120. sess = tf.Session()
  121. # 初始化变量,注意:string_input_product 内部创建了一个epoch计数器
  122. sess.run(init_op)
  123. # Start input enqueue threads.
  124. coord = tf.train.Coordinator()
  125. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  126. try:
  127. step = 0
  128. while not coord.should_stop():
  129. start_time = time.time()
  130. # Run one step of the model. The return values are
  131. # the activations from the `train_op` (which is
  132. # discarded) and the `loss` op. To inspect the values
  133. # of your ops or variables, you may include them in
  134. # the list passed to sess.run() and the value tensors
  135. # will be returned in the tuple from the call.
  136. _, loss_value = sess.run([train_op, loss])
  137. duration = time.time() - start_time
  138. # Print an overview fairly often.
  139. if step % 100 == 0:
  140. print('Step %d: loss = %.2f (%.3f sec)' % (step, loss_value,
  141. duration))
  142. step += 1
  143. except tf.errors.OutOfRangeError:
  144. print('Done training for %d epochs, %d steps.' % (FLAGS.num_epochs, step))
  145. finally:
  146. # 通知其他线程关闭
  147. coord.request_stop()
  148. # Wait for threads to finish.
  149. coord.join(threads)
  150. sess.close()
  151. def main(_):
  152. run_training()
  153. if __name__ == '__main__':
  154. parser = argparse.ArgumentParser()
  155. parser.add_argument(
  156. '--learning_rate',
  157. type=float,
  158. default=0.01,
  159. help='Initial learning rate.'
  160. )
  161. parser.add_argument(
  162. '--num_epochs',
  163. type=int,
  164. default=2,
  165. help='Number of epochs to run trainer.'
  166. )
  167. parser.add_argument(
  168. '--hidden1',
  169. type=int,
  170. default=128,
  171. help='Number of units in hidden layer 1.'
  172. )
  173. parser.add_argument(
  174. '--hidden2',
  175. type=int,
  176. default=32,
  177. help='Number of units in hidden layer 2.'
  178. )
  179. parser.add_argument(
  180. '--batch_size',
  181. type=int,
  182. default=100,
  183. help='Batch size.'
  184. )
  185. parser.add_argument(
  186. '--train_dir',
  187. type=str,
  188. default='/tmp/data',
  189. help='Directory with the training data.'
  190. )
  191. FLAGS, unparsed = parser.parse_known_args()
  192. tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

转载于:https://www.cnblogs.com/Ann21/p/10482120.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/249767
推荐阅读
相关标签
  

闽ICP备14008679号