訂閱
糾錯
加入自媒體

使用 TensorFlow Lite 在 Android 上進(jìn)行印地語字符識別

介紹

如果你曾經(jīng)想構(gòu)建一個用于文本識別的圖像分類器,我假設(shè)你可能已經(jīng)從 TensorFlow 的官方示例中實現(xiàn)了經(jīng)典的手寫數(shù)字識別應(yīng)用程序 。

該程序通常被稱為計算機(jī)視覺的“Hello World”,它是 ML 初學(xué)者構(gòu)建分類器應(yīng)用程序的一個很好的起點。構(gòu)建一個識別任何字符的自定義分類器不是很好嗎?在這篇文章中,我們將構(gòu)建一個印地語字符識別應(yīng)用程序,但你可以隨意選擇你自己選擇的數(shù)據(jù)集。

我們將構(gòu)建一個能夠識別印地語字符的機(jī)器學(xué)習(xí)模型,而且也可以從頭開始。我們不僅會構(gòu)建機(jī)器學(xué)習(xí)模型,還會將其部署在 Android 移動應(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ù)集,對吧?讓我們回憶一下。

MNIST 數(shù)字?jǐn)?shù)據(jù)庫image.png

MNIST 代表“Modified National Institute of Standards and Technology”,是一個流行的手寫數(shù)字識別數(shù)據(jù)庫,包含超過 60,000 張數(shù)字 0-9 的圖像,F(xiàn)在,了解 MNIST 數(shù)據(jù)庫的外觀和格式很重要,因為我們將合成一個“類似于 MNIST”的印地語字符數(shù)據(jù)集。

MNIST 數(shù)據(jù)集中的每個數(shù)字都是一個 28 x 28 的二進(jìn)制圖像,顏色為白色,背景為黑色。

MNIST 數(shù)字示例

好的,現(xiàn)在我們有了想法,讓我們?yōu)橛〉卣Z字符合成我們的數(shù)據(jù)集。我已經(jīng)將數(shù)據(jù)集保存在我的 GitHub 存儲庫中。

該數(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] 之間被矢量化到單個“.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ù)組

同樣,各個訓(xùn)練圖像的標(biāo)簽也被矢量化并捆綁到單個“.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 個類( - ?、?、?、? 和 ?)訓(xùn)練模型。該數(shù)據(jù)集涵蓋了所有元音、輔音和數(shù)字,因此你可以隨意選擇任何類別。

標(biāo)準(zhǔn)化輸入圖像

在這里,我們通過將每個像素除以 255 來歸一化輸入圖像,因此每個像素的值都在 [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 個類的模型,每個類有大約 200 張圖像。訓(xùn)練模型的時間將根據(jù)你為用例選擇的每個類和圖像的數(shù)量而有所不同。在模型訓(xùn)練時,去喝杯咖啡。

量化(Quantization)

我們已經(jīng)完成了這個博客的一半。TensorFlow 模型已準(zhǔn)備就緒。但是,要在移動應(yīng)用程序上使用此模型,我們需要對其進(jìn)行量化并將其轉(zhuǎn)換為 TF Lite 格式,這是原始 TF 模型的更輕量級版本。

量化允許在模型的準(zhǔn)確性和大小之間進(jìn)行有價值的權(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ā)了一個用于字符識別的 Android 應(yīng)用程序。在第 1 步中,你可能已經(jīng)克隆了存儲庫。在那里,你應(yīng)該找到Android_App目錄。

復(fù)制 Hindi-Character-Recognition-on-Android-using-TensorFlow-Lite/Android_App/app/src/main/assets 目錄中的 mnist.tflite  模型文件。

接下來,在 Android Studio 中打開項目并讓它自己構(gòu)建一段時間。構(gòu)建項目后,打開DigitClassifier.kt文件并編輯第 333 行,將其替換為模型中輸出類的數(shù)量。

同樣,在DigitClassifier.kt文件中,通過根據(jù)你的自定義數(shù)據(jù)集設(shè)置標(biāo)簽名稱來編輯 第 118 行到第 132 行。

最后,再次構(gòu)建項目并將其安裝在你的 Android 手機(jī)上,并享受你自己定制的印地語字符識別應(yīng)用程序。

最終應(yīng)用

結(jié)論

快速總結(jié)一下:

· 我們從數(shù)據(jù)準(zhǔn)備開始,合成一個類似于 MNIST 的數(shù)據(jù)集,用于印地語字符識別,由元音、輔音和數(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)建了一個 Android 應(yīng)用程序,并在其上部署了我們的分類器模型。

       原文標(biāo)題 : 使用 TensorFlow Lite 在 Android 上進(jìn)行印地語字符識別

聲明: 本文由入駐維科號的作者撰寫,觀點僅代表作者本人,不代表OFweek立場。如有侵權(quán)或其他問題,請聯(lián)系舉報。

發(fā)表評論

0條評論,0人參與

請輸入評論內(nèi)容...

請輸入評論/評論長度6~500個字

您提交的評論過于頻繁,請輸入驗證碼繼續(xù)

暫無評論

暫無評論

人工智能 獵頭職位 更多
掃碼關(guān)注公眾號
OFweek人工智能網(wǎng)
獲取更多精彩內(nèi)容
文章糾錯
x
*文字標(biāo)題:
*糾錯內(nèi)容:
聯(lián)系郵箱:
*驗 證 碼:

粵公網(wǎng)安備 44030502002758號