tf API 研读4:Inputs and Readers
来源:互联网 发布:乐视vr 没数据 编辑:程序博客网 时间:2024/05/22 15:55
tensorflow中数据的读入相关类或函数:
占位符(Placeholders)
tf提供一种占位符操作,在执行时需要为其提供数据data。
eg:x = tf.placeholder(tf.float32, shape=(1024, 1024))tf.placeholder_with_default(input, shape, name=None)当输出没有fed时,input通过一个占位符optf.sparse_placeholder(dtype, shape=None, name=None)为一个稀疏tensor插入一个占位符
读取器(Readers)
tf提供一系列读取各种数据格式的类。对于多文件输入,可以使用函数tf.train.string_input_producer,该函数将创建一个保持文件的FIFO队列,以供reader使用。或者如果输入的这些文件名有相雷同的字符串,也可以使用函数tf.train.match_filenames_once。
数据转换(Converting)
tf提供一系列方法将各种格式数据转换为tensor表示。
field_delim=None, name=None)将csv转换为tensor,与tf.TextLineReader搭配使用tf.decode_raw(bytes, out_type,
little_endian=None, name=None)将bytes转换为一个数字向量表示,bytes为一个字符串类型的tensor
与函数 tf.FixedLengthRecordReader搭配使用,详见tf的CIFAR-10例子选取与要输入的文件格式相匹配的reader,并将文件队列提供给reader的读方法( read method)。读方法将返回文件唯一标识的key,以及一个记录(record)(有助于对出现一些另类的records时debug),以及一个标量的字符串值。再使用一个(或多个)解码器(decoder) 或转换操作(conversion ops)将字符串转换为tensor类型。
#读取文件队列,使用reader中read的方法,返回key与valuefilename_queue = tf.train.string_input_producer(["file0.csv", "file1.csv"])reader = tf.TextLineReader()key, value = reader.read(filename_queue)record_defaults = [[1], [1], [1], [1], [1]]col1, col2, col3, col4, col5 = tf.decode_csv( value, record_defaults=record_defaults)features = tf.pack([col1, col2, col3, col4])with tf.Session() as sess: # Start populating the filename queue. coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for i in range(1200): # Retrieve a single instance: example, label = sess.run([features, col5]) coord.request_stop() coord.join(threads)
Example protocol buffer
提供了一些Example protocol buffers,tf所推荐的用于训练样本的数据格式,它们包含特征信息,详情可见。
这是一种与前述将手上现有的各种数据类型转换为支持的格式的方法,这种方法更容易将网络结构与数据集融合或匹配。这种tensorflow所推荐的数据格式是一个包含tf.train.Example protocol buffers (包含特征Features域)的TFRecords文件。
1、获取这种格式的文件方式为,首先将一般的数据格式填入Example protocol buffer中,再将 protocol buffer序列化为一个字符串,然后使用tf.python_io.TFRecordWriter类的相关方法将字符串写入一个TFRecords文件中,参见MNIST例子,将MNIST 数据转换为该类型数据。
2、读取TFRecords格式文件的方法为,使用tf.TFRecordReader读取器和tf.parse_single_example解码器。parse_single_example操作将 example protocol buffers解码为tensor形式。参见MNIST例子
name=None, example_names=None)将一组Example protos解析为tensor的字典形式
解析serialized所给予的序列化的一些Example protos
返回一个由特征keys映射Tensor和SparseTensor值的字典tf.parse_single_example(serialized, features,
name=None, example_names=None)解析一个单独的Example proto,与tf.parse_example方法雷同tf.decode_json_example(json_examples, name=None)将JSON编码的样本记录转换为二进制protocol buffer字符串
#tf.parse_example的使用举例#输入序列化数据如下: serialized = [ features { feature { key: "ft" value { float_list { value: [1.0, 2.0] } } } }, features { feature []}, features { feature { key: "ft" value { float_list { value: [3.0] } } }]#那么输出为一个字典(dict),如下:{"ft": SparseTensor(indices=[[0, 0], [0, 1], [2, 0]], values=[1.0, 2.0, 3.0], shape=(3, 2)) }##########再来看一个例子,给定两个序列化的原始输入样本:[ features { feature { key: "kw" value { bytes_list { value: [ "knit", "big" ] } } } feature { key: "gps" value { float_list { value: [] } } } }, features { feature { key: "kw" value { bytes_list { value: [ "emmy" ] } } } feature { key: "dank" value { int64_list { value: [ 42 ] } } } feature { key: "gps" value { } } }]#相关参数如下:example_names: ["input0", "input1"],features: { "kw": VarLenFeature(tf.string), "dank": VarLenFeature(tf.int64), "gps": VarLenFeature(tf.float32),}#那么有如下输出:{ "kw": SparseTensor( indices=[[0, 0], [0, 1], [1, 0]], values=["knit", "big", "emmy"] shape=[2, 2]), "dank": SparseTensor( indices=[[1, 0]], values=[42], shape=[2, 1]), "gps": SparseTensor( indices=[], values=[], shape=[2, 0]),}##########对于两个样本的输出稠密结果情况[ features { feature { key: "age" value { int64_list { value: [ 0 ] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } }, features { feature { key: "age" value { int64_list { value: [] } } } feature { key: "gender" value { bytes_list { value: [ "f" ] } } } }]#我们可以使用以下参数example_names: ["input0", "input1"],features: { "age": FixedLenFeature([], dtype=tf.int64, default_value=-1), "gender": FixedLenFeature([], dtype=tf.string),}#期望的结果如下{ "age": [[0], [-1]], "gender": [["f"], ["f"]],}
##Example protocol buffer相关使用的例子#将mnist的数据转换为TFRecords文件格式import osimport tensorflow as tffrom tensorflow.contrib.learn.python.learn.datasets import mnistSOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'TRAIN_IMAGES = 'train-images-idx3-ubyte.gz' # MNIST filenamesTRAIN_LABELS = 'train-labels-idx1-ubyte.gz'TEST_IMAGES = 't10k-images-idx3-ubyte.gz'TEST_LABELS = 't10k-labels-idx1-ubyte.gz'tf.app.flags.DEFINE_string('directory', '/tmp/data', 'Directory to download data files and write the ' 'converted result')tf.app.flags.DEFINE_integer('validation_size', 5000, 'Number of examples to separate from the training ' 'data for the validation set.')FLAGS = tf.app.flags.FLAGSdef _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))def convert_to(data_set, name): 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) writer = tf.python_io.TFRecordWriter(filename) for index in range(num_examples): image_raw = images[index].tostring() 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()) writer.close()def main(argv): # Get the data. data_sets = mnist.read_data_sets(FLAGS.directory, dtype=tf.uint8, reshape=False) # 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__': tf.app.run()
队列(Queues)
tensorflow提供了几个队列应用,用来将tf计算图与tensors的阶段流水组织到一起。队列是使用tensorflow计算的一个强大的机制,正如其他Tensorflow的元素一样,一个队列也是tf图中的一个节点(node),它是一个有状态的node,就像一个变量:其他节点可以改变其内容。
我们来看一个简单的例子,如下gif图,我们将创建一个先入先出队列(FIFOQueue)并且将值全设为0,然后我们构建一个图以获取队列出来的元素,对该元素加1操作,并将结果再放入队列末尾。渐渐地,队列中的数字便增加。
该结构通过多个步骤存储tensors,
并且对tensors进行入列(enqueue)与出列(dequeue)操作tf.QueueBase.enqueue(vals, name=None)将一个元素编入该队列中。如果在执行该操作时队列已满,
那么将会阻塞直到元素编入队列之中tf.QueueBase.enqueue_many(vals, name=None)将零个或多个元素编入该队列中tf.QueueBase.dequeue(name=None)将元素从队列中移出。如果在执行该操作时队列已空,
那么将会阻塞直到元素出列,返回出列的tensors的tupletf.QueueBase.dequeue_many(n, name=None)将一个或多个元素从队列中移出tf.QueueBase.size(name=None)计算队列中的元素个数tf.QueueBase.close
(cancel_pending_enqueues=False, name=None)关闭该队列f.QueueBase.dequeue_up_to(n, name=None)从该队列中移出n个元素并将之连接tf.QueueBase.dtypes列出组成元素的数据类型tf.QueueBase.from_list(index, queues)根据queues[index]的参考队列创建一个队列tf.QueueBase.name返回最队列下面元素的名称tf.QueueBase.names返回队列每一个组成部分的名称class tf.FIFOQueue在出列时依照先入先出顺序,其他方法与tf.QueueBase雷同class tf.PaddingFIFOQueue一个FIFOQueue ,同时根据padding支持batching变长的tensorclass tf.RandomShuffleQueue该队列将随机元素出列,其他方法与tf.QueueBase雷同
文件系统的处理(Dealing with the filesystem)
输入管道(Input pipeline)
用于设置输入预取数的管道TF函数,函数 “producer”添加一个队列至图中,同时一个相应用于运行队列中子图(subgraph)的QueueRunner
num_epochs=None, shuffle=True, seed=None, capacity=32,
shared_name=None, summary_name=None, name=None)为一个输入管道输出input_tensor中的多行至一个队列中tf.train.range_input_producer(limit, num_epochs=None,
shuffle=True, seed=None, capacity=32,
shared_name=None, name=None)产生一个从1至limit-1的整数至队列中tf.train.slice_input_producer(tensor_list, num_epochs=None,
shuffle=True, seed=None, capacity=32,
shared_name=None, name=None)对tensor_list中的每一个tensor切片tf.train.string_input_producer(string_tensor, num_epochs=None,
shuffle=True, seed=None, capacity=32,
shared_name=None, name=None)为一个输入管道输出一组字符串(比如文件名)至队列中
在输入管道末端批量打包(Batching at the end of an input pipeline)
该相关函数增添一个队列至图中以将数据一样本打包为batch。它们也会添加 一个QueueRunner,以便执行的已经被填满队列的子图
capacity=32, enqueue_many=False, shapes=None,
dynamic_pad=False, allow_smaller_final_batch=False,
shared_name=None, name=None)在输入的tensors中创建一些tensor数据格式的batch,
若输入为shape[*, x, y, z],那么输出则为[batch_size, x, y, z]
返回一个列表或者一个具有与输入tensors相同类型tensors的字典tf.train.batch_join(tensors_list, batch_size,
capacity=32, enqueue_many=False, shapes=None,
dynamic_pad=False, allow_smaller_final_batch=False,
shared_name=None, name=None)将一个tensors的列表添加至一个队列中以创建样本的batches
len(tensors_list)个线程将启动,
线程i将tensors_list[i]的tensors入列
tensors_list[i1][j]与tensors_list[i2][j]有相同的类型和shapetf.train.shuffle_batch(tensors, batch_size, capacity,
min_after_dequeue, num_threads=1, seed=None,
enqueue_many=False, shapes=None,
allow_smaller_final_batch=False,
shared_name=None, name=None)使用随机乱序的方法创建batches
tensors:用于入列的一个list或者dict
capacity:一个整数,表示队列中元素最大数目tf.train.shuffle_batch_join(tensors_list, batch_size,
capacity, min_after_dequeue, seed=None,
enqueue_many=False, shapes=None,
allow_smaller_final_batch=False,
shared_name=None, name=None)随机乱序的tensors创建batches,
其中tensors_list参数为tensors元组或tensors字典的列表
len(tensors_list)个线程将启动,
线程i将tensors_list[i]的tensors入列
tensors_list[i1][j]与tensors_list[i2][j]有相同的类型和shape
# 一个简单例子,使用tf.train.shuffle_batch创建一个具有32张图像和32个标签的batches.image_batch, label_batch = tf.train.shuffle_batch( [single_image, single_label], batch_size=32, num_threads=4, capacity=50000, min_after_dequeue=10000)
#Batching函数相关例子,以函数tf.train.shuffle_batch为例#为training, evaluation等操作将样本batching,以下代码使用随机顺序打包样本def read_my_file_format(filename_queue): reader = tf.SomeReader() key, record_string = reader.read(filename_queue) example, label = tf.some_decoder(record_string) processed_example = some_processing(example) return processed_example, labeldef input_pipeline(filenames, batch_size, num_epochs=None): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=True) example, label = read_my_file_format(filename_queue) # min_after_dequeue defines how big a buffer we will randomly sample # from -- bigger means better shuffling but slower start up and more # memory used. # capacity must be larger than min_after_dequeue and the amount larger # determines the maximum we will prefetch. Recommendation: # min_after_dequeue + (num_threads + a small safety margin) * batch_size min_after_dequeue = 10000 capacity = min_after_dequeue + 3 * batch_size example_batch, label_batch = tf.train.shuffle_batch( [example, label], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue) return example_batch, label_batch
#如果需要跟多的并行或文件之间的样本乱序操作,可以使用函数tf.train.shuffle_batch_join多实例化readerdef read_my_file_format(filename_queue): # 与上例子相同def input_pipeline(filenames, batch_size, read_threads, num_epochs=None): filename_queue = tf.train.string_input_producer( filenames, num_epochs=num_epochs, shuffle=True) example_list = [read_my_file_format(filename_queue) for _ in range(read_threads)] min_after_dequeue = 10000 capacity = min_after_dequeue + 3 * batch_size example_batch, label_batch = tf.train.shuffle_batch_join( example_list, batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue) return example_batch, label_batch
- tf API 研读4:Inputs and Readers
- tensorflow编程: Inputs and Readers
- tf API 研读2:math
- tf API 研读3:Building Graphs
- tf API 研读5:Data IO
- tf API 研读6:Running Graphs
- tf API 研读1:tf.nn,tf.layers, tf.contrib概述
- Video4Linux2 part 4: inputs and outputs
- mex2 Inputs and Outputs
- Filter Readers and Writers
- c2 Streams Readers and Writers
- TF API
- 171116 Keras-Multiple inputs and outputs
- Tensorflow(r1.4)API--tf.truncated_normal()
- Tensorflow(r1.4)API--tf.nn.conv2d
- Tensorflow(r1.4)API--tf.nn.max_pool
- Tensorflow(r1.4)API--tf.nn.dropout
- Tensorflow(r1.4)API--tf.summary.scalar
- Ubuntu联网安装Mysql
- jQuery3.2
- weex playground手机查看weex项目
- js里的call和apply方法
- [bzoj1751][Usaco2005 qua]Lake Counting
- tf API 研读4:Inputs and Readers
- Js学习之路三 --- 函数传参
- 正则表达式、Object、包装类
- 关于VMware时间不同步的解决方法
- 关于师徒制的一些思考
- swoole 同步task
- Android控件介绍及用法
- 梯度下降(Gradient Descent)
- OpenCV编程->双目标定(一)