1. 程式人生 > >深度學習(五十六)tensorflow專案構建流程

深度學習(五十六)tensorflow專案構建流程

tensorflow專案構建流程

微博黃錦池-hjimce qq:1393852684

一、構建路線

個人感覺對於任何一個深度學習庫,如mxnet、tensorflow、theano、caffe等,基本上我都採用同樣的一個學習流程,大體流程如下:

(1)訓練階段:資料打包-》網路構建、訓練-》模型儲存-》視覺化檢視損失函式、驗證精度

(2)測試階段:模型載入-》測試圖片讀取-》預測顯示結果

(3)移植階段:量化、壓縮加速-》微調-》C++移植打包-》上線

這邊我就以tensorflow為例子,講解整個流程的大體架構,完成一個深度學習專案所需要熟悉的過程程式碼。

二、訓練、測試階段

1、tensorflow打包資料

這一步對於tensorflow來說,也可以直接自己線上讀取:.jpg圖片、標籤檔案等,然後通過phaceholder變數,把資料送入網路中,進行計算。

不過這種效率比較低,對於大規模訓練資料來說,我們需要一個比較高效的方式,tensorflow建議我們採用tfrecoder進行高效資料讀取。學習tensorflow一定要學會tfrecoder檔案寫入、讀取,具體示例程式碼如下:

#coding=utf-8
#tensorflow高效資料讀取訓練
import tensorflow as tf
import cv2

#把train.txt檔案格式,每一行:圖片路徑名   類別標籤
#獎資料打包,轉換成tfrecords格式,以便後續高效讀取
def encode_to_tfrecords(lable_file,data_root,new_name='data.tfrecords',resize=None):
    writer=tf.python_io.TFRecordWriter(data_root+'/'+new_name)
    num_example=0
    with open(lable_file,'r') as f:
        for l in f.readlines():
            l=l.split()
            image=cv2.imread(data_root+"/"+l[0])
            if resize is not None:
                image=cv2.resize(image,resize)#為了
            height,width,nchannel=image.shape

            label=int(l[1])

            example=tf.train.Example(features=tf.train.Features(feature={
                'height':tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),
                'width':tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),
                'nchannel':tf.train.Feature(int64_list=tf.train.Int64List(value=[nchannel])),
                'image':tf.train.Feature(bytes_list=tf.train.BytesList(value=[image.tobytes()])),
                'label':tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))
            }))
            serialized=example.SerializeToString()
            writer.write(serialized)
            num_example+=1
    print lable_file,"樣本資料量:",num_example
    writer.close()
#讀取tfrecords檔案
def decode_from_tfrecords(filename,num_epoch=None):
    filename_queue=tf.train.string_input_producer([filename],num_epochs=num_epoch)#因為有的訓練資料過於龐大,被分成了很多個檔案,所以第一個引數就是檔案列表名引數
    reader=tf.TFRecordReader()
    _,serialized=reader.read(filename_queue)
    example=tf.parse_single_example(serialized,features={
        'height':tf.FixedLenFeature([],tf.int64),
        'width':tf.FixedLenFeature([],tf.int64),
        'nchannel':tf.FixedLenFeature([],tf.int64),
        'image':tf.FixedLenFeature([],tf.string),
        'label':tf.FixedLenFeature([],tf.int64)
    })
    label=tf.cast(example['label'], tf.int32)
    image=tf.decode_raw(example['image'],tf.uint8)
    image=tf.reshape(image,tf.pack([
        tf.cast(example['height'], tf.int32),
        tf.cast(example['width'], tf.int32),
        tf.cast(example['nchannel'], tf.int32)]))
    #label=example['label']
    return image,label
#根據佇列流資料格式,解壓出一張圖片後,輸入一張圖片,對其做預處理、及樣本隨機擴充
def get_batch(image, label, batch_size,crop_size):
        #資料擴充變換
    distorted_image = tf.random_crop(image, [crop_size, crop_size, 3])#隨機裁剪
    distorted_image = tf.image.random_flip_up_down(distorted_image)#上下隨機翻轉
    #distorted_image = tf.image.random_brightness(distorted_image,max_delta=63)#亮度變化
    #distorted_image = tf.image.random_contrast(distorted_image,lower=0.2, upper=1.8)#對比度變化

    #生成batch
    #shuffle_batch的引數:capacity用於定義shuttle的範圍,如果是對整個訓練資料集,獲取batch,那麼capacity就應該夠大
    #保證資料打的足夠亂
    images, label_batch = tf.train.shuffle_batch([distorted_image, label],batch_size=batch_size,
                                                 num_threads=16,capacity=50000,min_after_dequeue=10000)
    #images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)



    # 除錯顯示
    #tf.image_summary('images', images)
    return images, tf.reshape(label_batch, [batch_size])
#這個是用於測試階段,使用的get_batch函式
def get_test_batch(image, label, batch_size,crop_size):
        #資料擴充變換
    distorted_image=tf.image.central_crop(image,39./45.)
    distorted_image = tf.random_crop(distorted_image, [crop_size, crop_size, 3])#隨機裁剪
    images, label_batch=tf.train.batch([distorted_image, label],batch_size=batch_size)
    return images, tf.reshape(label_batch, [batch_size])
#測試上面的壓縮、解壓程式碼
def test():
    encode_to_tfrecords("data/train.txt","data",(100,100))
    image,label=decode_from_tfrecords('data/data.tfrecords')
    batch_image,batch_label=get_batch(image,label,3)#batch 生成測試
    init=tf.initialize_all_variables()
    with tf.Session() as session:
        session.run(init)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        for l in range(100000):#每run一次,就會指向下一個樣本,一直迴圈
            #image_np,label_np=session.run([image,label])#每呼叫run一次,那麼
            '''cv2.imshow("temp",image_np)
            cv2.waitKey()'''
            #print label_np
            #print image_np.shape


            batch_image_np,batch_label_np=session.run([batch_image,batch_label])
            print batch_image_np.shape
            print batch_label_np.shape



        coord.request_stop()#queue需要關閉,否則報錯
        coord.join(threads)
#test()

2、網路架構與訓練

經過上面的資料格式處理,接著我們只要寫一寫網路結構、網路優化方法,把資料搞進網路中就可以了,具體示例程式碼如下:

#coding=utf-8
import  tensorflow as tf
from  data_encoder_decoeder import  encode_to_tfrecords,decode_from_tfrecords,get_batch,get_test_batch
import  cv2
import  os

class network(object):
    def __init__(self):
        with tf.variable_scope("weights"):
            self.weights={
                #39*39*3->36*36*20->18*18*20
                'conv1':tf.get_variable('conv1',[4,4,3,20],initializer=tf.contrib.layers.xavier_initializer_conv2d()),
                #18*18*20->16*16*40->8*8*40
                'conv2':tf.get_variable('conv2',[3,3,20,40],initializer=tf.contrib.layers.xavier_initializer_conv2d()),
                #8*8*40->6*6*60->3*3*60
                'conv3':tf.get_variable('conv3',[3,3,40,60],initializer=tf.contrib.layers.xavier_initializer_conv2d()),
                #3*3*60->120
                'fc1':tf.get_variable('fc1',[3*3*60,120],initializer=tf.contrib.layers.xavier_initializer()),
                #120->6
                'fc2':tf.get_variable('fc2',[120,6],initializer=tf.contrib.layers.xavier_initializer()),
                }
        with tf.variable_scope("biases"):
            self.biases={
                'conv1':tf.get_variable('conv1',[20,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),
                'conv2':tf.get_variable('conv2',[40,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),
                'conv3':tf.get_variable('conv3',[60,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),
                'fc1':tf.get_variable('fc1',[120,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32)),
                'fc2':tf.get_variable('fc2',[6,],initializer=tf.constant_initializer(value=0.0, dtype=tf.float32))

            }

    def inference(self,images):
        # 向量轉為矩陣
        images = tf.reshape(images, shape=[-1, 39,39, 3])# [batch, in_height, in_width, in_channels]
        images=(tf.cast(images,tf.float32)/255.-0.5)*2#歸一化處理



        #第一層
        conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv1'])

        relu1= tf.nn.relu(conv1)
        pool1=tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        #第二層
        conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv2'])
        relu2= tf.nn.relu(conv2)
        pool2=tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        # 第三層
        conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv3'])
        relu3= tf.nn.relu(conv3)
        pool3=tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        # 全連線層1,先把特徵圖轉為向量
        flatten = tf.reshape(pool3, [-1, self.weights['fc1'].get_shape().as_list()[0]])

        drop1=tf.nn.dropout(flatten,0.5)
        fc1=tf.matmul(drop1, self.weights['fc1'])+self.biases['fc1']

        fc_relu1=tf.nn.relu(fc1)

        fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']

        return  fc2
    def inference_test(self,images):
                # 向量轉為矩陣
        images = tf.reshape(images, shape=[-1, 39,39, 3])# [batch, in_height, in_width, in_channels]
        images=(tf.cast(images,tf.float32)/255.-0.5)*2#歸一化處理



        #第一層
        conv1=tf.nn.bias_add(tf.nn.conv2d(images, self.weights['conv1'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv1'])

        relu1= tf.nn.relu(conv1)
        pool1=tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        #第二層
        conv2=tf.nn.bias_add(tf.nn.conv2d(pool1, self.weights['conv2'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv2'])
        relu2= tf.nn.relu(conv2)
        pool2=tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        # 第三層
        conv3=tf.nn.bias_add(tf.nn.conv2d(pool2, self.weights['conv3'], strides=[1, 1, 1, 1], padding='VALID'),
                             self.biases['conv3'])
        relu3= tf.nn.relu(conv3)
        pool3=tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')


        # 全連線層1,先把特徵圖轉為向量
        flatten = tf.reshape(pool3, [-1, self.weights['fc1'].get_shape().as_list()[0]])

        fc1=tf.matmul(flatten, self.weights['fc1'])+self.biases['fc1']
        fc_relu1=tf.nn.relu(fc1)

        fc2=tf.matmul(fc_relu1, self.weights['fc2'])+self.biases['fc2']

        return  fc2

    #計算softmax交叉熵損失函式
    def sorfmax_loss(self,predicts,labels):
        predicts=tf.nn.softmax(predicts)
        labels=tf.one_hot(labels,self.weights['fc2'].get_shape().as_list()[1])
        loss =-tf.reduce_mean(labels * tf.log(predicts))# tf.nn.softmax_cross_entropy_with_logits(predicts, labels)
        self.cost= loss
        return self.cost
    #梯度下降
    def optimer(self,loss,lr=0.001):
        train_optimizer = tf.train.GradientDescentOptimizer(lr).minimize(loss)

        return train_optimizer


def train():
    encode_to_tfrecords("data/train.txt","data",'train.tfrecords',(45,45))
    image,label=decode_from_tfrecords('data/train.tfrecords')
    batch_image,batch_label=get_batch(image,label,batch_size=50,crop_size=39)#batch 生成測試







   #網路連結,訓練所用
    net=network()
    inf=net.inference(batch_image)
    loss=net.sorfmax_loss(inf,batch_label)
    opti=net.optimer(loss)


    #驗證集所用
    encode_to_tfrecords("data/val.txt","data",'val.tfrecords',(45,45))
    test_image,test_label=decode_from_tfrecords('data/val.tfrecords',num_epoch=None)
    test_images,test_labels=get_test_batch(test_image,test_label,batch_size=120,crop_size=39)#batch 生成測試
    test_inf=net.inference_test(test_images)
    correct_prediction = tf.equal(tf.cast(tf.argmax(test_inf,1),tf.int32), test_labels)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))





    init=tf.initialize_all_variables()
    with tf.Session() as session:
        session.run(init)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        max_iter=100000
        iter=0
        if os.path.exists(os.path.join("model",'model.ckpt')) is True:
            tf.train.Saver(max_to_keep=None).restore(session, os.path.join("model",'model.ckpt'))
        while iter<max_iter:
            loss_np,_,label_np,image_np,inf_np=session.run([loss,opti,batch_label,batch_image,inf])
            #print image_np.shape
            #cv2.imshow(str(label_np[0]),image_np[0])
            #print label_np[0]
            #cv2.waitKey()
            #print label_np
            if iter%50==0:
                print 'trainloss:',loss_np
            if iter%500==0:
                accuracy_np=session.run([accuracy])
                print '***************test accruacy:',accuracy_np,'*******************'
                tf.train.Saver(max_to_keep=None).save(session, os.path.join('model','model.ckpt'))
            iter+=1





        coord.request_stop()#queue需要關閉,否則報錯
        coord.join(threads)

train()

3、視覺化顯示

(1)首先再原始碼中加入需要跟蹤的變數:

tf.scalar_summary("cost_function", loss)#損失函式值
(2)然後定義執行操作:
merged_summary_op = tf.merge_all_summaries()
(3)再session中定義儲存路徑:
summary_writer = tf.train.SummaryWriter('log', session.graph)

(4)然後再session執行的時候,儲存:

            summary_str,loss_np,_=session.run([merged_summary_op,loss,opti])
            summary_writer.add_summary(summary_str, iter)

(5)最後只要訓練完畢後,直接再終端輸入命令:
python /usr/local/lib/python2.7/dist-packages/tensorflow/tensorboard/tensorboard.py --logdir=log
然後開啟瀏覽器網址:
http://0.0.0.0:6006

即可觀訓練曲線。

4、測試階段

測試階段主要是直接通過載入圖模型、讀取引數等,然後直接通過tensorflow的相關函式,進行呼叫,而不需要網路架構相關的程式碼;通過記憶體feed_dict的方式,對相關的輸入節點賦予相關的資料,進行前向傳導,並獲取相關的節點數值。

#coding=utf-8
import  tensorflow  as tf
import  os
import  cv2

def load_model(session,netmodel_path,param_path):
    new_saver = tf.train.import_meta_graph(netmodel_path)
    new_saver.restore(session, param_path)
    x= tf.get_collection('test_images')[0]#在訓練階段需要呼叫tf.add_to_collection('test_images',test_images),儲存之
    y = tf.get_collection("test_inf")[0]
    batch_size = tf.get_collection("batch_size")[0]
    return  x,y,batch_size

def load_images(data_root):
    filename_queue = tf.train.string_input_producer(data_root)
    image_reader = tf.WholeFileReader()
    key,image_file = image_reader.read(filename_queue)
    image = tf.image.decode_jpeg(image_file)
    return image, key

def test(data_root="data/race/cropbrown"):
    image_filenames=os.listdir(data_root)
    image_filenames=[(data_root+'/'+i) for i in image_filenames]


    #print cv2.imread(image_filenames[0]).shape
    #image,key=load_images(image_filenames)
    race_listsrc=['black','brown','white','yellow']
    with tf.Session() as session:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)



        x,y,batch_size=load_model(session,os.path.join("model",'model_ori_race.ckpt.meta'),
                       os.path.join("model",'model_ori_race.ckpt'))
        predict_label=tf.cast(tf.argmax(y,1),tf.int32)
        print x.get_shape()
        for imgf in image_filenames:
            image=cv2.imread(imgf)
            image=cv2.resize(image,(76,76)).reshape((1,76,76,3))
            print "cv shape:",image.shape


            #cv2.imshow("t",image_np[:,:,::-1])
            y_np=session.run(predict_label,feed_dict = {x:image, batch_size:1})
            print race_listsrc[y_np]


        coord.request_stop()#queue需要關閉,否則報錯
        coord.join(threads)

4、移植階段

(1)一個演算法經過實驗階段後,接著就要進入移植商用,因此接著需要採用tensorflow的c api函式,直接進行預測推理,首先我們先把tensorflow編譯成連結庫,然後編寫cmake,呼叫tensorflow連結庫:

bazel build -c opt //tensorflow:libtensorflow.so

bazel-bin/tensorflow目錄下會生成libtensorflow.so檔案

5、C++ API呼叫、cmake 編寫:

三、熟悉常用API

1、LSTM使用

import  tensorflow.nn.rnn_cell

lstm = rnn_cell.BasicLSTMCell(lstm_size)#建立一個lstm cell單元類,隱藏層神經元個數為lstm_size

state = tf.zeros([batch_size, lstm.state_size])#一個序列隱藏層的狀態值

loss = 0.0
for current_batch_of_words in words_in_dataset:
    output, state = lstm(current_batch_of_words, state)#返回值為隱藏層神經元的輸出
    logits = tf.matmul(output, softmax_w) + softmax_b#matmul矩陣點乘
    probabilities = tf.nn.softmax(logits)#softmax輸出
    loss += loss_function(probabilities, target_words)

1、one-hot函式:

#ont hot 可以把訓練資料的標籤,直接轉換成one_hot向量,用於交叉熵損失函式
import tensorflow as tf
a=tf.convert_to_tensor([[1],[2],[4]])
b=tf.one_hot(a,5)

>>b的值為
[[[ 0.  1.  0.  0.  0.]]

 [[ 0.  0.  1.  0.  0.]]

 [[ 0.  0.  0.  0.  1.]]]

2、assign_sub

import tensorflow as tf

x = tf.Variable(10, name="x")
sub=x.assign_sub(3)#如果直接採用x.assign_sub,那麼可以看到x的值也會發生變化
init_op=tf.initialize_all_variables()
with tf.Session() as sess:
    sess.run(init_op)
    print sub.eval()
    print x.eval()
可以看到輸入sub=x=7
state_ops.assign_sub
採用state_ops的assign_sub也是同樣sub=x=7

也就是說assign函式返回結果值的同時,變數本身的值也會被改變
3、變數檢視

    #檢視所有的變數
    for l in tf.all_variables():
        print l.name

4、slice函式:

import cv2
import  tensorflow as tf
#slice 函式可以用於切割子矩形圖片,引數矩形框的rect,begin=(minx,miny),size=(width,height)
minx=20
miny=30
height=100
width=200

image=tf.placeholder(dtype=tf.uint8,shape=(386,386,3))
rect_image=tf.slice(image,(miny,minx,0),(height,width,-1))


cvimage=cv2.imread("1.jpg")
cv2.imshow("cv2",cvimage[miny:(miny+height),minx:(minx+width),:])


with tf.Session() as sess:
    tfimage=sess.run([rect_image],{image:cvimage})
    cv2.imshow('tf',tfimage[0])
cv2.waitKey()

5、正太分佈隨機初始化

tf.truncated_normal

6、列印操作運算在硬體裝置資訊

tf.ConfigProto(log_device_placement=True)
7、變數域名的reuse:
import  tensorflow as tf
with tf.variable_scope('foo'):#在沒有啟用reuse的情況下,如果該變數還未被建立,那麼就建立該變數,如果已經建立過了,那麼就獲取該共享變數
    v=tf.get_variable('v',[1])
with tf.variable_scope('foo',reuse=True):#如果啟用了reuse,那麼編譯的時候,如果get_variable沒有遇到一個已經建立的變數,是會出錯的
    v1=tf.get_variable('v1',[1])

8、allow_soft_placement的使用:allow_soft_placement=True,允許當在程式碼中指定tf.device裝置,如果裝置找不到,那麼就採用預設的裝置。如果該引數設定為false,當裝置找不到的時候,會直接編譯不通過。

9、batch normalize呼叫:

tf.contrib.layers.batch_norm(x, decay=0.9, updates_collections=None, epsilon=self.epsilon, scale=True, scope=self.name)