1. 程式人生 > 程式設計 >Keras模型轉成tensorflow的.pb操作

Keras模型轉成tensorflow的.pb操作

Keras的.h5模型轉成tensorflow的.pb格式模型,方便後期的前端部署。直接上程式碼

from keras.models import Model
from keras.layers import Dense,Dropout
from keras.applications.mobilenet import MobileNet
from keras.applications.mobilenet import preprocess_input
from keras.preprocessing.image import load_img,img_to_array
import tensorflow as tf
from keras import backend as K
import os
 
base_model = MobileNet((None,None,3),alpha=1,include_top=False,pooling='avg',weights=None)
x = Dropout(0.75)(base_model.output)
x = Dense(10,activation='softmax')(x)
 
model = Model(base_model.input,x)
model.load_weights('mobilenet_weights.h5')
 
def freeze_session(session,keep_var_names=None,output_names=None,clear_devices=True):
 from tensorflow.python.framework.graph_util import convert_variables_to_constants
 graph = session.graph
 with graph.as_default():
  freeze_var_names = list(set(v.op.name for v in tf.global_variables()).difference(keep_var_names or []))
  output_names = output_names or []
  output_names += [v.op.name for v in tf.global_variables()]
  input_graph_def = graph.as_graph_def()
  if clear_devices:
   for node in input_graph_def.node:
    node.device = ""
  frozen_graph = convert_variables_to_constants(session,input_graph_def,output_names,freeze_var_names)
  return frozen_graph
 
output_graph_name = 'NIMA.pb'
output_fld = ''
#K.set_learning_phase(0)
 
print('input is :',model.input.name)
print ('output is:',model.output.name)
 
sess = K.get_session()
frozen_graph = freeze_session(K.get_session(),output_names=[model.output.op.name])
 
from tensorflow.python.framework import graph_io
graph_io.write_graph(frozen_graph,output_fld,output_graph_name,as_text=False)
print('saved the constant graph (ready for inference) at: ',os.path.join(output_fld,output_graph_name))

補充知識:keras h5 model 轉換為tflite

在移動端的模型,若選擇tensorflow或者keras最基本的就是生成tflite檔案,以本文記錄一次轉換過程。

環境

tensorflow 1.12.0

python 3.6.5

h5 model saved by `model.save('tf.h5')`

直接轉換

`tflite_convert --output_file=tf.tflite --keras_model_file=tf.h5`
output
`TypeError: __init__() missing 2 required positional arguments: 'filters' and 'kernel_size'`

先轉成pb再轉tflite

```

git clone [email protected]:amir-abdi/keras_to_tensorflow.git
cd keras_to_tensorflow
python keras_to_tensorflow.py --input_model=path/to/tf.h5 --output_model=path/to/tf.pb
tflite_convert \

 --output_file=tf.tflite \
 --graph_def_file=tf.pb \
 --input_arrays=convolution2d_1_input \
 --output_arrays=dense_3/BiasAdd \
 --input_shape=1,3,448,448
```

引數說明,input_arrays和output_arrays是model的起始輸入變數名和結束變數名,input_shape是和input_arrays對應

官網是說需要用到tenorboard來檢視,一個比較trick的方法

先執行上面的命令,會報convolution2d_1_input找不到,在堆疊裡面有convert_saved_model.py檔案,get_tensors_from_tensor_names()這個方法,新增`print(list(tensor_name_to_tensor))` 到 tensor_name_to_tensor 這個變數下面,再執行一遍,會打印出所有tensor的名字,再根據自己的模型很容易就能判斷出實際的name。

以上這篇Keras模型轉成tensorflow的.pb操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。