机器学习 —— 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