简体   繁体   中英

Converting pb to tflite and getting valueerror

I am trying to convert my pb to tflite using this code. I got the code from github ( ImageCaptioning ). The authors made use of this code to convert their model, and I was able to make the pb model, but encountered some issues while trying to convert the pb model to tflite.

import tensorflow as tf
from tensorflow.python.platform import gfile
import cv2
import numpy as np


def main():
    sess = tf.Session()
    GRAPH_LOCATION = 'C:/Users/User/Documents/models-master/research/im2txt/im2txt/data/output_graph.pb'
    VOCAB_FILE = 'C:/Users/User/Documents/models-master/research/im2txt/Pretrained-Show-and-Tell-model-master/word_counts.txt'
    IMAGE_FILE = 'C:/Users/User/Documents/models-master/research/im2txt/g3doc/COCO_val2014_000000224477.jpg'

    # Read model
    with gfile.FastGFile(GRAPH_LOCATION, 'rb') as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())
        sess.graph.as_default()
        tf.import_graph_def(graph_def)

    with tf.gfile.GFile(IMAGE_FILE, "rb") as f:
        encoded_image = f.read()

    input_names = ['import/image_feed:0', 'import/input_feed:0', 'import/lstm/state_feed:0']
    output_names = ['import/softmax:0', 'import/lstm/state:0', 'import/lstm/initial_state:0']

    g = tf.get_default_graph()
    input_tensors = [g.get_tensor_by_name(x) for x in input_names]  
    output_tensors = [g.get_tensor_by_name(x) for x in output_names]


    converter = tf.lite.TFLiteConverter.from_session(sess, input_tensors, output_tensors)
    model = converter.convert()
    fid = open("C:/Users/User/Documents/models-master/research/im2txt/im2txt/data/converted_model.tflite", "wb")
    fid.write(model)
    fid.close()


if __name__ == '__main__':
    main()

but I am getting this error:

   "'{0}'.".format(_get_tensor_name(tensor)))
ValueError: Provide an input shape for input array 'import/image_feed'.

I am new to tfLite and I am unable to find the issue pertaining to the code.

Root-cause of the error is input_shape of input array. You need to provide input shape to the converter. You could inspect *.pb file using tensorboard or netron to find input_shapes . Check an example as follows.

import tensorflow as tf
graph_def_file = "./Mymodel.pb"
tflite_file = 'mytflite.tflite'

input_arrays = ["input"]
output_arrays = ["output"]

converter = tf.lite.TFLiteConverter.from_frozen_graph(
   graph_def_file=graph_def_file,
   input_arrays=input_arrays,
   output_arrays=output_arrays,input_shapes={'input_mel':[ 1, 32, 32]})

tflite_model = converter.convert()

open(tflite_file,'wb').write(tflite_model)

interpreter = tf.lite.Interpreter(model_content=tflite_model)
interpreter.allocate_tensors()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM