|
| 1 | +""" |
| 2 | +This example retrieves a model from tensorflowhub. |
| 3 | +It is converted into ONNX. Predictions are compared to |
| 4 | +the predictions from tensorflow to check there is no |
| 5 | +discrepencies. Inferencing time is also compared between |
| 6 | +*onnxruntime*, *tensorflow* and *tensorflow.lite*. |
| 7 | +""" |
| 8 | +from onnxruntime import InferenceSession |
| 9 | +import os |
| 10 | +import subprocess |
| 11 | +import timeit |
| 12 | +import numpy as np |
| 13 | +import tensorflow as tf |
| 14 | +from tensorflow import keras |
| 15 | +from tensorflow.keras import layers, Input |
| 16 | +from tensorflow.python.saved_model import tag_constants |
| 17 | +import tensorflow_hub as tfhub |
| 18 | + |
| 19 | +######################################## |
| 20 | +# Downloads the model. |
| 21 | +hub_layer = tfhub.KerasLayer( |
| 22 | + "https://tfhub.dev/google/efficientnet/b0/classification/1") |
| 23 | +model = keras.Sequential() |
| 24 | +model.add(tf.keras.Input(shape=(224, 224, 3), dtype=tf.float32)) |
| 25 | +model.add(hub_layer) |
| 26 | +print(model.summary()) |
| 27 | + |
| 28 | +######################################## |
| 29 | +# Saves the model. |
| 30 | +if not os.path.exists("efficientnetb0clas"): |
| 31 | + os.mkdir("efficientnetb0clas") |
| 32 | +tf.keras.models.save_model(model, "efficientnetb0clas") |
| 33 | + |
| 34 | +input_names = [n.name for n in model.inputs] |
| 35 | +output_names = [n.name for n in model.outputs] |
| 36 | +print('inputs:', input_names) |
| 37 | +print('outputs:', output_names) |
| 38 | + |
| 39 | +######################################## |
| 40 | +# Testing the model. |
| 41 | +input = np.random.randn(2, 224, 224, 3).astype(np.float32) |
| 42 | +expected = model.predict(input) |
| 43 | +print(expected) |
| 44 | + |
| 45 | +######################################## |
| 46 | +# Run the command line. |
| 47 | +proc = subprocess.run( |
| 48 | + 'python -m tf2onnx.convert --saved-model efficientnetb0clas ' |
| 49 | + '--output efficientnetb0clas.onnx --opset 12'.split(), |
| 50 | + capture_output=True) |
| 51 | +print(proc.returncode) |
| 52 | +print(proc.stdout.decode('ascii')) |
| 53 | +print(proc.stderr.decode('ascii')) |
| 54 | + |
| 55 | +######################################## |
| 56 | +# Runs onnxruntime. |
| 57 | +session = InferenceSession("efficientnetb0clas.onnx") |
| 58 | +got = session.run(None, {'input_1:0': input}) |
| 59 | +print(got[0]) |
| 60 | + |
| 61 | +######################################## |
| 62 | +# Measures the differences. |
| 63 | +print(np.abs(got[0] - expected).max()) |
| 64 | + |
| 65 | +######################################## |
| 66 | +# Measures processing time. |
| 67 | +print('tf:', timeit.timeit('model.predict(input)', |
| 68 | + number=10, globals=globals())) |
| 69 | +print('ort:', timeit.timeit("session.run(None, {'input_1:0': input})", |
| 70 | + number=10, globals=globals())) |
| 71 | + |
| 72 | +######################################## |
| 73 | +# Freezes the graph with tensorflow.lite. |
| 74 | +converter = tf.lite.TFLiteConverter.from_saved_model("efficientnetb0clas") |
| 75 | +tflite_model = converter.convert() |
| 76 | +with open("efficientnetb0clas.tflite", "wb") as f: |
| 77 | + f.write(tflite_model) |
| 78 | + |
| 79 | +# Builds an interpreter. |
| 80 | +interpreter = tf.lite.Interpreter(model_path='efficientnetb0clas.tflite') |
| 81 | +interpreter.allocate_tensors() |
| 82 | +input_details = interpreter.get_input_details() |
| 83 | +output_details = interpreter.get_output_details() |
| 84 | +print("input_details", input_details) |
| 85 | +print("output_details", output_details) |
| 86 | +index = input_details[0]['index'] |
| 87 | + |
| 88 | + |
| 89 | +def tflite_predict(input, interpreter=interpreter, index=index): |
| 90 | + res = [] |
| 91 | + for i in range(input.shape[0]): |
| 92 | + interpreter.set_tensor(index, input[i:i + 1]) |
| 93 | + interpreter.invoke() |
| 94 | + res.append(interpreter.get_tensor(output_details[0]['index'])) |
| 95 | + return np.vstack(res) |
| 96 | + |
| 97 | + |
| 98 | +print(input[0:1].shape, "----", input_details[0]['shape']) |
| 99 | +output_data = tflite_predict(input, interpreter, index) |
| 100 | +print(output_data) |
| 101 | + |
| 102 | +######################################## |
| 103 | +# Measures processing time again. |
| 104 | + |
| 105 | +print('tf:', timeit.timeit('model.predict(input)', |
| 106 | + number=10, globals=globals())) |
| 107 | +print('ort:', timeit.timeit("session.run(None, {'input_1:0': input})", |
| 108 | + number=10, globals=globals())) |
| 109 | +print('tflite:', timeit.timeit('tflite_predict(input)', |
| 110 | + number=10, globals=globals())) |
0 commit comments