1. 程式人生 > >有關於tensorflow的.TFRecords 檔案怎麼樣來生成和讀取操作

有關於tensorflow的.TFRecords 檔案怎麼樣來生成和讀取操作

下面將介紹如何生成和讀取tfrecords檔案:

首先介紹tfrecords檔案的生成,直接上程式碼:

from random import shuffle import numpy as np import glob import tensorflow as tf import cv2 import sys import os   # 因為我裝的是CPU版本的,執行起來會有'warning',解決方法入下,眼不見為淨~ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'   shuffle_data = True image_path = '/path/to/image/*.jpg'   # 取得該路徑下所有圖片的路徑,type(addrs)= list addrs = glob.glob(image_path) # 標籤資料的獲得具體情況具體分析,type(labels)= list labels = ...   # 這裡是打亂資料的順序 if shuffle_data:     c = list(zip(addrs, labels))     shuffle(c)     addrs, labels = zip(*c)   # 按需分割資料集 train_addrs = addrs[0:int(0.7*len(addrs))] train_labels = labels[0:int(0.7*len(labels))]   val_addrs = addrs[int(0.7*len(addrs)):int(0.9*len(addrs))] val_labels = labels[int(0.7*len(labels)):int(0.9*len(labels))]   test_addrs = addrs[int(0.9*len(addrs)):] test_labels = labels[int(0.9*len(labels)):]   # 上面不是獲得了image的地址麼,下面這個函式就是根據地址獲取圖片 def load_image(addr):  # A function to Load image     img = cv2.imread(addr)     img = cv2.resize(img, (224, 224), interpolation=cv2.INTER_CUBIC)     img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)     # 這裡/255是為了將畫素值歸一化到[0,1]     img = img / 255.     img = img.astype(np.float32)     return img   # 將資料轉化成對應的屬性 def _int64_feature(value):       return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))     def _bytes_feature(value):     return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))     def _float_feature(value):     return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))   # 下面這段就開始把資料寫入TFRecods檔案   train_filename = '/path/to/train.tfrecords'  # 輸出檔案地址   # 建立一個writer來寫 TFRecords 檔案 writer = tf.python_io.TFRecordWriter(train_filename)   for i in range(len(train_addrs)):     # 這是寫入操作視覺化處理     if not i % 1000:         print('Train data: {}/{}'.format(i, len(train_addrs)))         sys.stdout.flush()     # 載入圖片     img = load_image(train_addrs[i])       label = train_labels[i]       # 建立一個屬性(feature)     feature = {'train/label': _int64_feature(label),                'train/image': _bytes_feature(tf.compat.as_bytes(img.tostring()))}       # 建立一個 example protocol buffer     example = tf.train.Example(features=tf.train.Features(feature=feature))       # 將上面的example protocol buffer寫入檔案     writer.write(example.SerializeToString())   writer.close() sys.stdout.flush()

接下來介紹tfrecords檔案的讀取:

import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import os   os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' data_path = 'train.tfrecords'  # tfrecords 檔案的地址     with tf.Session() as sess:     # 先定義feature,這裡要和之前建立的時候保持一致     feature = {         'train/image': tf.FixedLenFeature([], tf.string),         'train/label': tf.FixedLenFeature([], tf.int64)     }     # 建立一個佇列來維護輸入檔案列表     filename_queue = tf.train.string_input_producer([data_path], num_epochs=1)       # 定義一個 reader ,讀取下一個 record     reader = tf.TFRecordReader()     _, serialized_example = reader.read(filename_queue)       # 解析讀入的一個record     features = tf.parse_single_example(serialized_example, features=feature)       # 將字串解析成影象對應的畫素組     image = tf.decode_raw(features['train/image'], tf.float32)       # 將標籤轉化成int32     label = tf.cast(features['train/label'], tf.int32)       # 這裡將圖片還原成原來的維度     image = tf.reshape(image, [224, 224, 3])       # 你還可以進行其他一些預處理....       # 這裡是建立順序隨機 batches(函式不懂的自行百度)     images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, min_after_dequeue=10)       # 初始化     init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())     sess.run(init_op)       # 啟動多執行緒處理輸入資料     coord = tf.train.Coordinator()     threads = tf.train.start_queue_runners(coord=coord)       ....         #關閉執行緒     coord.request_stop()     coord.join(threads)     sess.close()