搜尋

從資料到部署

Nov 03, 2024 am 01:43 AM

DataWhisper:掌握深度學習專案生命週期

作者:Abdellah Hallou(LinkedIn、Twitter)

歡迎來到深度學習計畫入門指南!本教程為任何想要深入學習令人興奮的深度學習世界的人提供了全面的資源。無論您是初學者還是經驗豐富的開發人員,本指南都將引導您從頭到尾完成建立深度學習專案的過程。

目錄

  • 你將學到什麼
  • 誰該學本教學
  • 需要幫助或有疑問?
  • 讓我們開始吧!
  • 匯入並載入資料集
  • 資料集結構
  • 探索性資料分析 (EDA)
  • 預處理資料
  • 建構模型
  • 評估準確度
  • 儲存並匯出模型
  • 做出預測
  • 部署
    • 建立一個新的flutter專案
    • 設定相機
    • 建立相機螢幕
    • 整合圖片上傳
    • 使用 TensorFlow Lite 進行物體辨識
    • 在影像上運行模型
    • 在對話框中顯示結果
    • 建構使用者介面

你將學到什麼

在本教程中,您將學習在行動應用程式中建立和部署深度學習模型所涉及的基本步驟。我們將涵蓋以下主題:

  1. 準備資料:我們將探索各種資料預處理方法,以確保訓練資料集穩健可靠。

  2. 模型建立:您將了解如何設計和建造 CNN 模型。

  3. 訓練模型:我們將深入研究使用 TensorFlow 訓練深度學習模型的過程。

  4. 在行動應用中部署:模型訓練完成後,我們將引導您完成使用 TensorFlow Lite 將其整合到行動應用中的步驟。您將了解如何隨時隨地進行預測!

誰應該學習本教程

本教學適合對深度學習概念和 Python 程式設計有基本了解的初學者和中級開發人員。無論您是資料科學家、機器學習愛好者還是行動應用開發人員,本指南都將為您提供啟動深度學習專案所需的知識。

需要協助或有疑問嗎?

如果您在學習本教學課程時遇到任何問題、有疑問或需要進一步說明,請隨時在此儲存庫「從資料到部署」中建立 GitHub 問題。我將非常樂意為您提供協助並提供必要的指導。

要建立問題,請按一下此儲存庫頁面頂部的「問題」 選項卡,然後按一下「新問題」 按鈕。請提供盡可能多的有關您所面臨的問題或疑問的背景和詳細資訊。這將幫助我更了解您的疑慮,並為您提供及時、準確的答案。

您的回饋很有價值,也可以幫助其他使用者改進本教學。因此,如果您需要任何幫助,請隨時與我們聯繫。讓我們一起學習,一起成長吧!

讓我們開始吧!

首先,請確保您已安裝所需的依賴項和程式庫。本教程分為幾個易於理解的部分,每個部分涵蓋深度學習專案工作流程的特定方面。請隨意跳至您最感興趣的部分或從頭到尾閱讀。

你準備好了嗎?

導入並載入資料集

讓我們開始對我們的程式碼進行必要的導入。我們將在本教程中使用 Fashion Mnist 資料集。

# Import the necessary libraries
from __future__ import print_function
import keras
from google.colab import drive
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.wrappers.scikit_learn import KerasClassifier
from keras import backend as K
from sklearn.model_selection import GridSearchCV
import tensorflow as tf
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt

資料集結構

在任何深度學習專案中,理解數據至關重要。在深入模型創建和訓練之前,我們首先載入資料並深入了解其結構、變數和整體特徵。

# Load the Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

探索性資料分析 (EDA)

現在資料已加載,讓我們執行一些探索性資料分析,以便更好地了解其特徵。

print("Shape of the training data : ",x_train.shape)
print("Shape of the testing data : ",x_test.shape)
Shape of the training data :  (60000, 28, 28)
Shape of the testing data :  (10000, 28, 28)

時尚 MNIST 資料集包含 10 個類別的 70,000 個 灰階影像。這些影像以低解析度顯示單件衣物(28 x 28 像素),如下所示:
From Data to Deployment

60,000 張影像用於訓練網絡,10,000 張影像用於評估網路學習分類影像的準確性。

# Printing unique values in training data
unique_labels = np.unique(y_train, axis=0)
print("Unique labels in training data:", unique_labels)
Unique labels in training data: [0 1 2 3 4 5 6 7 8 9]

標籤是一個整數數組,範圍從 0 到 9。它們對應於圖像代表的服裝類別:
|標籤| R類 |
| - |-|
| 0 | T卹/上衣|
| 1 |褲子|
| 2 |套頭衫|
| 3 |洋裝|
| 4 |外套|
| 5 |涼鞋|
| 6 |襯衫|
| 7 |運動鞋 |
| 8 |包|
| 9 | 及踝靴|

由於類別名稱不包含在資料集中,因此將它們儲存在此處以便稍後在繪製圖像時使用:

# Numeric labels
numeric_labels = np.sort(np.unique(y_train, axis=0))
# String labels
string_labels = np.array(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'])
# Mapping numeric labels to string labels
numeric_to_string = dict(zip(numeric_labels, string_labels))
print("Numeric to String Label Mapping:")
print(numeric_to_string)
Numeric to String Label Mapping:
{0: 'T-shirt/top', 1: 'Trouser', 2: 'Pullover', 3: 'Dress', 4: 'Coat', 5: 'Sandal', 6: 'Shirt', 7: 'Sneaker', 8: 'Bag', 9: 'Ankle boot'}

預處理數據

在訓練網路之前必須先對資料進行預處理。
我們首先定義資料集中的類別數(本例為 10)和輸入影像的尺寸(28x28 像素)。

# Import the necessary libraries
from __future__ import print_function
import keras
from google.colab import drive
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.wrappers.scikit_learn import KerasClassifier
from keras import backend as K
from sklearn.model_selection import GridSearchCV
import tensorflow as tf
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt

這部分負責重塑輸入影像資料以符合神經網路模型的預期格式。格式取決於所使用的後端(例如 TensorFlow 或 Theano)。在此程式碼片段中,我們使用 K.image_data_format() 檢查影像資料格式,並根據結果應用適當的重塑。

# Load the Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

資料中影像的像素值在0到255的範圍內。
在將這些值輸入 CNN 模型之前,將它們縮放到 0 到 1 的範圍。

print("Shape of the training data : ",x_train.shape)
print("Shape of the testing data : ",x_test.shape)

將類別標籤(表示為整數)轉換為二進位類別矩陣格式,這是多類別分類問題所需的。

Shape of the training data :  (60000, 28, 28)
Shape of the testing data :  (10000, 28, 28)

建構模型

在這一步驟中,我們定義並建立用於影像分類的捲積神經網路(CNN)模型。模型架構由多個層組成,例如卷積層、池化層、dropout 層和密集層。 build_model 函數將類別的數量、訓練和測試資料作為輸入,並傳回訓練歷史記錄和建構的模型。

# Printing unique values in training data
unique_labels = np.unique(y_train, axis=0)
print("Unique labels in training data:", unique_labels)
Unique labels in training data: [0 1 2 3 4 5 6 7 8 9]
# Numeric labels
numeric_labels = np.sort(np.unique(y_train, axis=0))
# String labels
string_labels = np.array(['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'])
# Mapping numeric labels to string labels
numeric_to_string = dict(zip(numeric_labels, string_labels))
print("Numeric to String Label Mapping:")
print(numeric_to_string)

評估準確性

為了評估訓練模型的效能,我們根據測試資料進行評估。評估方法用於計算測試損失和準確性。然後這些指標將列印到控制台。

Numeric to String Label Mapping:
{0: 'T-shirt/top', 1: 'Trouser', 2: 'Pullover', 3: 'Dress', 4: 'Coat', 5: 'Sandal', 6: 'Shirt', 7: 'Sneaker', 8: 'Bag', 9: 'Ankle boot'}

From Data to Deployment

num_classes = 10
# input image dimensions
img_rows, img_cols = 28, 28
if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

儲存並匯出模型

訓練模型後,我們使用 save 方法將其儲存為分層資料格式 (HDF5) 檔案格式。然後透過呼叫 move_to_drive 函數將模型匯出到 Google Drive。此外,使用 h52tflite 函數將模型轉換為 TensorFlow Lite 格式,產生的 TFLite 模型也儲存在 Google Drive 中。傳回已儲存的模型和TFLite模型的路徑。

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

做出預測

為了視覺化模型的預測,我們隨機選擇一組測試影像。該模型使用預測方法預測這些圖像的類別標籤。然後將預測標籤與地面真實標籤進行比較,以使用 matplotlib.
顯示影像及其對應的預測標籤

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

From Data to Deployment

有關模型的更多信息,請查看以下資源:

  1. https://www.tensorflow.org/tutorials/keras/classification
  2. https://github.com/cmasch/zalando-fashion-mnist/tree/master

部署

建立一個新的 Flutter 項目

在建立新的 Flutter 專案之前,請確保正確安裝 Flutter SDK 和其他 Flutter 應用程式開發相關的要求:https://docs.flutter.dev/get-started/install/windows

專案建立後,我們將實作 UI 以允許使用者拍照或從圖庫上傳映像,並使用匯出的 TensorFlow Lite 模型執行物件辨識。
首先,我們需要安裝這些軟體包:

  1. 相機:0.10.4
  2. 影像選擇器:
  3. tflite:^1.1.2

為此,請複製以下程式碼片段並將其貼到專案的 pubspec.yaml 檔案中:

# Import the necessary libraries
from __future__ import print_function
import keras
from google.colab import drive
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.wrappers.scikit_learn import KerasClassifier
from keras import backend as K
from sklearn.model_selection import GridSearchCV
import tensorflow as tf
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt

在專案的main.dart檔案中匯入必要的套件

# Load the Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

配置相機

為了啟用相機功能,我們將使用camera套件。首先,導入必要的套件並實例化相機控制器。使用 availableCameras() 函數取得可用攝影機的清單。在本教程中,我們將使用清單中的第一個相機。

print("Shape of the training data : ",x_train.shape)
print("Shape of the testing data : ",x_test.shape)

創建相機螢幕

建立一個名為 CameraScreen 的新 StatefulWidget,它將處理相機預覽和影像擷取功能。在 initState() 方法中,初始化相機控制器並設定解析度預設。此外,實作 _takePicture() 方法,該方法使用相機控制器捕捉影像。

Shape of the training data :  (60000, 28, 28)
Shape of the testing data :  (10000, 28, 28)

整合圖片上傳

要允許使用者從圖庫上傳映像,請匯入 image_picker 套件。實作 _pickImage() 方法,該方法利用 ImagePicker 類別從圖庫中選取映像。選擇影像後,可以使用 _processImage() 方法對其進行處理。

# Printing unique values in training data
unique_labels = np.unique(y_train, axis=0)
print("Unique labels in training data:", unique_labels)

使用 TensorFlow Lite 進行物件識別

為了執行物件識別,我們將使用 TensorFlow Lite。首先導入 tflite 套件。在 _initTensorFlow() 方法中,從資產載入 TensorFlow Lite 模型和標籤。您可以指定模型和標籤檔案路徑並調整執行緒數和 GPU 委託使用等設定。

# Import the necessary libraries
from __future__ import print_function
import keras
from google.colab import drive
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.wrappers.scikit_learn import KerasClassifier
from keras import backend as K
from sklearn.model_selection import GridSearchCV
import tensorflow as tf
from keras.utils.vis_utils import plot_model
import matplotlib.pyplot as plt

在圖像上運行模型

實作 _objectRecognition() 方法,該方法將影像檔案路徑作為輸入並在影像上運行 TensorFlow Lite 模型。此方法傳回已識別物件的標籤。

# Load the Fashion MNIST dataset
fashion_mnist = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion_mnist.load_data()

在對話方塊中顯示結果

處理影像時,使用 showDialog() 方法在對話方塊中顯示結果。自訂對話方塊以顯示已識別的物件標籤並提供取消選項。

print("Shape of the training data : ",x_train.shape)
print("Shape of the testing data : ",x_test.shape)

建構使用者介面

Shape of the training data :  (60000, 28, 28)
Shape of the testing data :  (10000, 28, 28)

From Data to Deployment
From Data to Deployment

以上是從資料到部署的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
了解差異:用於循環和python中的循環了解差異:用於循環和python中的循環May 16, 2025 am 12:17 AM

theDifferenceBetweewneaforoopandawhileLoopInpythonisthataThataThataThataThataThataThataNumberoFiterationSiskNownInAdvance,而leleawhileLoopisusedWhenaconDitionNeedneedneedneedNeedStobeCheckedStobeCheckedStobeCheckedStobeCheckedStobeceDrepeTysepectients.peatsiveSectlyStheStobeCeptellyWithnumberofiterations.1)forloopsareAceareIdealForitoringercortersence

Python循環控制:對於vs -a -a比較Python循環控制:對於vs -a -a比較May 16, 2025 am 12:16 AM

在Python中,for循環適用於已知迭代次數的情況,而while循環適合未知迭代次數且需要更多控制的情況。 1)for循環適用於遍歷序列,如列表、字符串等,代碼簡潔且Pythonic。 2)while循環在需要根據條件控制循環或等待用戶輸入時更合適,但需注意避免無限循環。 3)性能上,for循環略快,但差異通常不大。選擇合適的循環類型可以提高代碼的效率和可讀性。

如何在Python中結合兩個列表:5種簡單的方法如何在Python中結合兩個列表:5種簡單的方法May 16, 2025 am 12:16 AM

在Python中,可以通過五種方法合併列表:1)使用 運算符,簡單直觀,適用於小列表;2)使用extend()方法,直接修改原列表,適用於需要頻繁更新的列表;3)使用列表解析式,簡潔且可對元素進行操作;4)使用itertools.chain()函數,內存高效,適合大數據集;5)使用*運算符和zip()函數,適用於需要配對元素的場景。每種方法都有其特定用途和優缺點,選擇時應考慮項目需求和性能。

循環時循環:python語法,用例和示例循環時循環:python語法,用例和示例May 16, 2025 am 12:14 AM

foroopsare whenthenemberofiterationsisknown,而whileLoopsareUseduntilacTitionismet.1)ForloopSareIdealForeSequencesLikeLists,UsingSyntaxLike'forfruitinFruitinFruitinFruitIts:print(fruit)'。 2)'

python串聯列表列表python串聯列表列表May 16, 2025 am 12:08 AM

toConcateNateAlistofListsInpython,useextend,listComprehensions,itertools.Chain,orrecursiveFunctions.1)ExtendMethodStraightForwardButverBose.2)listComprechencomprechensionsareconconconciseandemandeconeandefforlargerdatasets.3)

Python中的合併列表:選擇正確的方法Python中的合併列表:選擇正確的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作員,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入兩個列表?如何在Python 3中加入兩個列表?May 14, 2025 am 12:09 AM

在Python3中,可以通過多種方法連接兩個列表:1)使用 運算符,適用於小列表,但對大列表效率低;2)使用extend方法,適用於大列表,內存效率高,但會修改原列表;3)使用*運算符,適用於合併多個列表,不修改原列表;4)使用itertools.chain,適用於大數據集,內存效率高。

Python串聯列表字符串Python串聯列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中從列表連接字符串最有效的方法。 1)使用join()方法高效且易讀。 2)循環使用 運算符對大列表效率低。 3)列表推導式與join()結合適用於需要轉換的場景。 4)reduce()方法適用於其他類型歸約,但對字符串連接效率低。完整句子結束。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)