Tensorlfow 数据读取之TFRecords

#coding=utf-8
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Converts MNIST data to TFRecords file format with Example protos."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import os
import sys

import tensorflow as tf

from tensorflow.contrib.learn.python.learn.datasets import mnist

FLAGS = None

#value must be type of int64
#把值转化为int64形的list,再转化为feature
def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

#value mstbe be type of Byte which can be generated by ndarry.tostring
#把值转化为byte形的list,再转化为feature
def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))def convert_to(data_set, name): """Converts a dataset to tfrecords."""
  #images 和 labels都是numpy数组
  images = data_set.images
  labels = data_set.labels
  num_examples = data_set.num_examples

  if images.shape[0] != num_examples:
    raise ValueError('Images size %d does not match label size %d.' %
                     (images.shape[0], num_examples))
  rows = images.shape[1]
  cols = images.shape[2]
  depth = images.shape[3]

  filename = os.path.join(FLAGS.directory, name + '.tfrecords')
  print('Writing', filename)
  #tfrecordwriter
  writer = tf.python_io.TFRecordWriter(filename)
  #通过for循环不断地把example(样本写入tfrecords文件
  for index in range(num_examples):
    #to binary_file
    image_raw = images[index].tostring()
    #Example is composed of features
    #Example里面包含有很多Features(字典类型)。每个Feature包含name,及对应的values(int64,float,byte类型)
    example = tf.train.Example(features=tf.train.Features(feature={
        'height': _int64_feature(rows),
        'width': _int64_feature(cols),
        'depth': _int64_feature(depth),
        'label': _int64_feature(int(labels[index])),
        'image_raw': _bytes_feature(image_raw)}))
    writer.write(example.SerializeToString()) #Serialize to string type
  writer.close()


def main(unused_argv):
  # Get the data.
  data_sets = mnist.read_data_sets(FLAGS.directory,
                                   dtype=tf.uint8,
                                   reshape=False,
                                   validation_size=FLAGS.validation_size)

  # Convert to Examples and write the result to TFRecords.
  convert_to(data_sets.train, 'train')
  convert_to(data_sets.validation, 'validation')
  convert_to(data_sets.test, 'test')


if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--directory',
      type=str,
      default='/tmp/data',
      help='Directory to download data files and write the converted result'
  )
  parser.add_argument(
      '--validation_size',
      type=int,
      default=5000,
      help="""\
      Number of examples to separate from the training data for the validation
      set.\
      """
  )
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorFlow是一个开源的机器学习框架,通常用于创建神经网络模型。在训练模型之前,需要准备好数据集,本文将介绍如何使用TensorFlow来读取数据。 TensorFlow提供了多种读取数据的方法,其中最常用的是使用tf.data模块。首先,我们需要定义一个数据集对象,并通过读取文件的方式将数据加载进来。TensorFlow支持多种文件格式,如csv、txt、json、tfrecord等,可以根据自己的需求选择合适的格式。 加载数据后,我们可以对数据进行一些预处理,比如做数据增强、进行归一化等操作。预处理完数据后,我们需要将数据转化为张量类型,并将其打包成batch。通过这种方式,我们可以在每次训练中同时处理多个数据。 随后,我们可以使用tf.data.Dataset中的shuffle()函数打乱数据集顺序,防止模型只学习到特定顺序下的模式,然后使用batch()函数将数据划分成批次。最后,我们可以使用repeat()函数让数据集每次可以被使用多次,达到更好的效果。 在TensorFlow中,我们可以通过输入函数将数据集传入模型中,使模型能够直数据集中读取数据。使用输入函数还有一个好处,即能够在模型训练时动态地修改数据的内容,特别是在使用esimator模块进行模型训练时,输入函数是必须要的。 总结一下,在TensorFlow中读取数据的流程如下:定义数据集对象-读取文件-预处理数据-打包数据为batch-打乱数据集-划分批次数据-重复数据集-使用输入函数读取数据。 在实际应用过程中,我们还可以通过其他方式来读取数据,如使用numpy、pandas等工具库,也可以自定义数据集类来处理数据。无论使用何种方式,读取数据都是机器学习训练中重要的一步,需要仔细处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值