一司顿、freeze
加載模型文件,從checkpoint文件讀取權(quán)重數(shù)據(jù)初始化到模型里的權(quán)重變量,將權(quán)重變量轉(zhuǎn)換成權(quán)重常量抡秆,通過指定的輸出節(jié)點將沒用于輸出推理的Op節(jié)點從圖中剝離掉,再重新保存到指定的文件里
1.tf.train.write_graph()以及tf.train.saver()生成pb文件和ckpt文件
bazel-bin/tensorflow/python/tools/freeze_graph --input_graph=/path/to/graph.pb --input_checkpoint=/path/to/model.ckpt --output_node_names=output/predict --output_graph=/path/to/frozen.pb
2.把訓(xùn)練好的權(quán)重變成常量之后再保存成PB文件
output_graph_def = convert_variables_to_constants(sess, sess.graph_def, output_node_names=['output/predict'])
with tf.gfile.FastGFile('model/CTNModel.pb', mode='wb') as f:
?????f.write(output_graph_def.SerializeToString())
二吟策、quant
1.網(wǎng)絡(luò)參數(shù)是按層組織儒士,每層數(shù)值都在同一數(shù)量級,即范圍相差不大踊挠,如[-6.0,4.0]乍桂,有大量論文研究表明確認(rèn)值最大和最小后每層數(shù)據(jù)使用8bit定點化量化已可以很好滿足推斷計算效床。量化最直接結(jié)果是參數(shù)存儲空間要求變小,經(jīng)驗值是減少約3/4剩檀;減少內(nèi)存讀取數(shù)據(jù)量,節(jié)省帶寬沪猴;使用simd進(jìn)行計算加速辐啄,如果有dsp進(jìn)行8bit加速計算節(jié)能,使得移動設(shè)備上進(jìn)行推斷計算變得更強大有效运嗜。
bazel-bin/tensorflow/tools/quantization/quantize_graph \
? --input=/tmp/classify_image_graph_def.pb \
? --output_node_names="softmax" --output=/tmp/quantized_graph.pb \
? --mode=eightbit
2.可刪除給定的一組輸入和輸出不需要的所有節(jié)點壶辜,該腳本還進(jìn)行了一些其他優(yōu)化担租,可以幫助加快模型,例如將顯式批量歸一化操作合并到卷積權(quán)重中以減少計算次數(shù)奋救。這可以根據(jù)輸入型號提供30%的速度
python -m tensorflow.python.tools.optimize_for_inference \
? --input = tf_files / retrained_graph.pb \
? --output = tf_files / optimized_graph.pb \
? --input_names =“input”\
? --output_names = “final_result”