用自己的數據集訓練Tensorflow模型

用自己的數據集訓練Tensorflow模型

上篇博文我們用tensorflow實現了一些簡單的圖像處理
TensorFlow中的圖像處理

今天我們進一步來學習tensorflow
本文具體數據集與源代碼可從我的GitHub地址獲取
https://github.com/liuzuoping/Deep_Learning_note

  • 數據預處理
  • 數據的讀取

數據讀取

根據tensorflow的官方教程來看,tensorflow主要支持4中數據讀取的方式。

  • Preloaded data: 預加載數據
  • Feeding: 先產生一個個batch數據,然後在運行的時候依次餵給計算圖。
  • Reading from file: 從文件中讀取,tensorflow主要支持兩種方法從文件中讀取數據餵給計算圖:一個是CSV,還有一個是TFRecords
  • 多管線輸入

預加載數據

import tensorflow as tf

# 構建一個Graph
x1 = tf.constant([1, 2, 3])
x2 = tf.constant([4, 5, 6])
y = tf.add(x1, x2)

# 喂數據 -> 啓動session,計算圖 
with tf.Session() as sess:
    print(sess.run(y))

[5 7 9]

Feeding

import tensorflow as tf

# 構建Graph
x1 = tf.placeholder(tf.int16)
x2 = tf.placeholder(tf.int16)
y = tf.add(x1, x2)

# X_1,X_2是變量,可以賦予不同的值
X_1 = [1, 2, 3]
X_2 = [4, 5, 6]

# 喂數據 -> 啓動session,計算圖 
with tf.Session() as sess:
    print(sess.run(y, feed_dict={x1: X_1, x2: X_2}))

[5 7 9]

從文件中讀取

  • 直接讀取文件
  • 寫入TFRecord並讀取

直接讀取文件

# 導入tensorflow
import tensorflow as tf 

# 新建一個Session
with tf.Session() as sess:
    # 我們要讀三幅圖片plate1.jpg, plate2.jpg, plate3.jpg
    filename = ['images/plate1.jpg', 'images/plate2.jpg', 'images/plate3.jpg']
    # string_input_producer會產生一個文件名隊列
    filename_queue = tf.train.string_input_producer(filename, shuffle=True, 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('tfIO/test_%d.jpg' % i, 'wb') as f:
            f.write(image_data)

寫入TFRecord並讀取

import tensorflow as tf
# 爲顯示圖片
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
%pylab inline
# 爲數據操作
import pandas as pd
import numpy as np
import os
img=mpimg.imread('images/plate1.jpg') 
tensors = np.array([img,img,img])
# show image
print('\n張量')
display(tensors)
plt.imshow(img)

在這裏插入圖片描述

import os
import tensorflow as tf
from PIL import Image


def create_record():
    writer = tf.python_io.TFRecordWriter("tfIO/tfrecord/test.tfrecord")
    for i in range(3):
        # 創建字典
        features={}
        # 寫入張量,類型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()
        # 寫入一個序列化的樣本
        writer.write(tf_serialized)
        # 由於上面有循環3次,所以到此我們已經寫了3個樣本
        # 關閉文件    
    writer.close()
    
def read_and_decode(filename):
    filename_queue = tf.train.string_input_producer([filename])

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'tensor': tf.FixedLenFeature([], tf.string),
                                           'tensor_shape' : tf.FixedLenFeature([], tf.int64),
                                       })

    tensor = tf.decode_raw(features['tensor'], tf.uint8)
    tensor = tf.reshape(tensor, [224, 224, 3])
    tensor = tf.cast(tensor, tf.float32) * (1. / 255) - 0.5
    tensor_shape = tf.cast(features['tensor_shape'], tf.int32)

    return tensor,tensor_shape

if __name__ == '__main__':
    img, label = read_and_decode("tfIO/tfrecord/test.tfrecord")

    img_batch, label_batch = tf.train.shuffle_batch([img, label],
                                                    batch_size=5, capacity=2000,
                                                    min_after_dequeue=1000)
    #初始化所有的op
    init = tf.initialize_all_variables()

    with tf.Session() as sess:
        sess.run(init)
        #啓動隊列
        threads = tf.train.start_queue_runners(sess=sess)
        for i in range(3):
            val, l= sess.run([img_batch, label_batch])
            #l = to_categorical(l, 12)
            print(val.shape, l)
發佈了274 篇原創文章 · 獲贊 412 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章