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

手寫數(shù)字識別及python實現(xiàn)

這篇具有很好參考價值的文章主要介紹了手寫數(shù)字識別及python實現(xiàn)。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

目錄

1、總體流程

2、代碼實現(xiàn)

下載數(shù)據(jù)集

確定激活函數(shù)、損失函數(shù)、計算梯度函數(shù)等

神經(jīng)網(wǎng)絡(luò)的搭建

模型的訓(xùn)練與驗證?

測試模型的泛化能力


1、總體流程

手寫數(shù)字識別及python實現(xiàn)

step1:下載數(shù)據(jù)集、讀取數(shù)據(jù)
step2:搭建神經(jīng)網(wǎng)絡(luò)(確定輸出層、隱藏層(層數(shù))、輸出層的結(jié)構(gòu))
step3:初始化偏置和權(quán)重
step4:設(shè)置損失函數(shù)、激活函數(shù)
step5:設(shè)置超參數(shù)
step6:神經(jīng)網(wǎng)絡(luò)訓(xùn)練數(shù)據(jù)(通過誤差反向傳播求導(dǎo)、學(xué)習)
step7:測試驗證數(shù)據(jù)集(確定Loss、精確度)
step8:測試模型的泛化能力(輸入自己手寫的數(shù)字進行判斷)

2、代碼實現(xiàn)

下載數(shù)據(jù)集

# coding: utf-8
try:
    import urllib.request
except ImportError:
    raise ImportError('You should use Python 3.x')
import os.path
import gzip
import pickle
import os
import numpy as np


url_base = 'http://yann.lecun.com/exdb/mnist/'
key_file = {
    'train_img':'train-images-idx3-ubyte.gz',
    'train_label':'train-labels-idx1-ubyte.gz',
    'test_img':'t10k-images-idx3-ubyte.gz',
    'test_label':'t10k-labels-idx1-ubyte.gz'
}

dataset_dir = os.path.abspath('.')
save_file = dataset_dir + "/mnist.pkl"

train_num = 60000
test_num = 10000
img_dim = (1, 28, 28)
img_size = 784


def _download(file_name):
    file_path = dataset_dir + "/" + file_name
    
    if os.path.exists(file_path):
        return

    print("Downloading " + file_name + " ... ")
    urllib.request.urlretrieve(url_base + file_name, file_path)
    print("Done")
    
def download_mnist():
    for v in key_file.values():
       _download(v)
        
def _load_label(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")
    with gzip.open(file_path, 'rb') as f:
            labels = np.frombuffer(f.read(), np.uint8, offset=8)
    print("Done")
    
    return labels

def _load_img(file_name):
    file_path = dataset_dir + "/" + file_name
    
    print("Converting " + file_name + " to NumPy Array ...")    
    with gzip.open(file_path, 'rb') as f:
            data = np.frombuffer(f.read(), np.uint8, offset=16)
    data = data.reshape(-1, img_size)
    print("Done")
    
    return data
    
def _convert_numpy():
    dataset = {}
    dataset['train_img'] =  _load_img(key_file['train_img'])
    dataset['train_label'] = _load_label(key_file['train_label'])    
    dataset['test_img'] = _load_img(key_file['test_img'])
    dataset['test_label'] = _load_label(key_file['test_label'])
    
    return dataset

def init_mnist():
    download_mnist()
    dataset = _convert_numpy()
    print("Creating pickle file ...")
    with open(save_file, 'wb') as f:
        pickle.dump(dataset, f, -1)
    print("Done!")

def _change_one_hot_label(X):
    T = np.zeros((X.size, 10))
    for idx, row in enumerate(T):
        row[X[idx]] = 1
        
    return T
    

def load_mnist(normalize=False, flatten=True, one_hot_label=False):
    """讀入MNIST數(shù)據(jù)集
    
    Parameters
    ----------
    normalize : 將圖像的像素值正規(guī)化為0.0~1.0
    one_hot_label : 
        one_hot_label為True的情況下,標簽作為one-hot數(shù)組返回
        one-hot數(shù)組是指[0,0,1,0,0,0,0,0,0,0]這樣的數(shù)組
    flatten : 是否將圖像展開為一維數(shù)組
    
    Returns
    -------
    (訓(xùn)練圖像, 訓(xùn)練標簽), (測試圖像, 測試標簽)
    """
    if not os.path.exists(save_file):
        init_mnist()
        
    with open(save_file, 'rb') as f:
        dataset = pickle.load(f)
    
    if normalize:
        for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].astype(np.float32)
            dataset[key] /= 255.0
            
    if one_hot_label:
        dataset['train_label'] = _change_one_hot_label(dataset['train_label'])
        dataset['test_label'] = _change_one_hot_label(dataset['test_label'])
    
    if not flatten:
         for key in ('train_img', 'test_img'):
            dataset[key] = dataset[key].reshape(-1, 1, 28, 28)

    return (dataset['train_img'], dataset['train_label']), (dataset['test_img'], dataset['test_label']) 


if __name__ == '__main__':
    init_mnist()

確定激活函數(shù)、損失函數(shù)、計算梯度函數(shù)等

##激活函數(shù)
def sigmoid(x):
    return 1/(1+np.exp(-x))
def softmax(x):
    if x.ndim == 2:
        x = x.T
        x = x - np.max(x, axis=0)
        y = np.exp(x) / np.sum(np.exp(x), axis=0)
        return y.T 

    x = x - np.max(x) # 溢出對策
    return np.exp(x) / np.sum(np.exp(x))

def cross_entropy_error(y, t):
    if y.ndim == 1:
        t = t.reshape(1, t.size)
        y = y.reshape(1, y.size)
        
    # 監(jiān)督數(shù)據(jù)是one-hot-vector的情況下,轉(zhuǎn)換為正確解標簽的索引
    if t.size == y.size:
        t = t.argmax(axis=1)
             
    batch_size = y.shape[0]
    return -np.sum(np.log(y[np.arange(batch_size), t] + 1e-7)) / batch_size

# 計算梯度
def numerical_gradient(f, x):
    h = 1e-4 # 0.0001
    grad = np.zeros_like(x)
    
    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        idx = it.multi_index
        tmp_val = x[idx]
        x[idx] = float(tmp_val) + h
        fxh1 = f(x) # f(x+h)
        
        x[idx] = tmp_val - h 
        fxh2 = f(x) # f(x-h)
        grad[idx] = (fxh1 - fxh2) / (2*h)
        
        x[idx] = tmp_val # 還原值
        it.iternext()   
        
    return grad

def sigmoid_grad(x):
    return (1.0 - sigmoid(x)) * sigmoid(x)

神經(jīng)網(wǎng)絡(luò)的搭建

class TwoLayerNet:

    def __init__(self, input_size, hidden_size, output_size, weight_init_std=0.01):
        # 初始化權(quán)重
        self.params = {}
        self.params['W1'] = weight_init_std * np.random.randn(input_size, hidden_size)
        self.params['b1'] = np.zeros(hidden_size)
        self.params['W2'] = weight_init_std * np.random.randn(hidden_size, output_size)
        self.params['b2'] = np.zeros(output_size)

    def predict(self, x):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
    
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        
        return y
        
    # x:輸入數(shù)據(jù), t:監(jiān)督數(shù)據(jù)
    def loss(self, x, t):
        y = self.predict(x)
        
        return cross_entropy_error(y, t)
    
    def accuracy(self, x, t):
        y = self.predict(x)
        y = np.argmax(y, axis=1)
        t = np.argmax(t, axis=1)
        
        accuracy = np.sum(y == t) / float(x.shape[0])
        return accuracy
        
    # x:輸入數(shù)據(jù), t:監(jiān)督數(shù)據(jù)
    def numerical_gradient(self, x, t):
        loss_W = lambda W: self.loss(x, t)
        
        grads = {}
        grads['W1'] = numerical_gradient(loss_W, self.params['W1'])
        grads['b1'] = numerical_gradient(loss_W, self.params['b1'])
        grads['W2'] = numerical_gradient(loss_W, self.params['W2'])
        grads['b2'] = numerical_gradient(loss_W, self.params['b2'])
        
        return grads
        
    def gradient(self, x, t):
        W1, W2 = self.params['W1'], self.params['W2']
        b1, b2 = self.params['b1'], self.params['b2']
        grads = {}
        
        batch_num = x.shape[0]
        
        # forward
        a1 = np.dot(x, W1) + b1
        z1 = sigmoid(a1)
        a2 = np.dot(z1, W2) + b2
        y = softmax(a2)
        
        # backward
        dy = (y - t) / batch_num
        grads['W2'] = np.dot(z1.T, dy)
        grads['b2'] = np.sum(dy, axis=0)
        
        da1 = np.dot(dy, W2.T)
        dz1 = sigmoid_grad(a1) * da1
        grads['W1'] = np.dot(x.T, dz1)
        grads['b1'] = np.sum(dz1, axis=0)

        return grads

模型的訓(xùn)練與驗證?

# 讀入數(shù)據(jù)
(x_train, t_train), (x_test, t_test) = load_mnist(flatten=True,normalize=True, one_hot_label=True)

network = TwoLayerNet(input_size=784, hidden_size=50, output_size=10)

iters_num = 10000
train_size = x_train.shape[0]
batch_size = 100
learning_rate = 0.1

train_loss_list = []
train_acc_list = []
test_acc_list = []

iter_per_epoch = max(train_size / batch_size, 1)

for i in range(iters_num):
    batch_mask = np.random.choice(train_size, batch_size)
    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]
    
    # 梯度
    #grad = network.numerical_gradient(x_batch, t_batch)
    grad = network.gradient(x_batch, t_batch)
    
    # 更新
    for key in ('W1', 'b1', 'W2', 'b2'):
        network.params[key] -= learning_rate * grad[key]
    
    loss = network.loss(x_batch, t_batch)
    train_loss_list.append(loss)
    
    if i % iter_per_epoch == 0:
        train_acc = network.accuracy(x_train, t_train)
        test_acc = network.accuracy(x_test, t_test)
        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)
        print(train_acc, test_acc)

## 驗證
import matplotlib.pyplot as plt
plt.subplot(1,2,1)
plt.plot(np.arange(0,10000),train_loss_list)
plt.title('Loss')
plt.subplot(1,2,2)
plt.plot(np.arange(0,np.size(train_acc_list)),train_acc_list,np.arange(0,np.size(test_acc_list)),test_acc_list)
plt.title('accuracy')
plt.show()

?訓(xùn)練過程中的誤差和精確度變化:
?

手寫數(shù)字識別及python實現(xiàn)

測試模型的泛化能力

import cv2
def img_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

def predict_img_num(filename, img_width, img_height, threshold, kernel_size):
    img_original = cv2.imread(filename)
    img = cv2.resize(img_original,(img_width,img_width),fx=1,fy=1)

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, thresh2 = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY)

    kernel = np.ones(kernel_size,np.uint8) 
    thresh2 = cv2.erode(thresh2,kernel,iterations = 1)

    ret, thresh2 = cv2.threshold(thresh2, threshold, 255, cv2.THRESH_BINARY_INV)
    print(thresh2.shape)

    img_show('test',thresh2)
    thresh2 = thresh2.reshape(1,img_width*img_width)
    a = network.predict(thresh2)
    label = np.argmax(np.array(a))
    
    return label

predict_img_num('8.jpg',28,28,127,(3,3))

輸入手寫圖片8:

手寫數(shù)字識別及python實現(xiàn)

輸出結(jié)果:手寫數(shù)字識別及python實現(xiàn)

?同樣你也可以輸入一些你自己手寫的數(shù)字,來測試模型的泛化能力文章來源地址http://www.zghlxwxcb.cn/news/detail-471791.html

到了這里,關(guān)于手寫數(shù)字識別及python實現(xiàn)的文章就介紹完了。如果您還想了解更多內(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)文章

  • Python代碼識別minist手寫數(shù)字【附pdf】

    Python代碼識別minist手寫數(shù)字【附pdf】

    一、概述 對于人類而言,要識別圖片中的數(shù)字是一件很容易的事情,但是,如何讓機器學(xué)會理解圖片上的數(shù)字,這似乎并不容易。那么,能否找出一個函數(shù)(模型),通過輸入相關(guān)的信息,最終得到期望的結(jié)果呢? 二、python代碼實現(xiàn)中涉及的輸入輸出內(nèi)容: 輸入:mnist數(shù)據(jù)

    2024年04月14日
    瀏覽(20)
  • 深度學(xué)習實驗:Softmax實現(xiàn)手寫數(shù)字識別

    深度學(xué)習實驗:Softmax實現(xiàn)手寫數(shù)字識別

    文章相關(guān)知識點:???????AI遮天傳 DL-回歸與分類_老師我作業(yè)忘帶了的博客-CSDN博客 ? MNIST數(shù)據(jù)集 ? MNIST手寫數(shù)字數(shù)據(jù)集是機器學(xué)習領(lǐng)域中廣泛使用的圖像分類數(shù)據(jù)集。它包含60,000個訓(xùn)練樣本和10,000個測試樣本。這些數(shù)字已進行尺寸規(guī)格化,并在固定尺寸的圖像中居中

    2023年04月08日
    瀏覽(23)
  • Matlab搭建AlexNet實現(xiàn)手寫數(shù)字識別

    Matlab搭建AlexNet實現(xiàn)手寫數(shù)字識別

    個人博客地址 Matlab 2020a Windows10 使用Matlab對MNIST數(shù)據(jù)集進行預(yù)處理,搭建卷積神經(jīng)網(wǎng)絡(luò)進行訓(xùn)練,實現(xiàn)識別手寫數(shù)字的任務(wù)。在訓(xùn)練過程中,每隔30個batch輸出一次模型在驗證集上的準確率和損失值。在訓(xùn)練結(jié)束后會輸出驗證集中每個數(shù)字的真實值、網(wǎng)絡(luò)預(yù)測值和判定概率,并

    2024年02月05日
    瀏覽(19)
  • python與深度學(xué)習(一):ANN和手寫數(shù)字識別

    python與深度學(xué)習(一):ANN和手寫數(shù)字識別

    神經(jīng)網(wǎng)絡(luò)是學(xué)者通過對生物神經(jīng)元的研究,提出了模擬生物神經(jīng)元機制的人工神經(jīng)網(wǎng)絡(luò)的數(shù)學(xué)模型,生物神經(jīng)元的模型抽象為如圖所示的數(shù)學(xué)結(jié)構(gòu)。 神經(jīng)元輸入向量?? = [??1, ????2, ??3, … , ????]T,經(jīng)過函數(shù)映射:??: ?? → ??后得到輸出??。 考慮一種簡化的情況,

    2024年02月16日
    瀏覽(17)
  • FPGA實現(xiàn)mnist手寫數(shù)字識別(軟件部分)

    FPGA實現(xiàn)mnist手寫數(shù)字識別(軟件部分)

    使用的環(huán)境:tf1.12,具體配置見here: 首先打開環(huán)境tf1.12,,再安裝以下的包: opencv 在這里下載“l(fā)inux-64/opencv3-3.1.0-py36_0.tar.bz2”,通過共享文件夾copy到download文件夾中,在文件夾下打開終端,輸入以下命令進行安裝: matplotlib(時刻注意是py36) Pillow(貌似不用了,上面已經(jīng)安

    2023年04月15日
    瀏覽(28)
  • python與深度學(xué)習(六):CNN和手寫數(shù)字識別二

    python與深度學(xué)習(六):CNN和手寫數(shù)字識別二

    本篇文章是對上篇文章訓(xùn)練的模型進行測試。首先是將訓(xùn)練好的模型進行重新加載,然后采用opencv對圖片進行加載,最后將加載好的圖片輸送給模型并且顯示結(jié)果。 在這里導(dǎo)入需要的第三方庫如cv2,如果沒有,則需要自行下載。 把MNIST數(shù)據(jù)集進行加載,并且把訓(xùn)練好的模型也

    2024年02月15日
    瀏覽(25)
  • 用PyTorch實現(xiàn)MNIST手寫數(shù)字識別(最新,非常詳細)

    用PyTorch實現(xiàn)MNIST手寫數(shù)字識別(最新,非常詳細)

    本文基于 PyTorch 框架,采用 CNN卷積神經(jīng)網(wǎng)絡(luò) 實現(xiàn) MNIST 手寫數(shù)字識別,僅在 CPU 上運行。 已分別實現(xiàn)使用Linear純線性層、CNN卷積神經(jīng)網(wǎng)絡(luò)、Inception網(wǎng)絡(luò)、和Residual殘差網(wǎng)絡(luò)四種結(jié)構(gòu)對MNIST數(shù)據(jù)集進行手寫數(shù)字識別,并對其識別準確率進行比較分析。(另外三種還未發(fā)布) 看完

    2024年02月06日
    瀏覽(24)
  • CNN卷積神經(jīng)網(wǎng)絡(luò)實現(xiàn)手寫數(shù)字識別(基于tensorflow)

    CNN卷積神經(jīng)網(wǎng)絡(luò)實現(xiàn)手寫數(shù)字識別(基于tensorflow)

    卷積網(wǎng)絡(luò)的 核心思想 是將: 局部感受野 權(quán)值共享(或者權(quán)值復(fù)制) 時間或空間亞采樣 卷積神經(jīng)網(wǎng)絡(luò) (Convolutional Neural Networks,簡稱: CNN )是深度學(xué)習當中一個非常重要的神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)。它主要用于用在 圖像圖片處理 , 視頻處理 , 音頻處理 以及 自然語言處理 等等。

    2024年02月11日
    瀏覽(23)
  • 基于python的Keras庫構(gòu)建的深度神經(jīng)網(wǎng)絡(luò)手寫數(shù)字識別模型

    基于python的Keras庫構(gòu)建的深度神經(jīng)網(wǎng)絡(luò)手寫數(shù)字識別模型

    目錄 模型訓(xùn)練過程 ①導(dǎo)入所需的庫 ②加載手寫體數(shù)據(jù)集,將數(shù)據(jù)集分為訓(xùn)練集和測試集 ③數(shù)據(jù)預(yù)處理 ④構(gòu)建模型 ⑤編譯模型 ⑥訓(xùn)練模型 ⑦使用測試集進行驗證 ⑧輸出模型準確率和時間消耗 完整代碼如下: 模型訓(xùn)練過程 使用到的數(shù)據(jù)集為IMDB電影評論情感分類數(shù)據(jù)集,該

    2024年02月09日
    瀏覽(30)
  • 深度學(xué)習:使用卷積神經(jīng)網(wǎng)絡(luò)CNN實現(xiàn)MNIST手寫數(shù)字識別

    深度學(xué)習:使用卷積神經(jīng)網(wǎng)絡(luò)CNN實現(xiàn)MNIST手寫數(shù)字識別

    本項目基于pytorch構(gòu)建了一個深度學(xué)習神經(jīng)網(wǎng)絡(luò),網(wǎng)絡(luò)包含卷積層、池化層、全連接層,通過此網(wǎng)絡(luò)實現(xiàn)對MINST數(shù)據(jù)集手寫數(shù)字的識別,通過本項目代碼,從原理上理解手寫數(shù)字識別的全過程,包括反向傳播,梯度下降等。 卷積神經(jīng)網(wǎng)絡(luò)是一種多層、前饋型神經(jīng)網(wǎng)絡(luò)。從功能上

    2024年02月13日
    瀏覽(20)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

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

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包