tensorflow直接在代码中通过代码直接生成.lite文件

Tensorflow Lite之编译生成tflite文件这篇文章中提到的在代码中生成lite文件会报错,可以按照如下修改

import tensorflow as tf
# manually put back imported modules
import tempfile
import subprocess
tf.contrib.lite.tempfile = tempfile
tf.contrib.lite.subprocess = subprocess

img = tf.placeholder(name="img", dtype=tf.float32, shape=(1, 64, 64, 3))
val = img + tf.constant([1., 2., 3.]) + tf.constant([1., 4., 4.])
out = tf.identity(val, name="out")
with tf.Session() as sess:
  tflite_model = tf.contrib.lite.toco_convert(sess.graph_def, [img], [out])
  open("converteds_model.tflite", "wb").write(tflite_model)

keras搭建模型转换实例

K.clear_session()

weight_path='./48net.h5'

input = Input(shape = [48,48,3],batch_shape=[1,48, 48, 3],name='image')
x = Conv2D(32, (3, 3), strides=1, padding='valid', name='conv1')(input)
x = PReLU(shared_axes=[1,2],name='prelu1')(x)
x = MaxPool2D(pool_size=3, strides=2, padding='same')(x)
x = Conv2D(64, (3, 3), strides=1, padding='valid', name='conv2')(x)
x = PReLU(shared_axes=[1,2],name='prelu2')(x)
x = MaxPool2D(pool_size=3, strides=2)(x)
x = Conv2D(64, (3, 3), strides=1, padding='valid', name='conv3')(x)
x = PReLU(shared_axes=[1,2],name='prelu3')(x)
x = MaxPool2D(pool_size=2)(x)
x = Conv2D(128, (2, 2), strides=1, padding='valid', name='conv4')(x)
x = PReLU(shared_axes=[1,2],name='prelu4')(x)
x = Permute((3,2,1))(x)
x = Flatten()(x)
x = Dense(256, name='conv5') (x)
x = PReLU(name='prelu5')(x)
classifier = Dense(2, activation='softmax',name='conv6-1')(x)
bbox_regress = Dense(4,name='conv6-2')(x)
landmark_regress = Dense(10,name='conv6-3')(x)
model = Model([input], [classifier, bbox_regress, landmark_regress])
model.load_weights(weight_path, by_name=True)

export_dir = './tflite/'
sess = K.get_session()
frozen_graphdef = tf.graph_util.convert_variables_to_constants(
      sess, sess.graph_def, ['conv6-1/Softmax', 'conv6-2/BiasAdd'])
tflite_model = tf.contrib.lite.toco_convert(frozen_graphdef, [input], [classifier,bbox_regress])
open(export_dir+"Onet.tflite", "wb").write(tflite_model)

input 一定要带上batch_shape

你可能感兴趣的:(tensorflow直接在代码中通过代码直接生成.lite文件)