keras—多层感知器MLP—MNIST手写数字识别
一、手写数字识别
现在就来说说如何使用神经网络实现手写数字识别。 在这里我使用mind manager工具绘制了要实现手写数字识别需要的模块以及模块的功能:
其中隐含层节点数量(即神经细胞数量)计算的公式(这只是经验公式,不一定是最佳值):
- m: 隐含层节点数
- n: 输入层节点数
- l:输出层节点数
- a:1-10之间的常数
本例子当中:
- 输入层节点n:784
- 输出层节点:10 (表示数字 0 ~ 9)
隐含层选30个,训练速度虽然快,但是准确率却只有91% 左右,如果将这个数字变为100 或是300,其训练速度回慢一些
,但准确率可以提高到93%~94% 左右。
因为这是使用的MNIST的手写数字训练数据,所以它的图像的分辨率是28 * 28,也就是有784个像素点,其下载地址为:http://yann.lecun.com/exdb/mnist/
二、查看数据程序
- 48000作为训练数据,12000作为验证数据,10000作为预测数据
#coding=utf-
import numpy as np #导入模块,numpy是扩展链接库
import pandas as pd #类似一个本地的excel,偏向现在的非结构化的数据库
import tensorflow as tf
import keras
from keras.utils import np_utils
np.random.seed() #设置seed可以产生的随机数据
from keras.datasets import mnist #导入模块,下载读取mnist数据
(x_train_image,y_train_label),\
(x_test_image,y_test_label)=mnist.load_data() #下载读取mnist数据
print('train data=',len(x_train_image))
print('test data=',len(x_test_image))
print('x_train_image:',x_train_image.shape)
print('y_train_label:',y_train_label.shape) #查看数据
import matplotlib.pyplot as plt
def plot_image(image): #定义显示函数
fig=plt.gcf()
fig.set_size_inches(,) #设置显示图形的大小
plt.imshow(image,cmap='binary') #黑白灰度显示
plt.show() #开始画图
y_train_label[] #查看第0项label数据
import matplotlib.pyplot as plt
def plot_image_labels_prediction(image,lables,prediction,idx,num=):#显示多项数据
fig=plt.gcf()
fig.set_size_inches(,) #设置显示图形的大小
if num>:num=
for i in range(,num): #画出num个数字图形
ax=plt.subplot(,,i+) #建立subplot字图形为5行5列
ax.imshow(image[idx],cmap='binary') #画出subgraph
title="lable="+str(lables[idx]) #设置字图形title,显示标签字段
if len(prediction)>: #如果传入了预测结果
title+=",predict="+str(prediction[idx]) #标题
ax.set_title(title,fontsize=) #设置字图形的标题
ax.set_xticks([]);ax.set_yticks([]) #设置不显示刻度
idx+= #读取下一项
plt.show()
plot_image_labels_prediction(x_train_image,y_train_label,[],,)#查看训练数据前10项
plot_image_labels_prediction(x_test_image,y_test_label,[],,) #查看测试数据前10项三、运行结果

四、训练预测识别程序
#coding=utf-8
#1.数据预处理
import numpy as np #导入模块,numpy是扩展链接库
import pandas as pd
import tensorflow
import keras
from keras.utils import np_utils
np.random.seed(10) #设置seed可以产生的随机数据
from keras.datasets import mnist #导入模块,下载读取mnist数据
(x_train_image,y_train_label),\
(x_test_image,y_test_label)=mnist.load_data() #下载读取mnist数据
print('train data=',len(x_train_image))
print('test data=',len(x_test_image))
print('x_train_image:',x_train_image.shape)
print('y_train_label:',y_train_label.shape)
import matplotlib.pyplot as plt
def plot_image(image):
fig=plt.gcf()
fig.set_size_inches(2,2)
plt.imshow(image,cmap='binary')
plt.show()
y_train_label[0]
import matplotlib.pyplot as plt
def plot_image_labels_prediction(image,lables,prediction,idx,num=10):
fig=plt.gcf()
fig.set_size_inches(12,14)
if num>25:num=25
for i in range(0,num):
ax=plt.subplot(5,5,i+1)
ax.imshow(image[idx],cmap='binary')
title="lable="+str(lables[idx])
if len(prediction)>0:
title+=",predict="+str(prediction[idx])
ax.set_title(title,fontsize=10)
ax.set_xticks([]);ax.set_yticks([])
idx+=1
plt.show()
plot_image_labels_prediction(x_train_image,y_train_label,[],0,10)
plot_image_labels_prediction(x_test_image,y_test_label,[],0,10)
x_Train=x_train_image.reshape(60000,784).astype('float32') #以reshape转化成784个float
x_Test=x_test_image.reshape(10000,784).astype('float32')
x_Train_normalize=x_Train/255 #将features标准化
x_Test_normalize=x_Test/255
y_Train_OneHot=np_utils.to_categorical(y_train_label)#将训练数据和测试数据的label进行one-hot encoding转化
y_Test_OneHot=np_utils.to_categorical(y_test_label)
#2.建立模型
from keras.models import Sequential #可以通过Sequential模型传递一个layer的list来构造该模型,序惯模型是多个网络层的线性堆叠
from keras.layers import Dense #全连接层
model=Sequential()
#建立输入层、隐藏层
model.add(Dense(units=256,
input_dim=784,
kernel_initializer='normal',
activation='relu'))
#建立输出层
model.add(Dense(units=10,
kernel_initializer='normal',
activation='softmax'))
print(model.summary())
#3、进行训练
#对训练模型进行设置,损失函数、优化器、权值
model.compile(loss='categorical_crossentropy',
optimizer='adam',metrics=['accuracy'])
# 设置训练与验证数据比例,80%训练,20%测试,执行10个训练周期,每一个周期200个数据,显示训练过程2次
train_history=model.fit(x=x_Train_normalize,
y=y_Train_OneHot,validation_split=0.2,
epochs=10,batch_size=200,verbose=2)
#显示训练过程
import matplotlib.pyplot as plt
def show_train_history(train_history,train,validation):
plt.plot(train_history.history[train])
plt.plot(train_history.history[validation])
plt.title('Train History')
plt.ylabel(train)
plt.xlabel('Epoch')
plt.legend(['train','validation'],loc='upper left') #显示左上角标签
plt.show()
show_train_history(train_history,'acc','val_acc') #画出准确率评估结果
show_train_history(train_history,'loss','val_loss') #画出误差执行结果
#以测试数据评估模型准确率
scores=model.evaluate(x_Test_normalize,y_Test_OneHot) #创建变量存储评估后的准确率数据,(特征值,真实值)
print()
print('accuracy',scores[1])
#进行预测
prediction=model.predict_classes(x_Test)
prediction
plot_image_labels_prediction(x_test_image,y_test_label,prediction,idx=340)五、运行结果


- 评估模型准确率结果为:0.9754

- 预测结果:有一个潦草的5预测错误为3

keras—多层感知器MLP—MNIST手写数字识别的更多相关文章
- mnist手写数字识别——深度学习入门项目(tensorflow+keras+Sequential模型)
前言 今天记录一下深度学习的另外一个入门项目——<mnist数据集手写数字识别>,这是一个入门必备的学习案例,主要使用了tensorflow下的keras网络结构的Sequential模型 ...
- 基于tensorflow的MNIST手写数字识别(二)--入门篇
http://www.jianshu.com/p/4195577585e6 基于tensorflow的MNIST手写字识别(一)--白话卷积神经网络模型 基于tensorflow的MNIST手写数字识 ...
- Tensorflow实现MNIST手写数字识别
之前我们讲了神经网络的起源.单层神经网络.多层神经网络的搭建过程.搭建时要注意到的具体问题.以及解决这些问题的具体方法.本文将通过一个经典的案例:MNIST手写数字识别,以代码的形式来为大家梳理一遍神 ...
- 持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型
持久化的基于L2正则化和平均滑动模型的MNIST手写数字识别模型 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考文献Tensorflow实战Google深度学习框架 实验平台: Tens ...
- TensorFlow——MNIST手写数字识别
MNIST手写数字识别 MNIST数据集介绍和下载:http://yann.lecun.com/exdb/mnist/ 一.数据集介绍: MNIST是一个入门级的计算机视觉数据集 下载下来的数据集 ...
- Android+TensorFlow+CNN+MNIST 手写数字识别实现
Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...
- 深度学习之 mnist 手写数字识别
深度学习之 mnist 手写数字识别 开始学习深度学习,先来一个手写数字的程序 import numpy as np import os import codecs import torch from ...
- 第三节,CNN案例-mnist手写数字识别
卷积:神经网络不再是对每个像素做处理,而是对一小块区域的处理,这种做法加强了图像信息的连续性,使得神经网络看到的是一个图像,而非一个点,同时也加深了神经网络对图像的理解,卷积神经网络有一个批量过滤器, ...
- mnist 手写数字识别
mnist 手写数字识别三大步骤 1.定义分类模型2.训练模型3.评价模型 import tensorflow as tfimport input_datamnist = input_data.rea ...
随机推荐
- 实验三:C分支结构程序设计
3.1 #include<stdio.h> int main(){ char a; scanf("%c",&a); if(a>=65&&a ...
- numpy里的randn
这个函数的作用就是从标准正态分布中返回一个或多个样本值.什么是标准正态分布 来源:http://www.360doc.com/content/17/0306/13/32342759_634411464 ...
- javascript面向对象的程序设计之Object.getOwnPropertyDescriptor()
Object.getOwnPropertyDescriptor()用于获取给定属性的描述信息,这个描述信息是一个对象. 如果是访问器属性,则这个对象的属性有configurable,enumerabl ...
- mysql更新(五) 完整性约束 外键的变种 三种关系 数据的增删改
11-数据的增删改 本节重点: 插入数据 INSERT 更新数据 UPDATE 删除数据 DELETE 再来回顾一下之前我们练过的一些操作,相信大家都对插入数据.更新数据.删除数据有了全面的认识. ...
- Win10 C盘根目录权限
cmd管理员运行 icacls c:\ /setintegritylevel M c盘属性,安全,完全控制.
- FDConnection
FDConnection 利用FDConnection获取信息,不用放query控件也可以. FDConnection1.GetTableNames('', '', '', List); FD ...
- Simple2D-20(重构)
为什么重构 Simple2D 开始的时候打算使用几周的时间来实现 Simple2D 的,主要是实现一些简单的 2D 渲染功能.但是编写的过程中不满于它只能实现简单的功能,后来添加了诸如Alpha测试. ...
- mysql大表优化
https://segmentfault.com/a/1190000006158186 https://tech.meituan.com/mysql-index.html http://www.cnb ...
- MySQLReport
简介: MySQLReport 一.安装 shell > yum -y install mysqlreport perl-DBD-MySQL 二.使用 shell > mysqlrepor ...
- Overcoming Life's Obstacles - ASC 2017 March 03-04
<Overcoming Life's Obstacles - How a top oboist overcame a neurological disorder to play again> ...