MLP神經網絡實例--手寫識別


1.導入MNIST數據集

直接使用fetch_mldata會報錯,錯誤信息是python3.7把fetch_mldata方法移除了,所以需要單獨下載數據集
從這個網站上下載數據集:

https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat

使用如下方法獲取路徑:

from sklearn.datasets.base import get_data_home 
print (get_data_home()) # 如我的電腦上的目錄為: C:\Users\Mr.Wmn\scikit_learn_data\mldata
#下載好mnist-original.mat數據集放到獲取的路徑里,在輸入如下內容便不會報錯了
#導入數據集拆分工具
from sklearn.model_selection import train_test_split
#導入數據集獲取工具
from sklearn.datasets import fetch_mldata
#導入MLP神經網絡
from sklearn.neural_network import MLPClassifier
#導入numpy
import numpy as np
#加載MNIST手寫數字數據集
mnist = fetch_mldata('MNIST original')
mnist
{'DESCR': 'mldata.org dataset: mnist-original',
 'COL_NAMES': ['label', 'data'],
 'target': array([0., 0., 0., ..., 9., 9., 9.]),
 'data': array([[0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        ...,
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0]], dtype=uint8)}

 

print('\n\n\n')
print('代碼運行結果')
print('====================================\n')
#打印樣本數量和樣本特征數
print('樣本數量:{} 樣本特征數:{}'.format(mnist.data.shape[0],mnist.data.shape[1]))
print('\n====================================')
print('\n\n\n')
代碼運行結果
====================================

樣本數量:70000 樣本特征數:784

====================================
#建立訓練數據集和測試數據集
X = mnist.data/255
y = mnist.target
X_train,X_test,y_train,y_test = train_test_split(X,y,train_size=1000,random_state=62)
print(X_train,X_test,y_train,y_test)
[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]] [[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 7. 3. 1. 9. 9. 9. 3. 8. 2. 9. 7. 1. 7. 1. 1. 4. 3. 1. 1. 3.
 0. 1. 3. 3. 4. 5. 8. 1. 2. 0. 4. 6. 7. 1. 2. 1.] [8. 2. 5. ... 3. 6. 9.]

 2.訓練MLP神經網絡

#設置神經網絡有兩個100個節點的隱藏層
mlp_hw = MLPClassifier(solver='lbfgs',hidden_layer_sizes=[100,100],activation='relu',alpha = 1e-5,random_state=62)
#使用數據訓練神經網絡模型
mlp_hw.fit(X_train,y_train)
print('\n\n\n')
print('代碼運行結果')
print('====================================\n')
#打印模型分數
print('測試數據集得分:{:.2f}% '.format(mlp_hw.score(X_test,y_test)*100))
print('\n====================================')
print('\n\n\n')
代碼運行結果
====================================

測試數據集得分:85.79% 

====================================

 3.使用模型進行數字識別

 

#導入圖像處理工具
from PIL import Image
#打開圖像
image = Image.open("4.png").convert('F')
#調整圖像的大小
image = image.resize((28,28))
arr = []
#將圖像中的像素作為預測數據點的特征
for i in range(28):
    for j in range(28):
        pixel = 1.0 - float(image.getpixel((j,i)))/255.
        arr.append(pixel)
#由於只有一個樣本,所以需要進行reshape操作
arr1 = np.array(arr).reshape(1,-1)
#進行圖像識別
print('圖片中的數字是:{:.0f}'.format(mlp_hw.predict(arr1)[0]))
圖片中的數字是:5

 

 總結 : 

  scikit-learn中的MLP分類和回歸在易用性表現不錯,但是僅限於處理小數據集,對於更龐大或更復雜的數據集就不怎么友好了.

  在計算能力充足並且參數設置合適的情況下,神經網絡可以比其他的機器學習算法表現更加優異

  其缺點也很明顯,如模型訓練時間相對更長,對數據預處理的要求較高.

 

文章引自 : 《深入淺出python機器學習》


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM