国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Tensorflow分批量讀取數據教程

2020-02-15 21:20:21
字體:
來源:轉載
供稿:網友

之前的博客里使用tf讀取數據都是每次fetch一條記錄,實際上大部分時候需要fetch到一個batch的小批量數據,在tf中這一操作的明顯變化就是tensor的rank發生了變化,我目前使用的人臉數據集是灰度圖像,因此大小是92*112的,所以最開始fetch拿到的圖像數據集經過reshape之后就是一個rank為2的tensor,大小是92*112的(如果考慮通道,也可以reshape為rank為3的,即92*112*1)。如果加入batch,比如batch大小為5,那么拿到的tensor的rank就變成了3,大小為5*92*112。

下面規則化的寫一下讀取數據的一般流程,按照官網的實例,一般把讀取數據拆分成兩個大部分,一個是函數專門負責讀取數據和解碼數據,一個函數則負責生產batch。

import tensorflow as tfdef read_data(fileNameQue):  reader = tf.TFRecordReader()  key, value = reader.read(fileNameQue)  features = tf.parse_single_example(value, features={'label': tf.FixedLenFeature([], tf.int64),                            'img': tf.FixedLenFeature([], tf.string),})  img = tf.decode_raw(features["img"], tf.uint8)  img = tf.reshape(img, [92,112]) # 恢復圖像原始大小  label = tf.cast(features["label"], tf.int32)  return img, labeldef batch_input(filename, batchSize):  fileNameQue = tf.train.string_input_producer([filename], shuffle=True)  img, label = read_data(fileNameQue) # fetch圖像和label  min_after_dequeue = 1000  capacity = min_after_dequeue+3*batchSize  # 預取圖像和label并隨機打亂,組成batch,此時tensor rank發生了變化,多了一個batch大小的維度  exampleBatch,labelBatch = tf.train.shuffle_batch([img, label],batch_size=batchSize, capacity=capacity,                           min_after_dequeue=min_after_dequeue)  return exampleBatch,labelBatchif __name__ == "__main__":  init = tf.initialize_all_variables()  exampleBatch, labelBatch = batch_input("./data/faceTF.tfrecords", batchSize=10)  with tf.Session() as sess:    sess.run(init)    coord = tf.train.Coordinator()    threads = tf.train.start_queue_runners(coord=coord)    for i in range(100):      example, label = sess.run([exampleBatch, labelBatch])      print(example.shape)    coord.request_stop()    coord.join(threads)

讀取數據和解碼數據與之前基本相同,針對不同格式數據集使用不同閱讀器和解碼器即可,后面是產生batch,核心是tf.train.shuffle_batch這個函數,它相當于一個蓄水池的功能,第一個參數代表蓄水池的入水口,也就是逐個讀取到的記錄,batch_size自然就是batch的大小了,capacity是蓄水池的容量,表示能容納多少個樣本,min_after_dequeue是指出隊操作后還可以供隨機采樣出批量數據的樣本池大小,顯然,capacity要大于min_after_dequeue,官網推薦:min_after_dequeue + (num_threads + a small safety margin) * batch_size,還有一個參數就是num_threads,表示所用線程數目。

min_after_dequeue這個值越大,隨機采樣的效果越好,但是消耗的內存也越大。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平果县| 卫辉市| 义乌市| 桐乡市| 百色市| 高尔夫| 华亭县| 广水市| 盖州市| 安龙县| 宁都县| 耒阳市| 都兰县| 张家港市| 拜城县| 峨边| 安多县| 伽师县| 株洲市| 琼海市| 建宁县| 乌海市| 甘孜县| 齐齐哈尔市| 德格县| 张家港市| 江安县| 开原市| 濮阳市| 云龙县| 满城县| 盘锦市| 科技| 商洛市| 鹿泉市| 左云县| 萍乡市| 兴隆县| 五峰| 清水河县| 芦溪县|