使用 TensorFlow Lite 在 Android 上進(jìn)行印地語(yǔ)字符識(shí)別
介紹
如果你曾經(jīng)想構(gòu)建一個(gè)用于文本識(shí)別的圖像分類(lèi)器,我假設(shè)你可能已經(jīng)從 TensorFlow 的官方示例中實(shí)現(xiàn)了經(jīng)典的手寫(xiě)數(shù)字識(shí)別應(yīng)用程序 。
該程序通常被稱(chēng)為計(jì)算機(jī)視覺(jué)的“Hello World”,它是 ML 初學(xué)者構(gòu)建分類(lèi)器應(yīng)用程序的一個(gè)很好的起點(diǎn)。構(gòu)建一個(gè)識(shí)別任何字符的自定義分類(lèi)器不是很好嗎?在這篇文章中,我們將構(gòu)建一個(gè)印地語(yǔ)字符識(shí)別應(yīng)用程序,但你可以隨意選擇你自己選擇的數(shù)據(jù)集。
我們將構(gòu)建一個(gè)能夠識(shí)別印地語(yǔ)字符的機(jī)器學(xué)習(xí)模型,而且也可以從頭開(kāi)始。我們不僅會(huì)構(gòu)建機(jī)器學(xué)習(xí)模型,還會(huì)將其部署在 Android 移動(dòng)應(yīng)用程序上。因此,本文將作為端到端教程,涵蓋構(gòu)建和部署 ML 應(yīng)用程序所需的幾乎所有內(nèi)容。
端到端流
數(shù)據(jù)準(zhǔn)備
我們需要大量數(shù)據(jù)來(lái)訓(xùn)練應(yīng)該產(chǎn)生良好結(jié)果的機(jī)器學(xué)習(xí)模型。你一定聽(tīng)說(shuō)過(guò) MNIST 數(shù)據(jù)集,對(duì)吧?讓我們回憶一下。
MNIST 數(shù)字?jǐn)?shù)據(jù)庫(kù)
MNIST 代表“Modified National Institute of Standards and Technology”,是一個(gè)流行的手寫(xiě)數(shù)字識(shí)別數(shù)據(jù)庫(kù),包含超過(guò) 60,000 張數(shù)字 0-9 的圖像,F(xiàn)在,了解 MNIST 數(shù)據(jù)庫(kù)的外觀和格式很重要,因?yàn)槲覀儗⒑铣梢粋(gè)“類(lèi)似于 MNIST”的印地語(yǔ)字符數(shù)據(jù)集。
MNIST 數(shù)據(jù)集中的每個(gè)數(shù)字都是一個(gè) 28 x 28 的二進(jìn)制圖像,顏色為白色,背景為黑色。
MNIST 數(shù)字示例
好的,現(xiàn)在我們有了想法,讓我們?yōu)橛〉卣Z(yǔ)字符合成我們的數(shù)據(jù)集。我已經(jīng)將數(shù)據(jù)集保存在我的 GitHub 存儲(chǔ)庫(kù)中。
該數(shù)據(jù)集包含所有印地語(yǔ)元音、輔音和數(shù)字。
這些圖像必須轉(zhuǎn)換為 NumPy 數(shù)組 (.npz),以供模型訓(xùn)練使用。下面的腳本將幫助你進(jìn)行轉(zhuǎn)換。
導(dǎo)入依賴
import tensorflow as tf
from tensorflow import keras
from PIL import Image
import os
import numpy as np
import matplotlib.pyplot as plt
import random
!pip install -q kaggle
!pip install -q kaggle-cli
print(tf.__version__)
import os
os.environ['KAGGLE_USERNAME'] = ""
os.environ['KAGGLE_KEY'] = ""
!kaggle datasets download -d nstiwari/hindi-character-recognition --unzip
將 JPG 圖像轉(zhuǎn)換為 NPZ(NumPy 數(shù)組)格式
# Converts all the images inside HindiCharacterRecognition/raw_images/10 into NPZ format.
path_to_files = "/content/HindiCharacterRecognition/raw_images/10/"
vectorized_images = []
for _, file in enumerate(os.listdir(path_to_files)):
image = Image.open(path_to_files + file)
image_array = np.a(chǎn)rray(image)
vectorized_images.a(chǎn)ppend(image_array)
np.savez("./10.npz", DataX=vectorized_images)
加載訓(xùn)練圖像 NumPy 數(shù)組
訓(xùn)練圖像被矢量化為 NumPy 數(shù)組。換句話說(shuō),訓(xùn)練圖像的像素在值 [0, 255] 之間被矢量化到單個(gè)“.npz”文件中。
path = "./HindiCharacterRecognition/vectorized_images/numeral_images.npz"
with np.load(path) as data:
#load DataX as train_data
train_images = data['DataX']
加載訓(xùn)練標(biāo)簽 NumPy 數(shù)組
同樣,各個(gè)訓(xùn)練圖像的標(biāo)簽也被矢量化并捆綁到單個(gè)“.npz”文件中。與圖像數(shù)組不同,標(biāo)簽數(shù)組包含從 0 到 n-1 的離散值,其中 n = 類(lèi)的數(shù)量。
path = "./HindiCharacterRecognition/vectorized_labels/numeral_labels.npz"
with np.load(path) as data:
#load DataX as train_data
train_labels = data['DataX']
NO_OF_CLASSES = 5 # Change the no. of classes according to your custom dataset
在此示例中,我正在為 5 個(gè)類(lèi)( - ?、?、?、? 和 ?)訓(xùn)練模型。該數(shù)據(jù)集涵蓋了所有元音、輔音和數(shù)字,因此你可以隨意選擇任何類(lèi)別。
標(biāo)準(zhǔn)化輸入圖像
在這里,我們通過(guò)將每個(gè)像素除以 255 來(lái)歸一化輸入圖像,因此每個(gè)像素的值都在 [0, 1] 之間。
值為 0 的像素是黑色的,而值為 1 的像素是白色的。介于 0 和 1 之間的任何值都是灰色的,其強(qiáng)度取決于離得最近的一端。
色標(biāo)
# Normalize the input image so that each pixel value is between 0 to 1.
train_images = train_images / 255.0
print('Pixels are normalized.')
檢查圖像和標(biāo)簽數(shù)組的形狀
· 圖像陣列的形狀應(yīng)為 (X, 28, 28),其中 X = 圖像的數(shù)量。
· 標(biāo)簽數(shù)組的形狀應(yīng)為 (X, )。
注意:圖像的數(shù)量和標(biāo)簽的數(shù)量應(yīng)該相等。
train_images.shape
train_labels.shape
可視化訓(xùn)練數(shù)據(jù)
# Show the first 50 images in the training dataset.
j = 0
plt.figure(figsize = (10, 10))
for i in range(550, 600): # Try playing with difference ranges in interval of 50. Example: range(250, 300)
j = j + 1
plt.subplot(10, 5, j)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap = plt.cm.gray)
plt.xlabel(train_labels[i])
plt.show()
數(shù)據(jù)集預(yù)覽
我們的數(shù)據(jù)集現(xiàn)在看起來(lái)很完美,可以接受訓(xùn)練了。
模型訓(xùn)練
讓我們從模型訓(xùn)練開(kāi)始。
在下面的單元格中,我們定義了模型的層并設(shè)置了超參數(shù),例如優(yōu)化器、損失函數(shù)、指標(biāo)、類(lèi)和epoch的數(shù)量來(lái)量化模型性能。
# Define the model architecture.
model = keras.Sequential([
keras.layers.InputLayer(input_shape=(28, 28)),
keras.layers.Reshape(target_shape = (28, 28, 1)),
keras.layers.Conv2D(filters=32, kernel_size = (3, 3), activation = tf.nn.relu),
keras.layers.Conv2D(filters=64, kernel_size = (3, 3), activation = tf.nn.relu),
keras.layers.MaxPooling2D(pool_size = (2, 2)),
keras.layers.Dropout(0.25),
keras.layers.Flatten(),
keras.layers.Dense(NO_OF_CLASSES)
])
# Define how to train the model
model.compile(optimizer = 'adam',
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits = True),
metrics = ['accuracy'])
# Train the digit classification model
model.fit(train_images, train_labels, epochs = 50)
model.summary()
我花了大約 30-45 分鐘來(lái)訓(xùn)練 5 個(gè)類(lèi)的模型,每個(gè)類(lèi)有大約 200 張圖像。訓(xùn)練模型的時(shí)間將根據(jù)你為用例選擇的每個(gè)類(lèi)和圖像的數(shù)量而有所不同。在模型訓(xùn)練時(shí),去喝杯咖啡。
量化(Quantization)
我們已經(jīng)完成了這個(gè)博客的一半。TensorFlow 模型已準(zhǔn)備就緒。但是,要在移動(dòng)應(yīng)用程序上使用此模型,我們需要對(duì)其進(jìn)行量化并將其轉(zhuǎn)換為 TF Lite 格式,這是原始 TF 模型的更輕量級(jí)版本。
量化允許在模型的準(zhǔn)確性和大小之間進(jìn)行有價(jià)值的權(quán)衡。隨著精度的輕微下降,模型大小可以大大減小,從而使其部署更容易。
將 TF 模型轉(zhuǎn)換為 TF Lite 格式
# Convert Keras model to TF Lite format.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_float_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_float_model)
# Show model size in KBs.
float_model_size = len(tflite_float_model) / 1024
print('Float model size = %dKBs.' % float_model_size)
# Re-convert the model to TF Lite using quantization.
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_quantized_model = converter.convert()
# Show model size in KBs.
quantized_model_size = len(tflite_quantized_model) / 1024
print('Quantized model size = %dKBs,' % quantized_model_size)
print('which is about %d%% of the float model size.' % (quantized_model_size * 100 / float_model_size))
# Save the quantized model to file to the Downloads directory
f = open('mnist.tflite', "wb")
f.write(tflite_quantized_model)
f.close()
# Download the digit classification model
from google.colab import files
files.download('mnist.tflite')
print('`mnist.tflite` has been downloaded')
我們現(xiàn)在已經(jīng)準(zhǔn)備好將 TF Lite 模型部署到 Android 應(yīng)用程序上。
部署模型
已經(jīng)開(kāi)發(fā)了一個(gè)用于字符識(shí)別的 Android 應(yīng)用程序。在第 1 步中,你可能已經(jīng)克隆了存儲(chǔ)庫(kù)。在那里,你應(yīng)該找到Android_App目錄。
復(fù)制 Hindi-Character-Recognition-on-Android-using-TensorFlow-Lite/Android_App/app/src/main/assets 目錄中的 mnist.tflite 模型文件。
接下來(lái),在 Android Studio 中打開(kāi)項(xiàng)目并讓它自己構(gòu)建一段時(shí)間。構(gòu)建項(xiàng)目后,打開(kāi)DigitClassifier.kt文件并編輯第 333 行,將其替換為模型中輸出類(lèi)的數(shù)量。
同樣,在DigitClassifier.kt文件中,通過(guò)根據(jù)你的自定義數(shù)據(jù)集設(shè)置標(biāo)簽名稱(chēng)來(lái)編輯 第 118 行到第 132 行。
最后,再次構(gòu)建項(xiàng)目并將其安裝在你的 Android 手機(jī)上,并享受你自己定制的印地語(yǔ)字符識(shí)別應(yīng)用程序。
最終應(yīng)用
結(jié)論
快速總結(jié)一下:
· 我們從數(shù)據(jù)準(zhǔn)備開(kāi)始,合成一個(gè)類(lèi)似于 MNIST 的數(shù)據(jù)集,用于印地語(yǔ)字符識(shí)別,由元音、輔音和數(shù)字組成;向量化圖像和標(biāo)簽以輸入神經(jīng)網(wǎng)絡(luò)。
· 接下來(lái),我們通過(guò)添加 Keras 層來(lái)構(gòu)建模型,配置超參數(shù)并開(kāi)始模型訓(xùn)練。
· 在訓(xùn)練完 TF 模型后,我們將其量化并轉(zhuǎn)換為 TF Lite 格式,以使其準(zhǔn)備好部署。
· 最后,我們構(gòu)建了一個(gè) Android 應(yīng)用程序,并在其上部署了我們的分類(lèi)器模型。
原文標(biāo)題 : 使用 TensorFlow Lite 在 Android 上進(jìn)行印地語(yǔ)字符識(shí)別

發(fā)表評(píng)論
請(qǐng)輸入評(píng)論內(nèi)容...
請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字
最新活動(dòng)更多
-
3月27日立即報(bào)名>> 【工程師系列】汽車(chē)電子技術(shù)在線大會(huì)
-
4月30日立即下載>> 【村田汽車(chē)】汽車(chē)E/E架構(gòu)革新中,新智能座艙挑戰(zhàn)的解決方案
-
5月15-17日立即預(yù)約>> 【線下巡回】2025年STM32峰會(huì)
-
即日-5.15立即報(bào)名>>> 【在線會(huì)議】安森美Hyperlux™ ID系列引領(lǐng)iToF技術(shù)革新
-
5月15日立即下載>> 【白皮書(shū)】精確和高效地表征3000V/20A功率器件應(yīng)用指南
-
5月16日立即參評(píng) >> 【評(píng)選啟動(dòng)】維科杯·OFweek 2025(第十屆)人工智能行業(yè)年度評(píng)選
推薦專(zhuān)題
- 1 UALink規(guī)范發(fā)布:挑戰(zhàn)英偉達(dá)AI統(tǒng)治的開(kāi)始
- 2 北電數(shù)智主辦酒仙橋論壇,探索AI產(chǎn)業(yè)發(fā)展新路徑
- 3 降薪、加班、裁員三重暴擊,“AI四小龍”已折戟兩家
- 4 “AI寒武紀(jì)”爆發(fā)至今,五類(lèi)新物種登上歷史舞臺(tái)
- 5 國(guó)產(chǎn)智駕迎戰(zhàn)特斯拉FSD,AI含量差幾何?
- 6 光計(jì)算迎來(lái)商業(yè)化突破,但落地仍需時(shí)間
- 7 東陽(yáng)光:2024年扭虧、一季度凈利大增,液冷疊加具身智能打開(kāi)成長(zhǎng)空間
- 8 地平線自動(dòng)駕駛方案解讀
- 9 封殺AI“照騙”,“淘寶們”終于不忍了?
- 10 優(yōu)必選:營(yíng)收大增主靠小件,虧損繼續(xù)又逢關(guān)稅,能否乘機(jī)器人東風(fēng)翻身?