如何将Tensorflow模型转换为TFLite模型

时间:2018-12-04 17:49:48

标签: python tensorflow deep-learning tensorflow-lite

  

我已经使用tensorflow后端训练了DNN,我想托管它   在火力中。经过训练的模型另存为 .meta 文件,   试图将模型转换成    tflite 使用以下代码,但出现了一些错误。那么如何将这个模型转换为Tensorflow Lite?

错误

文件“”,第1行,在     runfile('D:/ My Projects / FinalProject_Vr_02 / cnn.py',wdir ='D:/ My Projects / FinalProject_Vr_02')

Runfile中的文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py”,行704     execfile(文件名,命名空间)

execfile中的文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ spyder_kernels \ customize \ spydercustomize.py”,第108行     exec(compile(f.read(),文件名,'exec'),命名空间)

文件“ D:/ My Projects / FinalProject_Vr_02 / cnn.py”,第124行,在     converter = tf.contrib.lite.TFLiteConverter.from_saved_model(MODEL_NAME)

文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ contrib \ lite \ python \ lite.py”,行340,在from_saved_model中     output_arrays,tag_set,signature_key)

文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ contrib \ lite \ python \ convert_saved_model.py”,第239行,在freeze_saved_model中     meta_graph = get_meta_graph_def(saved_model_dir,tag_set)

get_meta_graph_def中的第61行,文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ contrib \ lite \ python \ convert_saved_model.py”     返回loader.load(sess,tag_set,Saved_model_dir)

文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ python \ saved_model \ loader_impl.py”,第196行,已加载     loader = SavedModelLoader(export_dir)

init 中的第212行“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ python \ saved_model \ loader_impl.py”     self._saved_model = _parse_saved_model(export_dir)

文件“ C:\ Users \ Asus \ Anaconda3 \ lib \ site-packages \ tensorflow \ python \ saved_model \ loader_impl.py”,第82行,在_parse_saved_model中     常量。SAVED_MODEL_FILENAME_PB))

OSError:SavedModel文件不存在于:snakes-0.001-2conv-basic.model / {saved_model.pbtxt | saved_model.pb}

import cv2                
import numpy as np     
import os                
from random import shuffle
from tqdm import tqdm  

TRAIN_DIR = 'D:\\My Projects\\Dataset\\dataset5_for_testing\\train'
TEST_DIR = 'D:\\My Projects\\Dataset\\dataset5_for_testing\\test'
IMG_SIZE = 50
LR = 1e-3

MODEL_NAME = 'snakes-{}-{}.model'.format(LR, '2conv-basic')

def label_img(img):
    print("\nimg inside label_img",img)
    print("\n",img.split('.')[-2])
    temp_name= img.split('.')[-2]
    print("\n",temp_name[:1])
    temp_name=temp_name[:1]
    word_label = temp_name


    if word_label == 'A': return [0,0,0,0,1]    #A_c 
    elif word_label == 'B': return [0,0,0,1,0]  #B_h
    elif word_label == 'C': return [0,0,1,0,0]  #C_i
    elif word_label == 'D': return [0,1,0,0,0]  #D_r    
    elif word_label == 'E' : return [1,0,0,0,0] #E_s

def create_train_data():
    training_data = []
    for img in tqdm(os.listdir(TRAIN_DIR)):
        label = label_img(img)
        path = os.path.join(TRAIN_DIR,img)
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))
        training_data.append([np.array(img),np.array(label)])
    shuffle(training_data)
    np.save('train_data.npy', training_data)
    return training_data


def process_test_data():
    testing_data = []
    for img in tqdm(os.listdir(TEST_DIR)):
        path = os.path.join(TEST_DIR,img)
        img_num = img.split('.')[0]
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))
        testing_data.append([np.array(img), img_num])
    shuffle(testing_data)
    np.save('test_data.npy', testing_data)
    return testing_data

train_data = create_train_data()


import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression
'''
from tflearn.data_preprocessing import ImagePreprocessing
from tflearn.data_augmentation import ImageAugmentation

# normalisation of images
img_prep = ImagePreprocessing()
img_prep.add_featurewise_zero_center()
img_prep.add_featurewise_stdnorm()

# Create extra synthetic training data by flipping & rotating images
img_aug = ImageAugmentation()
img_aug.add_random_flip_leftright()
img_aug.add_random_rotation(max_angle=25.)
'''


import tensorflow as tf
tf.reset_default_graph()

#convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input',data_preprocessing=img_prep, data_augmentation=img_aug)
convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')



convnet = conv_2d(convnet, 32, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 64, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 128, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 64, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 32, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = fully_connected(convnet, 1024, activation='relu')
convnet = dropout(convnet, 0.8)

convnet = fully_connected(convnet, 5, activation='softmax')
convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')

model = tflearn.DNN(convnet, tensorboard_dir='log')



if os.path.exists('{}.meta'.format(MODEL_NAME)):
    model.load(MODEL_NAME)
    print('model loaded!')

#train = train_data[:-500]
#test = train_data[-500:]

train = train_data[:-200]
test = train_data[-200:]

X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
Y = [i[1] for i in train]

test_x = np.array([i[0] for i in test]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
test_y = [i[1] for i in test]

model.fit({'input': X}, {'targets': Y}, n_epoch=3, validation_set=({'input': test_x}, {'targets': test_y}), 
    snapshot_step=500, show_metric=True, run_id=MODEL_NAME)


model.save(MODEL_NAME)


converter = tf.contrib.lite.TFLiteConverter.from_saved_model(MODEL_NAME)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

3 个答案:

答案 0 :(得分:1)

由于错误消息显示“ OSError:SavedModel文件在以下位置不存在:snakes-0.001-2conv-basic.model / {saved_model.pbtxt | saved_model.pb}”

那么,为什么不尝试打印出MODEL_NAME并同时查看本地目录以查看其中是否存在模型文件。

答案 1 :(得分:1)

我也在学习这一部分。但是正如我尝试过的那样,精简版转换可以接受冻结图或SavedModel。对于冻结图,您可以在https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/tutorials/post_training_quant.ipynb中看到示例。在底部的优化现有模型可以提供一些想法。

对于tf.contrib.lite.TFLiteConverter.from_saved_model,您应该传递包含一个.pb文件和一个变量文件夹的目录。就我自己而言,保存模型时,我得到了目录结构,就像

SAVED_MODEL_FOLDER
     |---TIMESTEMP_FOLDER
             |---VARIABLES_FOLDER
             |---SAVED_MODEL.pb

然后,如果您通过调用tf.contrib.lite.TFLiteConverter.from_saved_model({TIMESTAMP_FOLDER})

进行转换,该错误将消失。

答案 2 :(得分:0)

仅转换模型。您需要将其转换为TFLite图形,然后使用TOCO掩盖器。

我是亲自完成的,步骤在这里(https://apiai-aws-heroku-nodejs-bots.blogspot.com/2020/04/convert-tensorflow-object-detection.html)。