宝塔服务器面板,一键全能部署及管理,送你10850元礼包,点我领取

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:UsersMr.Wmnscikit_learn_datamldata
#下载好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'


')
print'代码运行结果')
print'====================================
')
#打印样本数量和样本特征数
print'样本数量:{} 样本特征数:{}'.formatmnist.data.shape[0],mnist.data.shape[1]))
print'
====================================')
print'


')
代码运行结果
====================================

样本数量:70000 样本特征数:784

====================================
#建立训练数据集和测试数据集
X = mnist.data/255
y = mnist.target
X_train,X_test,y_train,y_test = train_test_splitX,y,train_size=1000,random_state=62)
printX_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.]] [[0. 0. 0. ... 0. 0. 0.]
 [0. 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. 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 = MLPClassifiersolver='lbfgs',hidden_layer_sizes=[100,100],activation='relu',alpha = 1e-5,random_state=62)
#使用数据训练神经网络模型
mlp_hw.fitX_train,y_train)
print'


')
print'代码运行结果')
print'====================================
')
#打印模型分数
print'测试数据集得分:{:.2f}% '.formatmlp_hw.scoreX_test,y_test)*100))
print'
====================================')
print'


')
代码运行结果
====================================

测试数据集得分:85.79% 

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

 3.使用模型进行数字识别

 MLP神经网络实例–手写识别-风君子博客

#导入图像处理工具
from PIL import Image
#打开图像
image = Image.open"4.png").convert'F')
#调整图像的大小
image = image.resize28,28))
arr = []
#将图像中的像素作为预测数据点的特征
for i in range28):
    for j in range28):
        pixel = 1.0 - floatimage.getpixelj,i)))/255.
        arr.appendpixel)
#由于只有一个样本,所以需要进行reshape操作
arr1 = np.arrayarr).reshape1,-1)
#进行图像识别
print'图片中的数字是:{:.0f}'.formatmlp_hw.predictarr1)[0]))
图片中的数字是:5

 总结 : 

  scikit-learn中的MLP分类和回归在易用性表现不错,但是仅限于处理小数据集,对于更庞大或更复杂的数据集就不怎么友好了.

  在计算能力充足并且参数设置合适的情况下,神经网络可以比其他的机器学习算法表现更加优异

  其缺点也很明显,如模型训练时间相对更长,对数据预处理的要求较高.

文章引自 : 《深入浅出python机器学习》