当前位置: 首页 > 知识库问答 >
问题:

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

彭存
2023-03-14

我已经使用tensorflow后端训练了一个DNN,我想在FireBase中托管它。训练好的模型被保存为.meta文件,我尝试使用下面的代码将模型转换为tflite,但我遇到了一些错误。那么我如何将这个模型转换成Tensorflow Lite呢?

  File "<ipython-input-3-feb5263f2a51>", line 1, in <module>
    runfile('D:/My Projects/FinalProject_Vr_02/cnn.py', wdir='D:/My Projects/FinalProject_Vr_02')

  File "C:\Users\Asus\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
    execfile(filename, namespace)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "D:/My Projects/FinalProject_Vr_02/cnn.py", line 124, in <module>
    converter = tf.contrib.lite.TFLiteConverter.from_saved_model(MODEL_NAME)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\lite.py", line 340, in from_saved_model
    output_arrays, tag_set, signature_key)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\convert_saved_model.py", line 239, in freeze_saved_model
    meta_graph = get_meta_graph_def(saved_model_dir, tag_set)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\convert_saved_model.py", line 61, in get_meta_graph_def
    return loader.load(sess, tag_set, saved_model_dir)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\python\saved_model\loader_impl.py", line 196, in load
    loader = SavedModelLoader(export_dir)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\python\saved_model\loader_impl.py", line 212, in __init__
    self._saved_model = _parse_saved_model(export_dir)

  File "C:\Users\Asus\Anaconda3\lib\site-packages\tensorflow\python\saved_model\loader_impl.py", line 82, in _parse_saved_model
    constants.SAVED_MODEL_FILENAME_PB))

OSError: SavedModel file does not exist at: 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)

共有1个答案

巫马星雨
2023-03-14

因为错误消息显示“OSERROR:SavedModel文件不存在于:snakes-0.001-2conv-basic.model/{saved_model.pbtxtsaved_model.pb}”

那么为什么不试着打印出MODEL_NAME,并查看一下本地目录,看看模型文件是否在其中。

 类似资料:
  • 我目前在转换张量流时遇到问题。pb模型到TFlite格式。我目前正在遵循谷歌代码实验室的指示,错误说 Traceback(最近调用的最后一次):文件/usr/local/bin/tflite_convert,第5行,在tensorflow.lite.python.tflite_convert导入主重要错误:没有模块命名lite.python.tflite_convert 我正在使用谷歌提供的命令

  • 我想在Tensorflow中将整数量化的tflite模型转换为冻结图(.pb)。我通读并尝试了许多有关StackOverflow的解决方案,但没有一个有效。具体来说,toco不起作用(输出格式不能是TENSORFLOW\u GRAPHDEF)。 我的最终目标是通过tf2onnx获得量化的ONNX模型,但tf2onnx不支持tflite作为输入(只支持保存的_模型、检查点和图形_定义)。但是,在使用

  • (基本)C:\TensorFlow-master>Bazel run--Config=opt\//TensorFlow/contrib/lite/toco:toco--\--input_file=optimized_graph.pb\--output_file=abc.tflite\--input_format=tensorFlow_graphdef\--output_format=tflite\

  • 我目前正在尝试将RNN模型转换为TF lite。在多次尝试失败后,我尝试运行此处存储库中给出的示例。由于层定义位置的变化,这也引发了错误。一旦修复了下面的代码 我继续出错 在使用tf.compat.v1.disable\u eager\u execution()禁用渴望执行后,我得到了错误 有人有在TensorFlow 2.0中将RNN(LSTM、GRU、CustomRNN)转换为TFLite的工

  • 在使用进行实验时,我在将转换为时遇到了一个问题。 这是我的设置: 如果有人能解释转换失败的原因,那就太好了。

  • 我已经使用Keras来微调MobileNet v1。现在我有,我需要将其转换为TensorFlow Lite,以便在Android应用程序中使用。 我使用TFLite转换脚本。我可以在没有量化的情况下进行转换,但我需要更高的性能,所以我需要进行量化。 如果我运行此脚本: 它失败了: F tensorflow/contrib/lite/toco/tooling\u util。cc:1634]Arra