keras轉tensorflow lite【方法二】直接轉:簡單模型例項

有石為玉發表於2019-01-08

在youtube看到一個很讚的視訊,直接將簡單keras模型轉tensorflow lite,中間不經過轉tensorflow的過程。

之後有空會貼出具體實現圖示。現在只貼出連結和程式碼。

連結:https://www.youtube.com/watch?v=MZx1fhbL2q4

程式碼:

import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.contrib import lite

model = keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])])
model.compile(optimizer='sgd', loss='mean_squared_error')

xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float)
ys = np.array([-3.0, -1.0, 0.0, 3.0, 5.0, 7.0], dtype=float)

model.fit(xs, ys, epochs=500)

print(model.predict([10.0]))

keras_file = "linear.h5"
keras.models.save_model(model, keras_file)

#converter = lite.TocoConverter.from_keras_model_file(keras_file)
converter = lite.TFLiteConverter.from_keras_model_file(keras_file)
tflite_model = converter.convert()
open("linear.tflite", "wb").write(tflite_model)

環境:linux

圖示:

相關文章