Introduction
TensorFlow Lite conversion makes your machine learning models small and fast so they can run on phones and other small devices.
import tensorflow as tf # Load your trained model model = tf.keras.models.load_model('model.h5') # Create a converter from the model converter = tf.lite.TFLiteConverter.from_keras_model(model) # Convert the model to TensorFlow Lite format lite_model = converter.convert() # Save the converted model with open('model.tflite', 'wb') as f: f.write(lite_model)
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model_dir')
lite_model = converter.convert()converter = tf.lite.TFLiteConverter.from_keras_model(model) converter.optimizations = [tf.lite.Optimize.DEFAULT] lite_model = converter.convert()
converter = tf.lite.TFLiteConverter.from_concrete_functions([func]) lite_model = converter.convert()
import tensorflow as tf import numpy as np # Create a simple model model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(5,)), tf.keras.layers.Dense(1) ]) # Compile and train the model on dummy data model.compile(optimizer='adam', loss='mse') x_train = np.random.random((100, 5)) y_train = np.random.random((100, 1)) model.fit(x_train, y_train, epochs=2, verbose=1) # Convert the trained model to TensorFlow Lite converter = tf.lite.TFLiteConverter.from_keras_model(model) lite_model = converter.convert() # Save the TensorFlow Lite model with open('simple_model.tflite', 'wb') as f: f.write(lite_model) print('TensorFlow Lite model size:', len(lite_model), 'bytes')
model?from_keras_model().tflite_model after conversion?
import tensorflow as tf converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert()
converter = tf.lite.TFLiteConverter.from_saved_model('my_model')
tflite_model = converter.convert()
But got an error: ValueError: SavedModel file does not exist at: my_model. What is the most likely cause?from_keras_model() to create the converter from a Keras model.converter.optimizations = [tf.lite.Optimize.DEFAULT] to enable quantization.convert() to get the quantized TensorFlow Lite model.Pass the test and this pattern moves unknown