逗號分隔值(Comma-Separated Values,CSV,有時也稱為字符分隔值,因為分隔字符也可以不是逗號),其文件以純文本形式存儲表格數據(數字和文本)。純文本意味着該文件是一個字符序列,不含必須像二進制數字那樣被解讀的數據。CSV文件由任意數目的記錄組成,記錄間以某種換行符分隔;每條記錄由字段組成,字段間的分隔符是其它字符或字符串,最常見的是逗號或制表符。通常,所有記錄都有完全相同的字段序列.
import csv
import os
import numpy as np
import random
import requests
# name of data file
# 數據集名稱
birth_weight_file = 'birth_weight.csv'
# download data and create data file if file does not exist in current directory
# 如果當前文件夾下沒有birth_weight.csv數據集則下載dat文件並生成csv文件
if not os.path.exists(birth_weight_file):
birthdata_url = 'https://github.com/nfmcclure/tensorflow_cookbook/raw/master/01_Introduction/07_Working_with_Data_Sources/birthweight_data/birthweight.dat'
birth_file = requests.get(birthdata_url)
birth_data = birth_file.text.split('\r\n')
# split分割函數,以一行作為分割函數,windows中換行符號為'\r\n',每一行后面都有一個'\r\n'符號。
birth_header = birth_data[0].split('\t')
# 每一列的標題,標在第一行,即是birth_data的第一個數據。並使用制表符作為划分。
birth_data = [[float(x) for x in y.split('\t') if len(x) >= 1] for y in birth_data[1:] if len(y) >= 1]
print(np.array(birth_data).shape)
# (189, 9)
# 此為list數據形式不是numpy數組不能使用np,shape函數,但是我們可以使用np.array函數將list對象轉化為numpy數組后使用shape屬性進行查看。
with open(birth_weight_file, "w", newline='') as f:
# with open(birth_weight_file, "w") as f:
writer = csv.writer(f)
writer.writerows([birth_header])
writer.writerows(birth_data)
f.close()
birth_data = []
with open(birth_weight_file) as csvfile:
csv_reader = csv.reader(csvfile) # 使用csv.reader讀取csvfile中的文件
birth_header = next(csv_reader) # 讀取第一行每一列的標題
for row in csv_reader: # 將csv 文件中的數據保存到birth_data中
birth_data.append(row)
birth_data = [[float(x) for x in row] for row in birth_data] # 將數據從string形式轉換為float形式
birth_data = np.array(birth_data) # 將list數組轉化成array數組便於查看數據結構
birth_header = np.array(birth_header)
print(birth_data.shape) # 利用.shape查看結構。
print(birth_header.shape)
#
# (189, 9)
# (9,)
import pandas as pd
csv_data = pd.read_csv('birth_weight.csv') # 讀取訓練數據
print(csv_data.shape) # (189, 9)
N = 5
csv_batch_data = csv_data.tail(N) # 取后5條數據
print(csv_batch_data.shape) # (5, 9)
train_batch_data = csv_batch_data[list(range(3, 6))] # 取這20條數據的3到5列值(索引從0開始)
print(train_batch_data)
# RACE SMOKE PTL
# 184 0.0 0.0 0.0
# 185 0.0 0.0 1.0
# 186 0.0 1.0 0.0
# 187 0.0 0.0 0.0
# 188 0.0 0.0 1.0
'''使用Tensorflow讀取csv數據'''
filename = 'birth_weight.csv'
file_queue = tf.train.string_input_producer([filename]) # 設置文件名隊列,這樣做能夠批量讀取文件夾中的文件
reader = tf.TextLineReader(skip_header_lines=1) # 使用tensorflow文本行閱讀器,並且設置忽略第一行
key, value = reader.read(file_queue)
defaults = [[0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.], [0.]] # 設置列屬性的數據格式
LOW, AGE, LWT, RACE, SMOKE, PTL, HT, UI, BWT = tf.decode_csv(value, defaults)
# 將讀取的數據編碼為我們設置的默認格式
vertor_example = tf.stack([AGE, LWT, RACE, SMOKE, PTL, HT, UI]) # 讀取得到的中間7列屬性為訓練特征
vertor_label = tf.stack([BWT]) # 讀取得到的BWT值表示訓練標簽
# 用於給取出的數據添加上batch_size維度,以批處理的方式讀出數據。可以設置批處理數據大小,是否重復讀取數據,容量大小,隊列末尾大小,讀取線程等屬性。
example_batch, label_batch = tf.train.shuffle_batch([vertor_example, vertor_label], batch_size=10, capacity=100, min_after_dequeue=10)
# 初始化Session
with tf.Session() as sess:
coord = tf.train.Coordinator() # 線程管理器
threads = tf.train.start_queue_runners(coord=coord)
print(sess.run(tf.shape(example_batch))) # [10 7]
print(sess.run(tf.shape(label_batch))) # [10 1]
print(sess.run(example_batch)[3]) # [ 19. 91. 0. 1. 1. 0. 1.]
coord.request_stop()
coord.join(threads)
'''
對於使用所有Tensorflow的I/O操作來說開啟和關閉線程管理器都是必要的操作
with tf.Session() as sess:
coord = tf.train.Coordinator() # 線程管理器
threads = tf.train.start_queue_runners(coord=coord)
# Your code here~
coord.request_stop()
coord.join(threads)
'''
還有其他使用python讀取文件的各種方法,這里介紹三種,不定期進行補充。
本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。