1. 程式人生 > 程式設計 >使用TFRecord存取多個數據案例

使用TFRecord存取多個數據案例

TensorFlow提供了一種統一的格式來儲存資料,就是TFRecord,它可以統一不同的原始資料格式,並且更加有效地管理不同的屬性。

TFRecord格式

TFRecord檔案中的資料都是用tf.train.Example Protocol Buffer的格式來儲存的,tf.train.Example可以被定義為:

message Example{
  Features features = 1
}

message Features{
  map<string,Feature> feature = 1
}

message Feature{
  oneof kind{
    BytesList bytes_list = 1
    FloatList float_list = 1
    Int64List int64_list = 1
  }
}

可以看出Example是一個巢狀的資料結構,其中屬性名稱可以為一個字串,其取值可以是字串BytesList、實數列表FloatList或整數列表Int64List。

將資料轉化為TFRecord格式

以下程式碼是將MNIST輸入資料轉化為TFRecord格式:

# -*- coding: utf-8 -*-

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np


# 生成整數型的屬性
def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

# 生成浮點型的屬性
def _float_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))  
#若想儲存為陣列,則要改成value=value即可


# 生成字串型的屬性
def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


mnist = input_data.read_data_sets("/tensorflow_google",dtype=tf.uint8,one_hot=True)
images = mnist.train.images
# 訓練資料所對應的正確答案,可以作為一個屬性儲存在TFRecord中
labels = mnist.train.labels
# 訓練資料的影象解析度,這可以作為Example中的一個屬性
pixels = images.shape[1]
num_examples = mnist.train.num_examples

# 輸出TFRecord檔案的地址
filename = "/tensorflow_google/mnist_output.tfrecords"
# 建立一個writer來寫TFRecord檔案
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
  # 將影象矩陣轉換成一個字串
  image_raw = images[index].tostring()
  # 將一個樣例轉化為Example Protocol Buffer,並將所有的資訊寫入這個資料結構
  example = tf.train.Example(features=tf.train.Features(feature={
    'pixels': _int64_feature(pixels),'label': _int64_feature(np.argmax(labels[index])),'image_raw': _bytes_feature(image_raw)}))

  # 將一個Example寫入TFRecord檔案
  writer.write(example.SerializeToString())
writer.close()

本程式將MNIST資料集中所有的訓練資料儲存到了一個TFRecord檔案中,若資料量較大,也可以存入多個檔案。

從TFRecord檔案中讀取資料

以下程式碼可以從上面程式碼中的TFRecord中讀取單個或多個訓練資料:

# -*- coding: utf-8 -*-
import tensorflow as tf

# 建立一個reader來讀取TFRecord檔案中的樣例
reader = tf.TFRecordReader()
# 建立一個佇列來維護輸入檔案列表
filename_queue = tf.train.string_input_producer(["/Users/gaoyue/文件/Program/tensorflow_google/chapter7"
                         "/mnist_output.tfrecords"])

# 從檔案中讀出一個樣例,也可以使用read_up_to函式一次性讀取多個樣例
# _,serialized_example = reader.read(filename_queue)
_,serialized_example = reader.read_up_to(filename_queue,6) #讀取6個樣例
# 解析讀入的一個樣例,如果需要解析多個樣例,可以用parse_example函式
# features = tf.parse_single_example(serialized_example,features={
# 解析多個樣例
features = tf.parse_example(serialized_example,features={
  # TensorFlow提供兩種不同的屬性解析方法
  # 第一種是tf.FixedLenFeature,得到的解析結果為Tensor
  # 第二種是tf.VarLenFeature,得到的解析結果為SparseTensor,用於處理稀疏資料
  # 解析資料的格式需要與寫入資料的格式一致
  'image_raw': tf.FixedLenFeature([],tf.string),'pixels': tf.FixedLenFeature([],tf.int64),'label': tf.FixedLenFeature([],})

# tf.decode_raw可以將字串解析成影象對應的畫素陣列
images = tf.decode_raw(features['image_raw'],tf.uint8)
labels = tf.cast(features['label'],tf.int32)
pixels = tf.cast(features['pixels'],tf.int32)

sess = tf.Session()
# 啟動多執行緒處理輸入資料
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess,coord=coord)

# 每次執行可以讀取TFRecord中的一個樣例,當所有樣例都讀完之後,會重頭讀取
# for i in range(10):
#   image,label,pixel = sess.run([images,labels,pixels])
#   # print(image,pixel)
#   print(label,pixel)

# 讀取TFRecord中的前6個樣例,若加入迴圈,則會每次從上次輸出的地方繼續順序讀6個樣例
image,pixels])
print(label,pixel)

sess.close()

>> [7 3 4 6 1 8] [784 784 784 784 784 784]

輸出結果顯示,從TFRecord檔案中順序讀出前6個樣例。

以上這篇使用TFRecord存取多個數據案例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。