TensorFlow------讀取CSV文件實例


TensorFlow之讀取CSV文件實例:

import tensorflow as tf
import os


def csvread(filelist):
    '''
    讀取CSV文件
    :param filename:  路徑+文件名的列表
    :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)

    # batch_size跟隊列,數據的數量沒有影響,只決定這批次取多少數據
    # 4. 想要讀取多個數據,就需要批處理
    example_batch,label_batch = tf.train.batch([example,label],batch_size=9,num_threads=1,capacity=9)
    # print(example,label)
    return example_batch,label_batch

if __name__ == '__main__':
    # 找到文件,構建列表
    filename = os.listdir('./data/csvdata/')

    # 拼接路徑 重新組成列表
    filelist = [os.path.join('./data/csvdata/',file) for file in filename]

    # 調用函數傳參
    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]))


        # 回收子線程
        coord.request_stop()

        coord.join(threads)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM