MLP mnist 手写数字识别

#载入数据
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()

在这里插入图片描述

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.compile(loss='categorical_crossentropy',optimizer='adam')
#多分类的

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

在这里插入图片描述

#测试训练数据集效果
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)

在这里插入图片描述

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

在这里插入图片描述

  1. 实现了基于图像数据的数字自动识别分类
  • 完成了图像的数字化处理与可视化
  • 完成了数据预处理与格式转换
  • 建立mlp模型
  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickdlk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值