小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

tensorflow將訓練好的模型freeze,即將權(quán)重固化到圖里面,并使用該模型進行預測

 進門交錢 2017-05-24

ML主要分為訓練和預測兩個階段,此教程就是將訓練好的模型freeze并保存下來.freeze的含義就是將該模型的圖結(jié)構(gòu)和該模型的權(quán)重固化到一起了.也即加載freeze的模型之后,立刻能夠使用了。

下面使用一個簡單的demo來詳細解釋該過程,

一、首先運行腳本tiny_model.py

[python] view plain copy
  1. #-*- coding:utf-8 -*-  
  2. import tensorflow as tf  
  3. import numpy as np  
  4.   
  5.   
  6. with tf.variable_scope('Placeholder'):  
  7.     inputs_placeholder = tf.placeholder(tf.float32, name='inputs_placeholder', shape=[None, 10])  
  8.     labels_placeholder = tf.placeholder(tf.float32, name='labels_placeholder', shape=[None, 1])  
  9.   
  10. with tf.variable_scope('NN'):  
  11.     W1 = tf.get_variable('W1', shape=[10, 1], initializer=tf.random_normal_initializer(stddev=1e-1))  
  12.     b1 = tf.get_variable('b1', shape=[1], initializer=tf.constant_initializer(0.1))  
  13.     W2 = tf.get_variable('W2', shape=[10, 1], initializer=tf.random_normal_initializer(stddev=1e-1))  
  14.     b2 = tf.get_variable('b2', shape=[1], initializer=tf.constant_initializer(0.1))  
  15.   
  16.     a = tf.nn.relu(tf.matmul(inputs_placeholder, W1) + b1)  
  17.     a2 = tf.nn.relu(tf.matmul(inputs_placeholder, W2) + b2)  
  18.   
  19.     y = tf.div(tf.add(a, a2), 2)  
  20.   
  21. with tf.variable_scope('Loss'):  
  22.     loss = tf.reduce_sum(tf.square(y - labels_placeholder) / 2)  
  23.   
  24. with tf.variable_scope('Accuracy'):  
  25.     predictions = tf.greater(y, 0.5, name="predictions")  
  26.     correct_predictions = tf.equal(predictions, tf.cast(labels_placeholder, tf.bool), name="correct_predictions")  
  27.     accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))  
  28.   
  29.   
  30. adam = tf.train.AdamOptimizer(learning_rate=1e-3)  
  31. train_op = adam.minimize(loss)  
  32.   
  33. # generate_data  
  34. inputs = np.random.choice(10, size=[10000, 10])  
  35. labels = (np.sum(inputs, axis=1) > 45).reshape(-1, 1).astype(np.float32)  
  36. print('inputs.shape:', inputs.shape)  
  37. print('labels.shape:', labels.shape)  
  38.   
  39.   
  40. test_inputs = np.random.choice(10, size=[100, 10])  
  41. test_labels = (np.sum(test_inputs, axis=1) > 45).reshape(-1, 1).astype(np.float32)  
  42. print('test_inputs.shape:', test_inputs.shape)  
  43. print('test_labels.shape:', test_labels.shape)  
  44.   
  45. batch_size = 32  
  46. epochs = 10  
  47.   
  48. batches = []  
  49. print("%d items in batch of %d gives us %d full batches and %d batches of %d items" % (  
  50.     len(inputs),  
  51.     batch_size,  
  52.     len(inputs) // batch_size,  
  53.     batch_size - len(inputs) // batch_size,  
  54.     len(inputs) - (len(inputs) // batch_size) * 32)  
  55. )  
  56. for i in range(len(inputs) // batch_size):  
  57.     batch = [ inputs[batch_size*i:batch_size*i+batch_size], labels[batch_size*i:batch_size*i+batch_size] ]  
  58.     batches.append(list(batch))  
  59. if (i + 1) * batch_size < len(inputs):  
  60.     batch = [ inputs[batch_size*(i + 1):],labels[batch_size*(i + 1):] ]  
  61.     batches.append(list(batch))  
  62. print("Number of batches: %d" % len(batches))  
  63. print("Size of full batch: %d" % len(batches[0]))  
  64. print("Size if final batch: %d" % len(batches[-1]))  
  65.   
  66. global_count = 0  
  67.   
  68. with tf.Session() as sess:  
  69. #sv = tf.train.Supervisor()  
  70. #with sv.managed_session() as sess:  
  71.     sess.run(tf.initialize_all_variables())  
  72.     for i in range(epochs):  
  73.         for batch in batches:  
  74.             # print(batch[0].shape, batch[1].shape)  
  75.             train_loss , _= sess.run([loss, train_op], feed_dict={  
  76.                 inputs_placeholder: batch[0],  
  77.                 labels_placeholder: batch[1]  
  78.             })  
  79.             # print('train_loss: %d' % train_loss)  
  80.   
  81.             if global_count % 100 == 0:  
  82.                 acc = sess.run(accuracy, feed_dict={  
  83.                     inputs_placeholder: test_inputs,  
  84.                     labels_placeholder: test_labels  
  85.                 })  
  86.                 print('accuracy: %f' % acc)  
  87.             global_count += 1  
  88.   
  89.     acc = sess.run(accuracy, feed_dict={  
  90.         inputs_placeholder: test_inputs,  
  91.         labels_placeholder: test_labels  
  92.     })  
  93.     print("final accuracy: %f" % acc)  
  94.     #在session當中就要將模型進行保存  
  95.     saver = tf.train.Saver()  
  96.     last_chkp = saver.save(sess, 'results/graph.chkp')  
  97.     #sv.saver.save(sess, 'results/graph.chkp')  
  98.   
  99. for op in tf.get_default_graph().get_operations():  
  100.     print(op.name)  
說明:saver.save必須在session里面,因為在session里面,整個圖才是激活的,才能夠?qū)?shù)存進來,使用save之后能夠得到如下的文件:


說明:
.data:存放的是權(quán)重參數(shù)
.meta:存放的是圖和metadata,metadata是其他配置的數(shù)據(jù)
如果想將我們的模型固化,讓別人能夠使用,我們僅僅需要的是圖和參數(shù),metadata是不需要的

二、綜合上述幾個文件,生成可以使用的模型的步驟如下

1、恢復我們保存的圖
2、開啟一個Session,然后載入該圖要求的權(quán)重
3、刪除對預測無關(guān)的metadata
4、將處理好的模型序列化之后保存
運行freeze.py

[python] view plain copy
  1. #-*- coding:utf-8 -*-  
  2. import os, argparse  
  3. import tensorflow as tf  
  4. from tensorflow.python.framework import graph_util  
  5.   
  6. dir = os.path.dirname(os.path.realpath(__file__))  
  7.   
  8. def freeze_graph(model_folder):  
  9.     # We retrieve our checkpoint fullpath  
  10.     checkpoint = tf.train.get_checkpoint_state(model_folder)  
  11.     input_checkpoint = checkpoint.model_checkpoint_path  
  12.       
  13.     # We precise the file fullname of our freezed graph  
  14.     absolute_model_folder = "/".join(input_checkpoint.split('/')[:-1])  
  15.     output_graph = absolute_model_folder + "/frozen_model.pb"  
  16.   
  17.     # Before exporting our graph, we need to precise what is our output node  
  18.     # this variables is plural, because you can have multiple output nodes  
  19.     #freeze之前必須明確哪個是輸出結(jié)點,也就是我們要得到推論結(jié)果的結(jié)點  
  20.     #輸出結(jié)點可以看我們模型的定義  
  21.     #只有定義了輸出結(jié)點,freeze才會把得到輸出結(jié)點所必要的結(jié)點都保存下來,或者哪些結(jié)點可以丟棄  
  22.     #所以,output_node_names必須根據(jù)不同的網(wǎng)絡(luò)進行修改  
  23.     output_node_names = "Accuracy/predictions"  
  24.   
  25.     # We clear the devices, to allow TensorFlow to control on the loading where it wants operations to be calculated  
  26.     clear_devices = True  
  27.       
  28.     # We import the meta graph and retrive a Saver  
  29.     saver = tf.train.import_meta_graph(input_checkpoint + '.meta', clear_devices=clear_devices)  
  30.   
  31.     # We retrieve the protobuf graph definition  
  32.     graph = tf.get_default_graph()  
  33.     input_graph_def = graph.as_graph_def()  
  34.   
  35.     #We start a session and restore the graph weights  
  36.     #這邊已經(jīng)將訓練好的參數(shù)加載進來,也即最后保存的模型是有圖,并且圖里面已經(jīng)有參數(shù)了,所以才叫做是frozen  
  37.     #相當于將參數(shù)已經(jīng)固化在了圖當中   
  38.     with tf.Session() as sess:  
  39.         saver.restore(sess, input_checkpoint)  
  40.   
  41.         # We use a built-in TF helper to export variables to constant  
  42.         output_graph_def = graph_util.convert_variables_to_constants(  
  43.             sess,   
  44.             input_graph_def,   
  45.             output_node_names.split(",") # We split on comma for convenience  
  46.         )   
  47.   
  48.         # Finally we serialize and dump the output graph to the filesystem  
  49.         with tf.gfile.GFile(output_graph, "wb") as f:  
  50.             f.write(output_graph_def.SerializeToString())  
  51.         print("%d ops in the final graph." % len(output_graph_def.node))  
  52.   
  53.   
  54. if __name__ == '__main__':  
  55.     parser = argparse.ArgumentParser()  
  56.     parser.add_argument("--model_folder", type=str, help="Model folder to export")  
  57.     args = parser.parse_args()  
  58.   
  59.     freeze_graph(args.model_folder)  

說明:對于freeze操作,我們需要定義輸出結(jié)點的名字.因為網(wǎng)絡(luò)其實是比較復雜的,定義了輸出結(jié)點的名字,那么freeze的時候就只把輸出該結(jié)點所需要的子圖都固化下來,其他無關(guān)的就舍棄掉.因為我們freeze模型的目的是接下來做預測.所以,一般情況下,output_node_names就是我們預測的目標.

三、加載freeze后的模型,注意該模型已經(jīng)是包含圖和相應(yīng)的參數(shù)了.所以,我們不需要再加載參數(shù)進來.也即該模型加載進來已經(jīng)是可以使用了.

[python] view plain copy
  1. #-*- coding:utf-8 -*-  
  2. import argparse   
  3. import tensorflow as tf  
  4.   
  5. def load_graph(frozen_graph_filename):  
  6.     # We parse the graph_def file  
  7.     with tf.gfile.GFile(frozen_graph_filename, "rb") as f:  
  8.         graph_def = tf.GraphDef()  
  9.         graph_def.ParseFromString(f.read())  
  10.   
  11.     # We load the graph_def in the default graph  
  12.     with tf.Graph().as_default() as graph:  
  13.         tf.import_graph_def(  
  14.             graph_def,   
  15.             input_map=None,   
  16.             return_elements=None,   
  17.             name="prefix",   
  18.             op_dict=None,   
  19.             producer_op_list=None  
  20.         )  
  21.     return graph  
  22.   
  23. if __name__ == '__main__':  
  24.     parser = argparse.ArgumentParser()  
  25.     parser.add_argument("--frozen_model_filename", default="results/frozen_model.pb", type=str, help="Frozen model file to import")  
  26.     args = parser.parse_args()  
  27.     #加載已經(jīng)將參數(shù)固化后的圖  
  28.     graph = load_graph(args.frozen_model_filename)  
  29.   
  30.     # We can list operations  
  31.     #op.values() gives you a list of tensors it produces  
  32.     #op.name gives you the name  
  33.     #輸入,輸出結(jié)點也是operation,所以,我們可以得到operation的名字  
  34.     for op in graph.get_operations():  
  35.         print(op.name,op.values())  
  36.         # prefix/Placeholder/inputs_placeholder  
  37.         # ...  
  38.         # prefix/Accuracy/predictions  
  39.     #操作有:prefix/Placeholder/inputs_placeholder  
  40.     #操作有:prefix/Accuracy/predictions  
  41.     #為了預測,我們需要找到我們需要feed的tensor,那么就需要該tensor的名字  
  42.     #注意prefix/Placeholder/inputs_placeholder僅僅是操作的名字,prefix/Placeholder/inputs_placeholder:0才是tensor的名字  
  43.     x = graph.get_tensor_by_name('prefix/Placeholder/inputs_placeholder:0')  
  44.     y = graph.get_tensor_by_name('prefix/Accuracy/predictions:0')  
  45.           
  46.     with tf.Session(graph=graph) as sess:  
  47.         y_out = sess.run(y, feed_dict={  
  48.             x: [[3, 5, 7, 4, 5, 1, 1, 1, 1, 1]] # < 45  
  49.         })  
  50.         print(y_out) # [[ 0.]] Yay!  
  51.     print ("finish")  
說明:

1、在預測的過程中,當把freeze后的模型加載進來后,我們只需要定義好輸入的tensor和目標tensor即可

2、在這里要注意一下tensor_name和ops_name,

注意prefix/Placeholder/inputs_placeholder僅僅是操作的名字,prefix/Placeholder/inputs_placeholder:0才是tensor的名字

x = graph.get_tensor_by_name('prefix/Placeholder/inputs_placeholder:0')一定要使用tensor的名字

3、要獲取圖中ops的名字和對應(yīng)的tensor的名字,可用如下的代碼:

[python] view plain copy
  1. # We can list operations  
  2. #op.values() gives you a list of tensors it produces  
  3. #op.name gives you the name  
  4. #輸入,輸出結(jié)點也是operation,所以,我們可以得到operation的名字  
  5. for op in graph.get_operations():  
  6.     print(op.name,op.values())  

=============================================================================================================================

上面是使用了Saver()來保存模型,也可以使用sv = tf.train.Supervisor()來保存模型

[python] view plain copy
  1. #-*- coding:utf-8 -*-  
  2. import tensorflow as tf  
  3. import numpy as np  
  4.   
  5.   
  6. with tf.variable_scope('Placeholder'):  
  7.     inputs_placeholder = tf.placeholder(tf.float32, name='inputs_placeholder', shape=[None, 10])  
  8.     labels_placeholder = tf.placeholder(tf.float32, name='labels_placeholder', shape=[None, 1])  
  9.   
  10. with tf.variable_scope('NN'):  
  11.     W1 = tf.get_variable('W1', shape=[10, 1], initializer=tf.random_normal_initializer(stddev=1e-1))  
  12.     b1 = tf.get_variable('b1', shape=[1], initializer=tf.constant_initializer(0.1))  
  13.     W2 = tf.get_variable('W2', shape=[10, 1], initializer=tf.random_normal_initializer(stddev=1e-1))  
  14.     b2 = tf.get_variable('b2', shape=[1], initializer=tf.constant_initializer(0.1))  
  15.   
  16.     a = tf.nn.relu(tf.matmul(inputs_placeholder, W1) + b1)  
  17.     a2 = tf.nn.relu(tf.matmul(inputs_placeholder, W2) + b2)  
  18.   
  19.     y = tf.div(tf.add(a, a2), 2)  
  20.   
  21. with tf.variable_scope('Loss'):  
  22.     loss = tf.reduce_sum(tf.square(y - labels_placeholder) / 2)  
  23.   
  24. with tf.variable_scope('Accuracy'):  
  25.     predictions = tf.greater(y, 0.5, name="predictions")  
  26.     correct_predictions = tf.equal(predictions, tf.cast(labels_placeholder, tf.bool), name="correct_predictions")  
  27.     accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))  
  28.   
  29.   
  30. adam = tf.train.AdamOptimizer(learning_rate=1e-3)  
  31. train_op = adam.minimize(loss)  
  32.   
  33. # generate_data  
  34. inputs = np.random.choice(10, size=[10000, 10])  
  35. labels = (np.sum(inputs, axis=1) > 45).reshape(-1, 1).astype(np.float32)  
  36. print('inputs.shape:', inputs.shape)  
  37. print('labels.shape:', labels.shape)  
  38.   
  39.   
  40. test_inputs = np.random.choice(10, size=[100, 10])  
  41. test_labels = (np.sum(test_inputs, axis=1) > 45).reshape(-1, 1).astype(np.float32)  
  42. print('test_inputs.shape:', test_inputs.shape)  
  43. print('test_labels.shape:', test_labels.shape)  
  44.   
  45. batch_size = 32  
  46. epochs = 10  
  47.   
  48. batches = []  
  49. print("%d items in batch of %d gives us %d full batches and %d batches of %d items" % (  
  50.     len(inputs),  
  51.     batch_size,  
  52.     len(inputs) // batch_size,  
  53.     batch_size - len(inputs) // batch_size,  
  54.     len(inputs) - (len(inputs) // batch_size) * 32)  
  55. )  
  56. for i in range(len(inputs) // batch_size):  
  57.     batch = [ inputs[batch_size*i:batch_size*i+batch_size], labels[batch_size*i:batch_size*i+batch_size] ]  
  58.     batches.append(list(batch))  
  59. if (i + 1) * batch_size < len(inputs):  
  60.     batch = [ inputs[batch_size*(i + 1):],labels[batch_size*(i + 1):] ]  
  61.     batches.append(list(batch))  
  62. print("Number of batches: %d" % len(batches))  
  63. print("Size of full batch: %d" % len(batches[0]))  
  64. print("Size if final batch: %d" % len(batches[-1]))  
  65.   
  66. global_count = 0  
  67.   
  68. #with tf.Session() as sess:  
  69. sv = tf.train.Supervisor()  
  70. with sv.managed_session() as sess:  
  71.     #sess.run(tf.initialize_all_variables())  
  72.     for i in range(epochs):  
  73.         for batch in batches:  
  74.             # print(batch[0].shape, batch[1].shape)  
  75.             train_loss , _= sess.run([loss, train_op], feed_dict={  
  76.                 inputs_placeholder: batch[0],  
  77.                 labels_placeholder: batch[1]  
  78.             })  
  79.             # print('train_loss: %d' % train_loss)  
  80.   
  81.             if global_count % 100 == 0:  
  82.                 acc = sess.run(accuracy, feed_dict={  
  83.                     inputs_placeholder: test_inputs,  
  84.                     labels_placeholder: test_labels  
  85.                 })  
  86.                 print('accuracy: %f' % acc)  
  87.             global_count += 1  
  88.   
  89.     acc = sess.run(accuracy, feed_dict={  
  90.         inputs_placeholder: test_inputs,  
  91.         labels_placeholder: test_labels  
  92.     })  
  93.     print("final accuracy: %f" % acc)  
  94.     #在session當中就要將模型進行保存  
  95.     #saver = tf.train.Saver()  
  96.     #last_chkp = saver.save(sess, 'results/graph.chkp')  
  97.     sv.saver.save(sess, 'results/graph.chkp')  
  98.   
  99. for op in tf.get_default_graph().get_operations():  
  100.     print(op.name)  

注意:使用了sv = tf.train.Supervisor(),就不需要再初始化了,將sess.run(tf.initialize_all_variables())注釋掉,否則會報錯.



    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多