TensorFlow数据IO操作

本文详细介绍了在TensorFlow中如何进行文件读取,包括使用QueueRunner进行多线程读取、文件名队列、不同类型的文件解码(如CSV、JPEG、PNG、TFRecords)以及批处理操作。通过实例展示了如何使用tf.train.batch进行批处理,并手动启动线程进行数据读取。此外,还涵盖了线程管理与协调,确保数据读取的高效和稳定。
摘要由CSDN通过智能技术生成

占位符 & feed_dict搭配使用

QueueRunner

        通用文件读取流程

                图片、二进制数据、TFRecords

一、文件读取流程

        多线程 + 队列

1)构造文件名队列

file_queue = tf.train.string_input_producer(string_tensor,shuffle = True)
# string_tensor: 含有文件名+路径的一阶张量,一般传入一个列表
# shuffle:打乱文件名
# return 文件队列

2)读取与解码

# 读取文本文件,默认按行读取
reader = tf.TextLineReader()

# 读取图片文件
reader = tf.WholeFileReader()

# 读取二进制文件,每个记录为固定字节
# record_bytes:指定每次读取一个样本的字节数
reader = tf.FixedLengthRecordReader(record_bytes)

#读取TFRecords文件
reader = tf.TFRecordReader()

# 读取器实例化后,通过read()方法读取数据
key,value = reader.read(file_queque)
# key:文件名;value:一个样本

# 内容解码
 decoded = tf.decode_csv() # 解码文本文件内容
 decoded = tf.image.decode_jpeg(contents) # 将JPEG图片解码为unit8张量;return:unit8张量,3—D形状[height,width,channels]
 decoded = tf.image.decode_png(contents) #  将PNG图片解码为unit8张量
 decoded = tf.decode_raw() # 解码二进制文件内容,二进制都区委unit8类型
# 解码阶段默认读取为unit8类型,可以通过tf.cast转换

# 图片解码后需要将形状固定才可进行批处理
 decoded.setshape([height,width,channels])
# 修改图片的类型以保证之后的精度
 image_cast = tf.cast(decoded, tf.float32)

3)批处理队列

tf.train.batch(tensors,batch_size,num_threads = 1,capacity=32,name=None)
# 读取指定个数的张量
# tensors:可以是包含张量的列表,批处理的内容放到列表当中
# batch_size: 从队列中读取的批处理大小
# num_threads:进入队列的线程数
# capacity:队列中元素的最大数量
# return:tensors
tf.train.shuffle_batch

手动开启线程


with tf.Session() as sess:
    # 必须开启线程之后才能实现上述步骤
    # 创建线程管理器,对线程进行管理和协调
    coord = tf.train.Coordinator()
    mythread = tf.train.start_queue_runnners(sess=sess,coord=coord)
    
    # 回收线程,线程使用完之后需回收
    coord.request_stop()
    coord.join(mythread)
   
 

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
TensorFlow提供了一个名为tf.Transform的库,用于数据预处理。tf.Transform允许用户使用TensorFlow来转换数据,结合各种数据处理框架,例如Apache Beam等。tf.Transform的主要目的是使数据预处理与模型训练分离,从而使数据预处理更加可重复和可扩展。 tf.Transform的工作流程如下: 1. 定义预处理函数:定义一个Python函数来执行数据预处理操作。 2. 将预处理函数转换为TensorFlow图:使用beam.Map将预处理函数转换为TensorFlow图。 3. 运行转换后的图:使用Apache Beam运行转换后的图,以生成预处理后的数据集。 以下是一个简单的示例,演示如何使用tf.Transform对数据进行预处理: ```python import tensorflow as tf import tensorflow_transform as tft import apache_beam as beam # 定义预处理函数 def preprocessing_fn(inputs): x = inputs['x'] y = inputs['y'] s = inputs['s'] x_centered = x - tft.mean(x) y_normalized = tft.scale_to_0_1(y) s_integerized = tft.compute_and_apply_vocabulary(s) return { 'x_centered': x_centered, 'y_normalized': y_normalized, 's_integerized': s_integerized } # 加载数据集 raw_data = [ {'x': 1, 'y': 2, 's': 'hello'}, {'x': 2, 'y': 3, 's': 'world'}, {'x': 3, 'y': 4, 's': 'hello'} ] raw_data_metadata = tft.tf_metadata.dataset_metadata.DatasetMetadata( tft.tf_metadata.schema_utils.schema_from_feature_spec({ 's': tf.io.FixedLenFeature([], tf.string), 'y': tf.io.FixedLenFeature([], tf.float32), 'x': tf.io.FixedLenFeature([], tf.float32), })) raw_data_metadata = tft.tf_metadata.dataset_metadata.DatasetMetadata( tft.tf_metadata.schema_utils.schema_from_feature_spec({ 's': tf.io.FixedLenFeature([], tf.string), 'y': tf.io.FixedLenFeature([], tf.float32), 'x': tf.io.FixedLenFeature([], tf.float32), })) # 将预处理函数转换为TensorFlow图 with beam.Pipeline() as pipeline: with tft_beam.Context(temp_dir=tempfile.mkdtemp()): coder = tft.coders.ExampleProtoCoder(raw_data_metadata.schema) examples = pipeline | 'CreateExamples' >> beam.Create(raw_data) | 'ToTFExample' >> beam.Map(coder.encode) # 使用tft_beam.AnalyzeAndTransformDataset将预处理函数转换为TensorFlow图 transformed_dataset, transform_fn = ( (examples, raw_data_metadata) | tft_beam.AnalyzeAndTransformDataset(preprocessing_fn)) transformed_data, transformed_metadata = transformed_dataset # 运行转换后的图 transformed_data | 'WriteData' >> beam.io.WriteToTFRecord(output_path) transform_fn | 'WriteTransformFn' >> tft_beam.WriteTransformFn(output_path) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值