使用 TensorFlow Lite 在 Android 上進(jìn)行印地語字符識(shí)別
介紹
如果你曾經(jīng)想構(gòu)建一個(gè)用于文本識(shí)別的圖像分類器,我假設(shè)你可能已經(jīng)從 TensorFlow 的官方示例中實(shí)現(xiàn)了經(jīng)典的手寫數(shù)字識(shí)別應(yīng)用程序 。
該程序通常被稱為計(jì)算機(jī)視覺的“Hello World”,它是 ML 初學(xué)者構(gòu)建分類器應(yīng)用程序的一個(gè)很好的起點(diǎn)。構(gòu)建一個(gè)識(shí)別任何字符的自定義分類器不是很好嗎?在這篇文章中,我們將構(gòu)建一個(gè)印地語字符識(shí)別應(yīng)用程序,但你可以隨意選擇你自己選擇的數(shù)據(jù)集。
我們將構(gòu)建一個(gè)能夠識(shí)別印地語字符的機(jī)器學(xué)習(xí)模型,而且也可以從頭開始。我們不僅會(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ù)來訓(xùn)練應(yīng)該產(chǎn)生良好結(jié)果的機(jī)器學(xué)習(xí)模型。你一定聽說過 MNIST 數(shù)據(jù)集,對(duì)吧?讓我們回憶一下。
MNIST 數(shù)字?jǐn)?shù)據(jù)庫
MNIST 代表“Modified National Institute of Standards and Technology”,是一個(gè)流行的手寫數(shù)字識(shí)別數(shù)據(jù)庫,包含超過 60,000 張數(shù)字 0-9 的圖像,F(xiàn)在,了解 MNIST 數(shù)據(jù)庫的外觀和格式很重要,因?yàn)槲覀儗⒑铣梢粋(gè)“類似于 MNIST”的印地語字符數(shù)據(jù)集。
MNIST 數(shù)據(jù)集中的每個(gè)數(shù)字都是一個(gè) 28 x 28 的二進(jìn)制圖像,顏色為白色,背景為黑色。
MNIST 數(shù)字示例
好的,現(xiàn)在我們有了想法,讓我們?yōu)橛〉卣Z字符合成我們的數(shù)據(jù)集。我已經(jīng)將數(shù)據(jù)集保存在我的 GitHub 存儲(chǔ)庫中。
該數(shù)據(jù)集包含所有印地語元音、輔音和數(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ù)組。換句話說,訓(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 = 類的數(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è)類( - ?、?、?、? 和 ?)訓(xùn)練模型。該數(shù)據(jù)集涵蓋了所有元音、輔音和數(shù)字,因此你可以隨意選擇任何類別。
標(biāo)準(zhǔn)化輸入圖像
在這里,我們通過將每個(gè)像素除以 255 來歸一化輸入圖像,因此每個(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)在看起來很完美,可以接受訓(xùn)練了。
模型訓(xùn)練
讓我們從模型訓(xùn)練開始。
在下面的單元格中,我們定義了模型的層并設(shè)置了超參數(shù),例如優(yōu)化器、損失函數(shù)、指標(biāo)、類和epoch的數(shù)量來量化模型性能。
# 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 分鐘來訓(xùn)練 5 個(gè)類的模型,每個(gè)類有大約 200 張圖像。訓(xùn)練模型的時(shí)間將根據(jù)你為用例選擇的每個(gè)類和圖像的數(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)開發(fā)了一個(gè)用于字符識(shí)別的 Android 應(yīng)用程序。在第 1 步中,你可能已經(jīng)克隆了存儲(chǔ)庫。在那里,你應(yīng)該找到Android_App目錄。
復(fù)制 Hindi-Character-Recognition-on-Android-using-TensorFlow-Lite/Android_App/app/src/main/assets 目錄中的 mnist.tflite 模型文件。
接下來,在 Android Studio 中打開項(xiàng)目并讓它自己構(gòu)建一段時(shí)間。構(gòu)建項(xiàng)目后,打開DigitClassifier.kt文件并編輯第 333 行,將其替換為模型中輸出類的數(shù)量。
同樣,在DigitClassifier.kt文件中,通過根據(jù)你的自定義數(shù)據(jù)集設(shè)置標(biāo)簽名稱來編輯 第 118 行到第 132 行。
最后,再次構(gòu)建項(xiàng)目并將其安裝在你的 Android 手機(jī)上,并享受你自己定制的印地語字符識(shí)別應(yīng)用程序。
最終應(yīng)用
結(jié)論
快速總結(jié)一下:
· 我們從數(shù)據(jù)準(zhǔn)備開始,合成一個(gè)類似于 MNIST 的數(shù)據(jù)集,用于印地語字符識(shí)別,由元音、輔音和數(shù)字組成;向量化圖像和標(biāo)簽以輸入神經(jīng)網(wǎng)絡(luò)。
· 接下來,我們通過添加 Keras 層來構(gòu)建模型,配置超參數(shù)并開始模型訓(xùn)練。
· 在訓(xùn)練完 TF 模型后,我們將其量化并轉(zhuǎn)換為 TF Lite 格式,以使其準(zhǔn)備好部署。
· 最后,我們構(gòu)建了一個(gè) Android 應(yīng)用程序,并在其上部署了我們的分類器模型。
原文標(biāo)題 : 使用 TensorFlow Lite 在 Android 上進(jìn)行印地語字符識(shí)別

發(fā)表評(píng)論
請(qǐng)輸入評(píng)論內(nèi)容...
請(qǐng)輸入評(píng)論/評(píng)論長度6~500個(gè)字
最新活動(dòng)更多
-
即日-6.16立即報(bào)名>> 【在線會(huì)議】Solution Talks |Computex 2025關(guān)鍵趨勢(shì)深讀
-
6月20日立即下載>> 【白皮書】精準(zhǔn)測(cè)量 安全高效——福祿克光伏行業(yè)解決方案
-
7月3日立即報(bào)名>> 【在線會(huì)議】英飛凌新一代智能照明方案賦能綠色建筑與工業(yè)互聯(lián)
-
7月22-29日立即報(bào)名>> 【線下論壇】第三屆安富利汽車生態(tài)圈峰會(huì)
-
7.30-8.1火熱報(bào)名中>> 全數(shù)會(huì)2025(第六屆)機(jī)器人及智能工廠展
-
7月31日免費(fèi)預(yù)約>> OFweek 2025具身機(jī)器人動(dòng)力電池技術(shù)應(yīng)用大會(huì)
推薦專題
- 1 AI 眼鏡讓百萬 APP「集體失業(yè)」?
- 2 大廠紛紛入局,百度、阿里、字節(jié)搶奪Agent話語權(quán)
- 3 深度報(bào)告|中國AI產(chǎn)業(yè)正在崛起成全球力量,市場(chǎng)潛力和關(guān)鍵挑戰(zhàn)有哪些?
- 4 上海跑出80億超級(jí)獨(dú)角獸:獲上市公司戰(zhàn)投,干人形機(jī)器人
- 5 國家數(shù)據(jù)局局長劉烈宏調(diào)研格創(chuàng)東智
- 6 下一代入口之戰(zhàn):大廠為何紛紛押注智能體?
- 7 百億AI芯片訂單,瘋狂傾銷中東?
- 8 Robotaxi新消息密集釋放,量產(chǎn)元年誰在領(lǐng)跑?
- 9 格斗大賽出圈!人形機(jī)器人致命短板曝光:頭腦過于簡(jiǎn)單
- 10 為何全球AI巨頭都在搶?MCP協(xié)議背后的暴富玄機(jī)大公開!