0
本文作者: skura | 2019-10-17 17:27 |
本教程介紹如何使用 tf.Keras 時(shí)序 API 從頭開始訓(xùn)練模型,將 tf.Keras 模型轉(zhuǎn)換為 tflite 格式,并在 Android 上運(yùn)行該模型。我將以 MNIST 數(shù)據(jù)為例介紹圖像分類,并分享一些你可能會(huì)面臨的常見問題。本教程著重于端到端的體驗(yàn),我不會(huì)深入探討各種 tf.Keras API 或 Android 開發(fā)。
下載我的示例代碼并執(zhí)行以下操作:
在 colab 中運(yùn)行:使用 tf.keras 的訓(xùn)練模型,并將 keras 模型轉(zhuǎn)換為 tflite(鏈接到 Colab notebook)。
在 Android Studio 中運(yùn)行:DigitRecognizer(鏈接到Android應(yīng)用程序)。
1.訓(xùn)練自定義分類器
加載數(shù)據(jù)
我們將使用作為tf.keras框架一部分的mnst數(shù)據(jù)。
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
預(yù)處理數(shù)據(jù)
接下來,我們將輸入圖像從 28x28 變?yōu)?28x28x1 的形狀,將其標(biāo)準(zhǔn)化,并對標(biāo)簽進(jìn)行 one-hot 編碼。
定義模型體系結(jié)構(gòu)
然后我們將用 cnn 定義網(wǎng)絡(luò)架構(gòu)。
def create_model():
# Define the model architecture
model = keras.models.Sequential([
# Must define the input shape in the first layer of the neural network
keras.layers.Conv2D(filters=32, kernel_size=3, padding='same', activation='relu', input_shape=(28,28,1)),
keras.layers.MaxPooling2D(pool_size=2),
keras.layers.Dropout(0.3),
keras.layers.Conv2D(filters=64, kernel_size=3, padding='same', activation='relu'),
keras.layers.MaxPooling2D(pool_size=2),
keras.layers.Dropout(0.3),
keras.layers.Flatten(),
keras.layers.Dense(128, activation='relu'),
keras.layers.Dropout(0.5),
keras.layers.Dense(10, activation='softmax')
])
# Compile the model
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.Adam(),
metrics=['accuracy'])
return model
訓(xùn)練模型
然后我們使用 model.fit()來訓(xùn)練模型。
model.fit(x_train,
y_train,
batch_size=64,
epochs=3,
validation_data=(x_test, y_test))
2.模型保存和轉(zhuǎn)換
訓(xùn)練結(jié)束后,我們將保存一個(gè) Keras 模型并將其轉(zhuǎn)換為 TFLite 格式。
保存一個(gè) Keras 模型
下面是保存 Keras 模型的方法-
# Save tf.keras model in HDF5 format
keras_model = "mnist_keras_model.h5"
keras.models.save_model(model, keras_model)
將keras模型轉(zhuǎn)換為tflite
當(dāng)使用 TFLite 轉(zhuǎn)換器將 Keras 模型轉(zhuǎn)換為 TFLite 格式時(shí),有兩個(gè)選擇- 1)從命令行轉(zhuǎn)換,或 2)直接在 python 代碼中轉(zhuǎn)換,這個(gè)更加推薦。
1)通過命令行轉(zhuǎn)換
$ tflite_convert \
$ --output_file=mymodel.tflite \
$ --keras_model_file=mymodel.h5
2)通過 python 代碼轉(zhuǎn)換
如果你可以訪問模型訓(xùn)練代碼,則這是轉(zhuǎn)換的首選方法。
# Convert the model
flite_model = converter.convert()
# Create the tflite model file
tflite_model_name = "mymodel.tflite"
open(tflite_model_name, "wb").write(tflite_model)
你可以將轉(zhuǎn)換器的訓(xùn)練后量化設(shè)置為 true。
# Set quantize to true
converter.post_training_quantize=True
驗(yàn)證轉(zhuǎn)換的模型
將 Keras 模型轉(zhuǎn)換為 TFLite 格式后,驗(yàn)證它是否能夠與原始 Keras 模型一樣正常運(yùn)行是很重要的。請參閱下面關(guān)于如何使用 TFLite 模型運(yùn)行推斷的 python 代碼片段。示例輸入是隨機(jī)輸入數(shù)據(jù),你需要根據(jù)自己的數(shù)據(jù)更新它。
# Load TFLite model and allocate tensors. interpreter = tf.contrib.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()
# Get input and output tensors
input_details = interpreter.get_input_details() output_details = interpreter.get_output_details()
# Test model on random input data
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape),
dtype=np.float32) interpreter.set_tensor(input_details[0]['index'], input_data)
interpreter.invoke()
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)
ps:確保在轉(zhuǎn)換后和將 TFLite 模型放到 Android 上面之前始終測試它。否則,當(dāng)它在你的 Android 應(yīng)用程序上不能工作時(shí),你無法分清是你的 android 代碼有問題還是 ML 模型有問題。
3.在 Android 上實(shí)現(xiàn) tflite 模型
現(xiàn)在我們準(zhǔn)備在 Android 上實(shí)現(xiàn) TFLite 模型。創(chuàng)建一個(gè)新的 Android 項(xiàng)目并遵循以下步驟
將 mnist.tflite 模型放在 assets 文件夾下
更新 build.gradle 以包含 tflite 依賴項(xiàng)
為用戶創(chuàng)建自定義視圖
創(chuàng)建一個(gè)進(jìn)行數(shù)字分類的分類器
從自定義視圖輸入圖像
圖像預(yù)處理
用模型對圖像進(jìn)行分類
后處理
在用戶界面中顯示結(jié)果
Classifier 類是大多數(shù) ML 魔術(shù)發(fā)生的地方。確保在類中設(shè)置的維度與模型預(yù)期的維度匹配:
28x28x1 的圖像
10 位數(shù)字的 10 個(gè)類:0、1、2、3…9
要對圖像進(jìn)行分類,請執(zhí)行以下步驟:
預(yù)處理輸入圖像。將位圖轉(zhuǎn)換為 bytebuffer 并將像素轉(zhuǎn)換為灰度,因?yàn)?MNIST 數(shù)據(jù)集是灰度的。
使用由內(nèi)存映射到 assets 文件夾下的模型文件創(chuàng)建的解釋器運(yùn)行推斷。
后處理輸出結(jié)果以在 UI 中顯示。我們得到的結(jié)果有 10 種可能,我們將選擇在 UI 中顯示概率最高的數(shù)字。
過程中的挑戰(zhàn)
以下是你可能遇到的挑戰(zhàn):
在 tflite 轉(zhuǎn)換期間,如果出現(xiàn)「tflite 不支持某個(gè)操作」的錯(cuò)誤,則應(yīng)請求 tensorflow 團(tuán)隊(duì)添加該操作或自己創(chuàng)建自定義運(yùn)算符。
有時(shí),轉(zhuǎn)換似乎是成功的,但轉(zhuǎn)換后的模型卻不起作用:例如,轉(zhuǎn)換后的分類器可能在正負(fù)測試中以~0.5 的精度隨機(jī)分類。(我在 tf 1.10 中遇到了這個(gè)錯(cuò)誤,后來在 tf1.12 中修復(fù)了它)。
如果 Android 應(yīng)用程序崩潰,請查看 logcat 中的 stacktrace 錯(cuò)誤:
確保輸入圖像大小和顏色通道設(shè)置正確,以匹配模型期望的輸入張量大小。
確保 in build.gradle aaptoptions 設(shè)置為不壓縮 tflite 文件。
aaptOptions {
noCompress "tflite"
}
總體來說,用 tf.Keras 訓(xùn)練一個(gè)簡單的圖像分類器是輕而易舉的,保存 Keras 模型并將其轉(zhuǎn)換為 TFLite 也相當(dāng)容易。目前,我們在 Android 上實(shí)現(xiàn) TFLite 模型的方法仍然有點(diǎn)單調(diào),希望將來能有所改進(jìn)。
via:https://medium.com/@margaretmz/e2e-tfkeras-tflite-android-273acde6588
雷鋒網(wǎng)雷鋒網(wǎng)雷鋒網(wǎng)
雷峰網(wǎng)版權(quán)文章,未經(jīng)授權(quán)禁止轉(zhuǎn)載。詳情見轉(zhuǎn)載須知。