机器学习 —— sklearn实现神经网络并用于手写数字识别

该博客介绍了如何利用Python的sklearn库实现一个多层感知器(MLP)神经网络,用于手写数字识别。首先,加载MNIST数据集,然后进行数据预处理,包括标准化和二值化。接着,通过train_test_split进行数据划分,并使用tanh激活函数、L2正则化和批量大小为100的MLP模型进行训练。最后,展示训练和测试集上的分类报告,显示出高精度的识别效果。
摘要由CSDN通过智能技术生成

机器学习 —— sklearn实现神经网络并用于手写数字识别

from sklearn.neural_network import MLPClassifier
"""
Multilayer Perception 多层感知器
"""
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_digits
from sklearn.metrics import classification_report
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
import matplotlib.pylab as pl

# 加载数据
data = load_digits()
image = data.images
X = data.data
Y = data.target

pl.gray() # 图片灰度化
pl.matshow(image[1])

# 数据预处理
STD = StandardScaler()
X = STD.fit_transform(X)

BIN = LabelBinarizer()
Y = BIN.fit_transform(Y)

x_train,x_test,y_train,y_test = train_test_split(X,Y)

# 模型训练
MLP_model = MLPClassifier(hidden_layer_sizes=(100,50),activation="tanh",alpha = 0.01,batch_size=100,max_iter=int(1e4))
MLP_model.fit(x_train,y_train)

# 模型评估
y_train_pre = MLP_model.predict(x_train)
y_test_pre = MLP_model.predict(x_test)

print("train:",classification_report(y_train,y_train_pre))
print("test",classification_report(y_test,y_test_pre))

train: precision recall f1-score support

      0       1.00      1.00      1.00       136
      1       1.00      1.00      1.00       127
      2       1.00      1.00      1.00       132
      3       1.00      1.00      1.00       141
      4       1.00      1.00      1.00       129
      5       1.00      1.00      1.00       141
      6       1.00      1.00      1.00       136
      7       1.00      1.00      1.00       138
      8       1.00      1.00      1.00       135
      9       1.00      1.00      1.00       132

avg / total 1.00 1.00 1.00 1347

test precision recall f1-score support

      0       0.98      0.98      0.98        42
      1       0.95      0.98      0.96        55
      2       0.96      1.00      0.98        45
      3       0.98      0.98      0.98        42
      4       0.98      1.00      0.99        52
      5       0.91      0.98      0.94        41
      6       0.98      0.98      0.98        45
      7       0.97      0.93      0.95        41
      8       0.97      0.85      0.90        39
      9       0.94      0.92      0.93        48

avg / total 0.96 0.96 0.96 450

在这里插入图片描述

by CyrusMay 2022 04 17

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值