国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級)

這篇具有很好參考價值的文章主要介紹了機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

簡介

準備寫個系列博客介紹機器學習實戰(zhàn)中的部分公開項目。首先從初級項目開始。


本文為初級項目第二篇:利用MNIST數(shù)據(jù)集訓練手寫數(shù)字分類。
項目原網(wǎng)址為:Deep Learning Project – Handwritten Digit Recognition using Python。

第一篇為:機器學習實戰(zhàn) | emojify 使用Python創(chuàng)建自己的表情符號(深度學習初級)

技術(shù)流程

項目構(gòu)想:
MNIST數(shù)字分類項目,使機器能夠識別手寫數(shù)字。該Python項目對于計算機視覺可能非常有用。在這里,我們將使用MNIST數(shù)據(jù)集使用卷積神經(jīng)網(wǎng)絡(luò)訓練模型。

經(jīng)過訓練后,在GUI頁面(gui.py程序)顯示效果如下:左邊是手寫數(shù)字,通過鼠標手寫鍵入;右邊點擊recognise會提示訓練結(jié)果以及識別置信度。
機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級),Deep Learning,python 學習總結(jié),機器學習,分類,深度學習

1. 載入依賴包和數(shù)據(jù)集

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape, y_train.shape)

除了常規(guī)包外,同樣需要提前配置KerasTensorFlow,安裝命令為:

pip install keras==2.10.0
pip install TensorFlow==2.10.0

這里需要注意MNIST手寫數(shù)據(jù)集導入方法,直接從Keras中加載:keras.datasets.mnist

通過mnist.load獲取訓練數(shù)據(jù)和測試數(shù)據(jù),訓練數(shù)據(jù)集維度為: 60000 × 28 × 28 60000 \times 28\times28 60000×28×28,測試數(shù)據(jù)集維度為: 10000 × 28 × 28 10000 \times 28\times28 10000×28×28.

2. 數(shù)據(jù)預處理

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

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

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
  • x_train.reshape:將圖像數(shù)據(jù)轉(zhuǎn)換為神經(jīng)網(wǎng)絡(luò)輸入,圖像大小 60000 × 28 × 28 60000 \times 28\times28 60000×28×28,輸出大小為 60000 × 28 × 28 × 1 60000 \times 28\times28\times1 60000×28×28×1。
  • keras.utils.to_categorical:將阿拉伯數(shù)字的0-9共10個數(shù)字(類別)轉(zhuǎn)換為one-shot特征,用二進制表示分類類別,比如數(shù)字0用0000表示,數(shù)字1用0001表示,數(shù)字2用0010表示。
  • x_train /= 255:將圖像數(shù)據(jù)歸一化,首先將數(shù)據(jù)類型轉(zhuǎn)換為float32,接著將數(shù)據(jù)歸一化到0~1范圍內(nèi)。

3. 創(chuàng)建卷積神經(jīng)網(wǎng)絡(luò)模型

batch_size = 128
num_classes = 10
epochs = 50

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])

該項目設(shè)計了卷積神經(jīng)網(wǎng)絡(luò)(CNN)模型,包括兩層卷積層、池化層、全連接層等。

函數(shù)分析:

  • Sequential:序貫模型,與函數(shù)式模型對立。from keras.models import Sequential, 序貫模型通過一層層神經(jīng)網(wǎng)絡(luò)連接構(gòu)建深度神經(jīng)網(wǎng)絡(luò)。
  • add(): 疊加網(wǎng)絡(luò)層,參數(shù)可為conv2D卷積神經(jīng)網(wǎng)絡(luò)層,MaxPooling2D二維最大池化層,Dropout隨機失活層(防止過擬合),Dense密集層(全連接FC層,在Keras層中FC層被寫作Dense層),下面會詳細介紹這幾個層的含義和參數(shù)設(shè)置。
  • compile(): 編譯神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu),參數(shù)包括:loss,字符串結(jié)構(gòu),指定損失函數(shù)(包括MSE等);optimizer,表示優(yōu)化方式(優(yōu)化器),用于控制梯度裁剪;metrics,列表,用來衡量模型指標,表示評價指標。

網(wǎng)絡(luò)結(jié)構(gòu)介紹:

  • conv2D: 卷積神經(jīng)網(wǎng)絡(luò)層,參數(shù)包括:
  1. filters: 層深度(縱向),一般來說前期數(shù)據(jù)減少,后期數(shù)量逐漸增加,建議選擇 2 N 2^N 2N作為深度,比如說:[32,64,128] => [256,512,1024];
  2. kernel_size: 決定了2D卷積窗口的寬度和高度,一般設(shè)置為 ( 1 × 1 ) (1\times1) (1×1), ( 3 × 3 ) (3\times3) (3×3), ( 5 × 5 ) (5\times5) (5×5), ( 7 × 7 ) (7\times7) (7×7).
  3. activation:激活函數(shù),可選擇為:sigmoid,tanh,relu等
  • MaxPooling2D: 池化層,本質(zhì)上是采樣,對輸入的數(shù)據(jù)進行壓縮,一般用在卷積層后,加快神經(jīng)網(wǎng)絡(luò)的訓練速度。沒有需要學習的參數(shù),數(shù)據(jù)降維,用來防止過擬合現(xiàn)象。
  • Dropout:防過擬合層,在訓練時,忽略一定數(shù)量的特征檢測器,用來增加稀疏性,用伯努利分布(0-1分布)B(1,p)來隨機忽略特征數(shù)量,輸入?yún)?shù)為p的大小
  • Flatten:將多維輸入數(shù)據(jù)一維化,用在卷積層到全連接層的過渡,減少參數(shù)的使用量,避免過擬合現(xiàn)象,無參。
  • Dense:全連接層,將特征非線性變化映射到輸出空間上。

4. 訓練神經(jīng)網(wǎng)絡(luò)

hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
print("The model has successfully trained")

model.save('mnist.h5')
print("Saving the model as mnist.h5")

  • model.fit:在搭建完成后,將數(shù)據(jù)送入模型進行訓練。參數(shù)包括:
  1. x:訓練數(shù)據(jù)輸入;
  2. y:訓練數(shù)據(jù)輸出;
  3. batch_size: batch樣本數(shù)量,即訓練一次網(wǎng)絡(luò)所用的樣本數(shù);
  4. epochs:迭代次數(shù),即全部樣本數(shù)據(jù)將被“輪”多少次,輪完訓練停止;
  5. verbose:可選訓練過程中信息是否輸出參數(shù),0表示不輸出信息,1表示顯示進度條(一般默認為1),2表示每個epoch輸出一行記錄;
  6. valdation_data:驗證數(shù)據(jù)集。
  • model.save:保存訓練模型權(quán)重

訓練成功后,會在源目錄下保存mnist.h5文件,即為權(quán)重文件。

5. 評價網(wǎng)絡(luò)

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
  • model.evaluate:評價網(wǎng)絡(luò),返回值是一個浮點數(shù),表示損失值和評估指標值,輸入?yún)?shù)為測試數(shù)據(jù),verbose表示測試過程中信息是否輸出參數(shù),同樣verbose=0表示不輸出測試信息。

完整程序

train.py : 完整訓練代碼。

gui.py: GUI窗口,輸出可互動的界面。

train.py 程序

"""
Handwrittern digit recognition
"""

"""
1. Import the libraries and load the dataset
"""
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K

import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

print(x_train.shape, y_train.shape)

"""
2. Preprocess the data
"""
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)

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

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

"""
3. Create the model
"""
batch_size = 128
num_classes = 10
epochs = 50

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),activation='relu',input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,optimizer=keras.optimizers.Adadelta(),metrics=['accuracy'])

"""
4. Train the model
"""
hist = model.fit(x_train, y_train,batch_size=batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test))
print("The model has successfully trained")

model.save('mnist.h5')
print("Saving the model as mnist.h5")

"""
5. Evaluate the model
"""
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

訓練結(jié)果會保存在源目錄下,生成文件名為:mnist.h5

gui.py程序

from keras.models import load_model
from tkinter import *
import tkinter as tk
import win32gui
from PIL import ImageGrab, Image
import numpy as np

model = load_model('mnist.h5')

def predict_digit(img):
    #resize image to 28x28 pixels
    img = img.resize((28, 28))
    #convert rgb to grayscale
    img = img.convert('L')
    img = np.array(img)
    #reshaping to support our model input and normalizing
    img = img.reshape(1, 28, 28, 1)
    img = img/255.0
    #predicting the class
    res = model.predict([img])[0]
    return np.argmax(res), max(res)

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        self.x = self.y = 0

        # Creating elements
        self.canvas = tk.Canvas(self, width=300, height=300, bg = "white", cursor="cross")
        self.label = tk.Label(self, text="Thinking..", font=("Helvetica", 48))
        self.classify_btn = tk.Button(self, text = "Recognise", command =self.classify_handwriting)
        self.button_clear = tk.Button(self, text = "Clear", command = self.clear_all)

        # Grid structure
        self.canvas.grid(row=0, column=0, pady=2, sticky=W, )
        self.label.grid(row=0, column=1,pady=2, padx=2)
        self.classify_btn.grid(row=1, column=1, pady=2, padx=2)
        self.button_clear.grid(row=1, column=0, pady=2)

        #self.canvas.bind("<Motion>", self.start_pos)
        self.canvas.bind("<B1-Motion>", self.draw_lines)

    def clear_all(self):
        self.canvas.delete("all")

    def classify_handwriting(self):
        HWND = self.canvas.winfo_id() # get the handle of the canvas
        rect = win32gui.GetWindowRect(HWND) # get the coordinate of the canvas
        im = ImageGrab.grab(rect)

        digit, acc = predict_digit(im)
        self.label.configure(text= str(digit)+', '+ str(int(acc*100))+'%')

    def draw_lines(self, event):
        self.x = event.x
        self.y = event.y
        r=8
        self.canvas.create_oval(self.x-r, self.y-r, self.x + r, self.y + r, fill='black')

app = App()
mainloop()

gui.py程序中用了tkinter包來呈現(xiàn)GUI頁面,具體語句這里就不再分析解釋了,需要學習的話可以參考以下鏈接:Python GUI編程(Tkinter)

gui.py運行后,輸出頁面為:

機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級),Deep Learning,python 學習總結(jié),機器學習,分類,深度學習
通過鍵盤在左側(cè)手寫字符,點擊recognise輸出識別結(jié)果。
機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級),Deep Learning,python 學習總結(jié),機器學習,分類,深度學習


如有問題,歡迎指出和討論。文章來源地址http://www.zghlxwxcb.cn/news/detail-558426.html

到了這里,關(guān)于機器學習實戰(zhàn) | MNIST手寫數(shù)字分類項目(深度學習初級)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • MNIST手寫數(shù)字辨識-cnn網(wǎng)路 (機器學習中的hello world,加油)

    MNIST手寫數(shù)字辨識-cnn網(wǎng)路 (機器學習中的hello world,加油)

    用PyTorch實現(xiàn)MNIST手寫數(shù)字識別(非常詳細) - 知乎 (zhihu.com) 參考來源(這篇文章非常適合入門來看,每個細節(jié)都講解得很到位) 一、模塊函數(shù)用法-查漏補缺: 1.關(guān)于torch.nn.functional.max_pool2d()的用法: 上述示例中,輸入張量 input 經(jīng)過最大池化操作后,使用了 kernel_size=2 和 strid

    2024年02月09日
    瀏覽(44)
  • 機器學習第一周:用卷積神經(jīng)網(wǎng)絡(luò)實現(xiàn)Mnist手寫數(shù)字識別(付基礎(chǔ)知識解釋)

    MNIST 數(shù)據(jù)集是一個手寫數(shù)字識別數(shù)據(jù)集,包含了 60000 張訓練圖像和 10000 張測試圖像,每張圖像都是 28x28 像素的灰度圖像。 在這個代碼中,我們首先使用了 numpy 庫中的 np.random.seed() 方法來設(shè)置隨機種子,以確保結(jié)果可重復。 然后,我們使用了 Keras 中的 mnist.load_data() 方法來

    2024年02月08日
    瀏覽(29)
  • 實戰(zhàn):基于卷積的MNIST手寫體分類

    實戰(zhàn):基于卷積的MNIST手寫體分類

    前面實現(xiàn)了基于多層感知機的MNIST手寫體識別,本章將實現(xiàn)以卷積神經(jīng)網(wǎng)絡(luò)完成的MNIST手寫體識別。 1.? 數(shù)據(jù)的準備 在本例中,依舊使用MNIST數(shù)據(jù)集,對這個數(shù)據(jù)集的數(shù)據(jù)和標簽介紹,前面的章節(jié)已詳細說明過了,相對于前面章節(jié)直接對數(shù)據(jù)進行“折疊”處理,這里需要顯式地

    2024年02月10日
    瀏覽(32)
  • Keras-4-深度學習用于計算機視覺-卷積神經(jīng)網(wǎng)絡(luò)對 MNIST 數(shù)字進行分類:

    本篇學習記錄主要包括:《Python深度學習》的第5章(深度學習用于計算機視覺)的第1節(jié)(卷積神經(jīng)網(wǎng)絡(luò)簡介)內(nèi)容。 相關(guān)知識點: 密集層 (Dense層、全連接層) 和 卷積層的區(qū)別在于: Dense層從輸入特征空間中學到的是全局模式;而卷積層學到的是局部模式 (學到的是卷積核大

    2024年02月11日
    瀏覽(29)
  • 基于PyTorch的MNIST手寫體分類實戰(zhàn)

    基于PyTorch的MNIST手寫體分類實戰(zhàn)

    第2章對MNIST數(shù)據(jù)做了介紹,描述了其構(gòu)成方式及其數(shù)據(jù)的特征和標簽的含義等。了解這些有助于編寫合適的程序來對MNIST數(shù)據(jù)集進行分析和識別。本節(jié)將使用同樣的數(shù)據(jù)集完成對其進行分類的任務(wù)。 3.1.1 ?數(shù)據(jù)圖像的獲取與標簽的說明 MNIST數(shù)據(jù)集的詳細介紹在第2章中已經(jīng)完成

    2024年02月08日
    瀏覽(27)
  • 深度學習筆記(七)——基于Iris/MNIST數(shù)據(jù)集構(gòu)建基礎(chǔ)的分類網(wǎng)絡(luò)算法實戰(zhàn)

    深度學習筆記(七)——基于Iris/MNIST數(shù)據(jù)集構(gòu)建基礎(chǔ)的分類網(wǎng)絡(luò)算法實戰(zhàn)

    文中程序以Tensorflow-2.6.0為例 部分概念包含筆者個人理解,如有遺漏或錯誤,歡迎評論或私信指正。 截圖和程序部分引用自北京大學機器學習公開課 在神經(jīng)網(wǎng)絡(luò)的構(gòu)建過程中,都避不開以下幾個步驟: 導入網(wǎng)絡(luò)和依賴模塊 原始數(shù)據(jù)處理和清洗 加載訓練和測試數(shù)據(jù) 構(gòu)建網(wǎng)絡(luò)

    2024年01月18日
    瀏覽(21)
  • 卷積神經(jīng)網(wǎng)絡(luò)CNN原理+代碼(pytorch實現(xiàn)MNIST集手寫數(shù)字分類任務(wù))

    卷積神經(jīng)網(wǎng)絡(luò)CNN原理+代碼(pytorch實現(xiàn)MNIST集手寫數(shù)字分類任務(wù))

    前言 若將圖像數(shù)據(jù)輸入全連接層,可能會導致喪失一些位置信息 卷積神經(jīng)網(wǎng)絡(luò)將圖像按照原有的空間結(jié)構(gòu)保存,不會喪失位置信息。 卷積運算: 1.以單通道為例: 將將input中選中的部分與kernel進行數(shù)乘 : 以上圖為例對應(yīng)元素相乘結(jié)果為211,并將結(jié)果填入output矩陣的左上角

    2024年02月04日
    瀏覽(24)
  • 人工智能TensorFlow MNIST手寫數(shù)字識別——實戰(zhàn)篇

    人工智能TensorFlow MNIST手寫數(shù)字識別——實戰(zhàn)篇

    上期文章TensorFlow手寫數(shù)字-訓練篇,我們訓練了我們的神經(jīng)網(wǎng)絡(luò),本期使用上次訓練的模型,來識別手寫數(shù)字(本期構(gòu)建TensorFlow神經(jīng)網(wǎng)絡(luò)代碼為上期文章分享代碼) http://scs.ryerson.ca/~aharley/vis/conv/ 0、插入第三方庫 1、圖片處理函數(shù)

    2024年02月15日
    瀏覽(38)
  • 清華青年AI自強作業(yè)hw3_1:用線性回歸模型擬合MNIST手寫數(shù)字分類

    清華青年AI自強作業(yè)hw3_1:用線性回歸模型擬合MNIST手寫數(shù)字分類

    一起學AI系列博客:目錄索引 hw3_1:用線性回歸模型擬合MNIST手寫數(shù)字分類 初步體驗Tensorflow編程環(huán)境 體會用回歸模型網(wǎng)絡(luò)擬合效果 嘗試后發(fā)現(xiàn)hw3_1/hw3_3的參考代碼為TF1.x框架代碼,升級到TF2.x框架多為不便(升級踩坑記錄),于是采用TF2.x中的keras框架重新寫了一遍。 思路分析

    2024年02月10日
    瀏覽(21)
  • 【深度學習實戰(zhàn)—1】:基于Keras的手寫數(shù)字識別(非常詳細、代碼開源)

    【深度學習實戰(zhàn)—1】:基于Keras的手寫數(shù)字識別(非常詳細、代碼開源)

    ?博客主頁:王樂予?? ?年輕人要:Living for the moment(活在當下)!?? ??推薦專欄:【圖像處理】【千錘百煉Python】【深度學習】【排序算法】 ?? 本來想著多更新一些關(guān)于深度學習的文章,但這方面知識專業(yè)度很高,如果作者本身都掌握不好,又怎么能寫出好文章分享

    2024年02月07日
    瀏覽(23)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包