[tensorflow] - csv文件读取

    文件流程 csv读取流程 函数的流程
import tensorflow as tf
import os

"""
    tensorflow中csv文件的读取
    1、 先找到文件,构造一个列表
    
    2、 构造一个文件队列
    
    3、 读取(read)队列内容
            csv: 读取一行
            二进制文件: 指定一个样本的bytes读取
            图片文件: 按一张一张的读取
    
    4、 解码(decode)
    tf.decode_csv(records, record_defaults=None,field_delim = None, name=None)
    
    
    5、 批处理(多个样本)
    批处理大小,和数量无关.取决于该批次处理数量的大小
"""


def csvread(filelist):
    """
    读取CSV文件
    :param filelist: 文件路径 + 名字列表
    :return: 读取的内容
    """

    # 1. 构造文件队列
    file_queue = tf.train.string_input_producer(filelist)

    # 2. 构造csv阅读器读取
    reader = tf.TextLineReader()

    key, value = reader.read(file_queue)

    # 3. 对每行内容进行解密
    # record_defaults: 指定每一个样本额每一列的类型,指定默认值 [["None"], [4.0]]
    records = [["None"], ["None"]]
    example, label = tf.decode_csv(value, record_defaults=records)

    # 4. 想要读取多个,需要进行批处理
    example_batch, label_batch = tf.train.batch([example, label], batch_size=9, num_threads=1, capacity=9)
    print(example_batch, label_batch)

    return example_batch, label_batch


if __name__ == "__main__":
    # 1、找到文件,放入列表  路径 + 名字
    file_name = os.listdir("./data/csvdata/")

    filelist = [os.path.join("./data/csvdata", file) for file in file_name]

    # print(file_name)
    example_batch, label_batch = csvread(filelist)

    # 开启会话运行结果
    with tf.Session() as sess:
        # 定义一个线程协调器
        coord = tf.train.Coordinator()

        # 开启读文件的线程
        threads = tf.train.start_queue_runners(sess, coord=coord)

        # 打印读取的内容
        print(sess.run([example_batch, label_batch]))

        # 把程序的图结构写入事件
        filewriter = tf.summary.FileWriter("./summary/", graph=sess.graph)

        # 回收子线程
        coord.request_stop()

        coord.join(threads)
经验分享 程序员 微信小程序 职场和发展