tensorflow資料讀取和處理
阿新 • • 發佈:2018-12-13
檔案匹配
["file0", "file1"]
或[("file%d" % i) for i in range(2)]
files = tf.train.match_filenames_once("C:/path/to/data.tfrecords-*")
讀取檔案佇列
二進位制檔案,每一個畫素點的代表佔用一個byte
的檔案,所以在以二進位制儲存的圖片中,圖片總共的畫素點表示一張圖片的大小
tf.train.string_input_producer()
傳入以一個檔案列表,系統會自動生成檔名的佇列
num_epochs: 使用佇列的次數
shufflue: 對傳入的檔案列表進行打亂
*注意:只使用tf.train.string_input_producer()
tf.train.start_queue_runers
後才會使停滯的資料流動起來,程式不會陷入等待狀態。
batch 輸出佇列
深入tensorflow
讀取
tf.wholeFileReader()
讀取佇列中的檔案佇列中的檔案,讀取整個檔案,如果一個檔案中有多個檔案,則不能使用wholeFileReader,讀取一個檔案中的多個檔案使用 tf.FIxedLengthRecordReader()(已固定的大小讀取檔案中)
tf.FIxedLengthRecordReader()
每次一固定的大小讀取一個檔案中的片段
TFrecorder
製作
# open TFRecord file
writer = tf.python_io.TFRecordWriter('%s.tfrecord' %'test')
# 這裡我們將會寫3個樣本,每個樣本里有4個feature:標量,向量,矩陣,張量
for i in range(3):
# 建立字典
features={}
# 寫入標量,型別Int64,由於是標量,所以"value=[scalars[i]]" 變成list
features['scalar'] = tf.train.Feature(int64_list=tf.train.Int64List( value=[scalars[i]]))
# 寫入向量,型別float,本身就是list,所以"value=vectors[i]"沒有中括號
features['vector'] = tf.train.Feature(float_list = tf.train.FloatList(value=vectors[i]))
# 寫入矩陣,型別float,本身是矩陣,一種方法是將矩陣flatten成list
features['matrix'] = tf.train.Feature(float_list = tf.train.FloatList(value=matrices[i].reshape(-1)))
# 然而矩陣的形狀資訊(2,3)會丟失,需要儲存形狀資訊,隨後可轉回原形狀
features['matrix_shape'] = tf.train.Feature(int64_list = tf.train.Int64List(value=matrices[i].shape))
# 寫入張量,型別float,本身是三維張量,另一種方法是轉變成字元型別儲存,隨後再轉回原型別
features['tensor']= tf.train.Feature(bytes_list=tf.train.BytesList(value=[tensors[i].tostring()]))
# 儲存丟失的形狀資訊(806,806,3)
features['tensor_shape'] = tf.train.Feature(int64_list = tf.train.Int64List(value=tensors[i].shape))
# 將存有所有feature的字典送入tf.train.Features中
tf_features = tf.train.Features(feature= features)
# 再將其變成一個樣本example
tf_example = tf.train.Example(features = tf_features)
# 序列化該樣本
tf_serialized = tf_example.SerializeToString()
# write
writer.write(tf_serialized)
# close
writer.close()
載入
def parse_function(example_proto):
# example_proto,tf_serialized
dics = {'scalar': tf.FixedLenFeature(shape=(), dtype=tf.int64, default_value=None),
# when parse the example, shape below can be used as reshape, for example reshape (3,) to (1,3)
'vector': tf.FixedLenFeature(shape=(1,3), dtype=tf.float32),
# we can use VarLenFeature, but it returns SparseTensor
'matrix': tf.VarLenFeature(dtype=dtype('float32')),
'matrix_shape': tf.FixedLenFeature(shape=(2,), dtype=tf.int64),
# tensor在寫入時 使用了toString(),shape是()
# we first set the type as tf.string, then change to its original type: tf.uint8
'tensor': tf.FixedLenFeature(shape=(), dtype=tf.string),
'tensor_shape': tf.FixedLenFeature(shape=(3,), dtype=tf.int64)}
# parse all features in a single example according to the dics
parsed_example = tf.parse_single_example(example_proto, dics)
# decode string
parsed_example['tensor'] = tf.decode_raw(parsed_example['tensor'], tf.uint8)
# sparse_tensor_to_dense
parsed_example['matrix'] = tf.sparse_tensor_to_dense(parsed_example['matrix'])
# reshape matrix
parsed_example['matrix'] = tf.reshape(parsed_example['matrix'], parsed_example['matrix_shape'])
# reshape tensor
parsed_example['tensor'] = tf.reshape(parsed_example['tensor'], parsed_example['tensor_shape'])
return parsed_example
處理
程式碼應用
21個專案 p28
with tf.Session() as sess:
# 我們要讀三幅圖片A.jpg, B.jpg, C.jpg
filename = ['A.jpg', 'B.jpg', 'C.jpg']
# string_input_producer會產生一個檔名佇列
filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5)
# reader從檔名佇列中讀資料。對應的方法是reader.read
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
# tf.train.string_input_producer定義了一個epoch變數,要對它進行初始化
tf.local_variables_initializer().run()
# 使用start_queue_runners之後,才會開始填充佇列
threads = tf.train.start_queue_runners(sess=sess)
i = 0
while True:
i += 1
# 獲取圖片資料並儲存
image_data = sess.run(value)
with open('read/test_%d.jpg' % i, 'wb') as f:
f.write(image_data)
# 程式最後會丟擲一個OutOfRangeError,這是epoch跑完,佇列關閉的標誌