欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MLP mnist 手写数字识别

程序员文章站 2024-01-22 11:19:46
...
#载入数据
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test)=mnist.load_data()
#X_train是图像数据,y_train是标签
#数据量有点大 载入需要时间
print(type(X_train),X_train.shape)
#可视化数据
img1 = X_train[0]
%matplotlib inline
from matplotlib import pyplot as plt
fig1 = plt.figure(figsize=(3,3))
plt.imshow(img1)
plt.title(y_train[0])
plt.show()

MLP mnist 手写数字识别

print(img1.shape) #28*28 = 784

feature_size = img1.shape[0] * img1.shape[1]
#维度转换
X_train_format = X_train.reshape(X_train.shape[0],feature_size)
X_test_format = X_test.reshape(X_test.shape[0],feature_size)

print(feature_size,X_train_format.shape)

784 (60000, 784)

#归一化 0-255的图像数据/255 =0-1
X_test_nromal = X_test_format/255
X_train_normal =  X_train_format/255
print(X_train_normal[0])

#format the output data (lables)
from keras.utils import to_categorical
y_train_format = to_categorical(y_train)
y_test_format = to_categorical(y_test)
print(y_train_format[0])

建立模型

from keras.models import Sequential
from keras.layers import Dense,Activation

mlp = Sequential()
mlp.add(Dense(units=392,activation="sigmoid",input_dim=feature_size))
mlp.add(Dense(units=392,activation="sigmoid"))
mlp.add(Dense(units=10,activation="softmax"))
mlp.summary()

MLP mnist 手写数字识别

#配置模型
mlp.compile(loss='categorical_crossentropy',optimizer='adam')
#多分类的

mlp.fit(X_train_normal,y_train_format,epochs=10) #训练

MLP mnist 手写数字识别

#测试训练数据集效果
y_train_predict = mlp.predict_classes(X_train_normal)
print(y_train_predict)

from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_train,y_train_predict)
print(accuracy)

#测试集预测效果
y_test_predict = mlp.predict_classes(X_test_nromal)
accuracy_test = accuracy_score(y_test,y_test_predict)
print(accuracy_test)

MLP mnist 手写数字识别

#测试集数据可视化
img2 = X_test[100]
fig2 = plt.figure(figsize=(3,3))
plt.imshow(img2)
plt.title(y_test_predict[100])
plt.show()

MLP mnist 手写数字识别

  1. 实现了基于图像数据的数字自动识别分类
  • 完成了图像的数字化处理与可视化
  • 完成了数据预处理与格式转换
  • 建立mlp模型