Tensorflow數(shù)據(jù)讀取有三種方式:
- Preloaded data: 預(yù)加載數(shù)據(jù)
- Feeding: Python產(chǎn)生數(shù)據(jù),再把數(shù)據(jù)喂給后端,。
- Reading from file: 從文件中直接讀取
這三種有讀取方式有什么區(qū)別呢,? 我們首先要知道TensorFlow(TF)是怎么樣工作的。
TF的核心是用C++寫的,,這樣的好處是運(yùn)行快,,缺點(diǎn)是調(diào)用不靈活。而Python恰好相反,,所以結(jié)合兩種語(yǔ)言的優(yōu)勢(shì),。涉及計(jì)算的核心算子和運(yùn)行框架是用C++寫的,并提供API給Python,。Python調(diào)用這些API,,設(shè)計(jì)訓(xùn)練模型(Graph),再將設(shè)計(jì)好的Graph給后端去執(zhí)行,。簡(jiǎn)而言之,,Python的角色是Design,,C++是Run。
一,、預(yù)加載數(shù)據(jù):
- import tensorflow as tf
- # 設(shè)計(jì)Graph
- x1 = tf.constant([2, 3, 4])
- x2 = tf.constant([4, 0, 1])
- y = tf.add(x1, x2)
- # 打開(kāi)一個(gè)session --> 計(jì)算y
- with tf.Session() as sess:
- print sess.run(y)
二,、python產(chǎn)生數(shù)據(jù),再將數(shù)據(jù)喂給后端
- import tensorflow as tf
- # 設(shè)計(jì)Graph
- x1 = tf.placeholder(tf.int16)
- x2 = tf.placeholder(tf.int16)
- y = tf.add(x1, x2)
- # 用Python產(chǎn)生數(shù)據(jù)
- li1 = [2, 3, 4]
- li2 = [4, 0, 1]
- # 打開(kāi)一個(gè)session --> 喂數(shù)據(jù) --> 計(jì)算y
- with tf.Session() as sess:
- print sess.run(y, feed_dict={x1: li1, x2: li2})
說(shuō)明:在這里x1, x2只是占位符,,沒(méi)有具體的值,,那么運(yùn)行的時(shí)候去哪取值呢?這時(shí)候就要用到sess.run() 中的feed_dict 參數(shù),,將Python產(chǎn)生的數(shù)據(jù)喂給后端,,并計(jì)算y。
這兩種方案的缺點(diǎn):
1,、預(yù)加載:將數(shù)據(jù)直接內(nèi)嵌到Graph中,,再把Graph傳入Session中運(yùn)行,。當(dāng)數(shù)據(jù)量比較大時(shí),,Graph的傳輸會(huì)遇到效率問(wèn)題。
2,、用占位符替代數(shù)據(jù),,待運(yùn)行的時(shí)候填充數(shù)據(jù)。
前兩種方法很方便,,但是遇到大型數(shù)據(jù)的時(shí)候就會(huì)很吃力,,即使是Feeding,中間環(huán)節(jié)的增加也是不小的開(kāi)銷,,比如數(shù)據(jù)類型轉(zhuǎn)換等等,。最優(yōu)的方案就是在Graph定義好文件讀取的方法,讓TF自己去從文件中讀取數(shù)據(jù),,并解碼成可使用的樣本集,。
三、從文件中讀取,,簡(jiǎn)單來(lái)說(shuō)就是將數(shù)據(jù)讀取模塊的圖搭好
1,、準(zhǔn)備數(shù)據(jù),構(gòu)造三個(gè)文件,A.csv,B.csv,C.csv
- $ echo -e "Alpha1,A1\nAlpha2,A2\nAlpha3,A3" > A.csv
- $ echo -e "Bee1,B1\nBee2,B2\nBee3,B3" > B.csv
- $ echo -e "Sea1,C1\nSea2,C2\nSea3,C3" > C.csv
2,、單個(gè)Reader,,單個(gè)樣本
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- # 生成一個(gè)先入先出隊(duì)列和一個(gè)QueueRunner,生成文件名隊(duì)列
- filenames = ['A.csv', 'B.csv', 'C.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- # 定義Reader
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- # 定義Decoder
- example, label = tf.decode_csv(value, record_defaults=[['null'], ['null']])
- #example_batch, label_batch = tf.train.shuffle_batch([example,label], batch_size=1, capacity=200, min_after_dequeue=100, num_threads=2)
- # 運(yùn)行Graph
- with tf.Session() as sess:
- coord = tf.train.Coordinator() #創(chuàng)建一個(gè)協(xié)調(diào)器,管理線程
- threads = tf.train.start_queue_runners(coord=coord) #啟動(dòng)QueueRunner, 此時(shí)文件名隊(duì)列已經(jīng)進(jìn)隊(duì),。
- for i in range(10):
- print example.eval(),label.eval()
- coord.request_stop()
- coord.join(threads)
說(shuō)明:這里沒(méi)有使用tf.train.shuffle_batch,,會(huì)導(dǎo)致生成的樣本和label之間對(duì)應(yīng)不上,亂序了,。生成結(jié)果如下:
Alpha1 A2
Alpha3 B1
Bee2 B3
Sea1 C2
Sea3 A1
Alpha2 A3
Bee1 B2
Bee3 C1
Sea2 C3
Alpha1 A2
解決方案:用tf.train.shuffle_batch,那么生成的結(jié)果就能夠?qū)?yīng)上,。
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- # 生成一個(gè)先入先出隊(duì)列和一個(gè)QueueRunner,生成文件名隊(duì)列
- filenames = ['A.csv', 'B.csv', 'C.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- # 定義Reader
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- # 定義Decoder
- example, label = tf.decode_csv(value, record_defaults=[['null'], ['null']])
- example_batch, label_batch = tf.train.shuffle_batch([example,label], batch_size=1, capacity=200, min_after_dequeue=100, num_threads=2)
- # 運(yùn)行Graph
- with tf.Session() as sess:
- coord = tf.train.Coordinator() #創(chuàng)建一個(gè)協(xié)調(diào)器,管理線程
- threads = tf.train.start_queue_runners(coord=coord) #啟動(dòng)QueueRunner, 此時(shí)文件名隊(duì)列已經(jīng)進(jìn)隊(duì)。
- for i in range(10):
- e_val,l_val = sess.run([example_batch, label_batch])
- print e_val,l_val
- coord.request_stop()
- coord.join(threads)
3,、單個(gè)Reader,多個(gè)樣本,主要也是通過(guò)tf.train.shuffle_batch來(lái)實(shí)現(xiàn)
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- filenames = ['A.csv', 'B.csv', 'C.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- example, label = tf.decode_csv(value, record_defaults=[['null'], ['null']])
- # 使用tf.train.batch()會(huì)多加了一個(gè)樣本隊(duì)列和一個(gè)QueueRunner,。
- #Decoder解后數(shù)據(jù)會(huì)進(jìn)入這個(gè)隊(duì)列,再批量出隊(duì),。
- # 雖然這里只有一個(gè)Reader,,但可以設(shè)置多線程,相應(yīng)增加線程數(shù)會(huì)提高讀取速度,,但并不是線程越多越好,。
- example_batch, label_batch = tf.train.batch(
- [example, label], batch_size=5)
- with tf.Session() as sess:
- coord = tf.train.Coordinator()
- threads = tf.train.start_queue_runners(coord=coord)
- for i in range(10):
- e_val,l_val = sess.run([example_batch,label_batch])
- print e_val,l_val
- coord.request_stop()
- coord.join(threads)
說(shuō)明:下面這種寫法,提取出來(lái)的batch_size個(gè)樣本,,特征和label之間也是不同步的
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- filenames = ['A.csv', 'B.csv', 'C.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- example, label = tf.decode_csv(value, record_defaults=[['null'], ['null']])
- # 使用tf.train.batch()會(huì)多加了一個(gè)樣本隊(duì)列和一個(gè)QueueRunner,。
- #Decoder解后數(shù)據(jù)會(huì)進(jìn)入這個(gè)隊(duì)列,再批量出隊(duì),。
- # 雖然這里只有一個(gè)Reader,,但可以設(shè)置多線程,相應(yīng)增加線程數(shù)會(huì)提高讀取速度,,但并不是線程越多越好,。
- example_batch, label_batch = tf.train.batch(
- [example, label], batch_size=5)
- with tf.Session() as sess:
- coord = tf.train.Coordinator()
- threads = tf.train.start_queue_runners(coord=coord)
- for i in range(10):
- print example_batch.eval(), label_batch.eval()
- coord.request_stop()
- coord.join(threads)
說(shuō)明:輸出結(jié)果如下:可以看出feature和label之間是不對(duì)應(yīng)的
['Alpha1'
'Alpha2' 'Alpha3' 'Bee1' 'Bee2'] ['B3' 'C1' 'C2' 'C3' 'A1']
['Alpha2' 'Alpha3' 'Bee1' 'Bee2' 'Bee3'] ['C1' 'C2' 'C3' 'A1' 'A2']
['Alpha3' 'Bee1' 'Bee2' 'Bee3' 'Sea1'] ['C2' 'C3' 'A1' 'A2' 'A3']
4、多個(gè)reader,,多個(gè)樣本
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- filenames = ['A.csv', 'B.csv', 'C.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- record_defaults = [['null'], ['null']]
- #定義了多種解碼器,每個(gè)解碼器跟一個(gè)reader相連
- example_list = [tf.decode_csv(value, record_defaults=record_defaults)
- for _ in range(2)] # Reader設(shè)置為2
- # 使用tf.train.batch_join(),,可以使用多個(gè)reader,并行讀取數(shù)據(jù),。每個(gè)Reader使用一個(gè)線程,。
- example_batch, label_batch = tf.train.batch_join(
- example_list, batch_size=5)
- with tf.Session() as sess:
- coord = tf.train.Coordinator()
- threads = tf.train.start_queue_runners(coord=coord)
- for i in range(10):
- e_val,l_val = sess.run([example_batch,label_batch])
- print e_val,l_val
- coord.request_stop()
- coord.join(threads)
tf.train.batch 與tf.train.shuffle_batch 函數(shù)是單個(gè)Reader讀取,但是可以多線程,。tf.train.batch_join 與tf.train.shuffle_batch_join 可設(shè)置多Reader讀取,,每個(gè)Reader使用一個(gè)線程。至于兩種方法的效率,,單Reader時(shí),,2個(gè)線程就達(dá)到了速度的極限。多Reader時(shí),,2個(gè)Reader就達(dá)到了極限,。所以并不是線程越多越快,甚至更多的線程反而會(huì)使效率下降,。
5,、迭代控制,設(shè)置epoch參數(shù),,指定我們的樣本在訓(xùn)練的時(shí)候只能被用多少輪
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- filenames = ['A.csv', 'B.csv', 'C.csv']
- #num_epoch: 設(shè)置迭代數(shù)
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False,num_epochs=3)
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- record_defaults = [['null'], ['null']]
- #定義了多種解碼器,每個(gè)解碼器跟一個(gè)reader相連
- example_list = [tf.decode_csv(value, record_defaults=record_defaults)
- for _ in range(2)] # Reader設(shè)置為2
- # 使用tf.train.batch_join(),,可以使用多個(gè)reader,,并行讀取數(shù)據(jù)。每個(gè)Reader使用一個(gè)線程,。
- example_batch, label_batch = tf.train.batch_join(
- example_list, batch_size=1)
- #初始化本地變量
- init_local_op = tf.initialize_local_variables()
- with tf.Session() as sess:
- sess.run(init_local_op)
- coord = tf.train.Coordinator()
- threads = tf.train.start_queue_runners(coord=coord)
- try:
- while not coord.should_stop():
- e_val,l_val = sess.run([example_batch,label_batch])
- print e_val,l_val
- except tf.errors.OutOfRangeError:
- print('Epochs Complete!')
- finally:
- coord.request_stop()
- coord.join(threads)
- coord.request_stop()
- coord.join(threads)
在迭代控制中,,記得添加tf.initialize_local_variables() ,官網(wǎng)教程沒(méi)有說(shuō)明,,但是如果不初始化,,運(yùn)行就會(huì)報(bào)錯(cuò)。
=========================================================================================對(duì)于傳統(tǒng)的機(jī)器學(xué)習(xí)而言,,比方說(shuō)分類問(wèn)題,,[x1
x2 x3]是feature。對(duì)于二分類問(wèn)題,label經(jīng)過(guò)one-hot編碼之后就會(huì)是[0,1]或者[1,0],。一般情況下,,我們會(huì)考慮將數(shù)據(jù)組織在csv文件中,一行代表一個(gè)sample。然后使用隊(duì)列的方式去讀取數(shù)據(jù)
說(shuō)明:對(duì)于該數(shù)據(jù),前三列代表的是feature,,因?yàn)槭欠诸悊?wèn)題,后兩列就是經(jīng)過(guò)one-hot編碼之后得到的label
使用隊(duì)列讀取該csv文件的代碼如下:
- #-*- coding:utf-8 -*-
- import tensorflow as tf
- # 生成一個(gè)先入先出隊(duì)列和一個(gè)QueueRunner,生成文件名隊(duì)列
- filenames = ['A.csv']
- filename_queue = tf.train.string_input_producer(filenames, shuffle=False)
- # 定義Reader
- reader = tf.TextLineReader()
- key, value = reader.read(filename_queue)
- # 定義Decoder
- 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])
- label = tf.pack([col4,col5])
- example_batch, label_batch = tf.train.shuffle_batch([features,label], batch_size=2, capacity=200, min_after_dequeue=100, num_threads=2)
- # 運(yùn)行Graph
- with tf.Session() as sess:
- coord = tf.train.Coordinator() #創(chuàng)建一個(gè)協(xié)調(diào)器,,管理線程
- threads = tf.train.start_queue_runners(coord=coord) #啟動(dòng)QueueRunner, 此時(shí)文件名隊(duì)列已經(jīng)進(jìn)隊(duì)。
- for i in range(10):
- e_val,l_val = sess.run([example_batch, label_batch])
- print e_val,l_val
- coord.request_stop()
- coord.join(threads)
輸出結(jié)果如下:
說(shuō)明:
record_defaults = [[1], [1], [1], [1], [1]]
代表解析的模板,每個(gè)樣本有5列,,在數(shù)據(jù)中是默認(rèn)用‘,,’隔開(kāi)的,,然后解析的標(biāo)準(zhǔn)是[1],,也即每一列的數(shù)值都解析為整型。[1.0]就是解析為浮點(diǎn),,['null']解析為string類型
|