keras—多层感知器识别手写数字算法程序
#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 #全连接层
from keras.layers import Dropout #避免过度拟合
model=Sequential()
#建立输入层、隐藏层
model.add(Dense(units=1000,
input_dim=784,
kernel_initializer='normal',
activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=1000,
kernel_initializer='normal',
activation='relu'))
model.add(Dropout(0.5))
#建立输出层
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)
#4、建立模型提高预测准确率
#建立混淆矩阵
import pandas as pd #pandas 是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的
pd.crosstab(y_test_label,prediction,
rownames=['label'],colnames=['predict'])
#建立真实值与预测值dataFrame
df=pd.DataFrame({'label':y_test_label,'predict':prediction})
df[:2]
df[(df.label==5)&(df.predict==3)]
plot_image_labels_prediction(x_test_image,y_test_label,prediction,idx=340,num=1)
keras—多层感知器识别手写数字算法程序的更多相关文章
- 【TensorFlow-windows】(三) 多层感知器进行手写数字识别(mnist)
主要内容: 1.基于多层感知器的mnist手写数字识别(代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...
- TensorFlow—多层感知器—MNIST手写数字识别
1 import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data import ...
- keras—多层感知器MLP—MNIST手写数字识别
一.手写数字识别 现在就来说说如何使用神经网络实现手写数字识别. 在这里我使用mind manager工具绘制了要实现手写数字识别需要的模块以及模块的功能: 其中隐含层节点数量(即神经细胞数量)计算 ...
- 4.2tensorflow多层感知器MLP识别手写数字最易懂实例代码
自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1 多层感知器MLP(m ...
- keras框架的MLP手写数字识别MNIST,梳理?
keras框架的MLP手写数字识别MNIST 代码: # coding: utf-8 # In[1]: import numpy as np import pandas as pd from kera ...
- Keras mlp 手写数字识别示例
#基于mnist数据集的手写数字识别 #构造了三层全连接层组成的多层感知机,最后一层为输出层 #基于Keras 2.1.1 Tensorflow 1.4.0 代码: import keras from ...
- 手写数字识别——利用keras高层API快速搭建并优化网络模型
在<手写数字识别——手动搭建全连接层>一文中,我们通过机器学习的基本公式构建出了一个网络模型,其实现过程毫无疑问是过于复杂了——不得不考虑诸如数据类型匹配.梯度计算.准确度的统计等问题,但 ...
- 学习笔记CB009:人工神经网络模型、手写数字识别、多层卷积网络、词向量、word2vec
人工神经网络,借鉴生物神经网络工作原理数学模型. 由n个输入特征得出与输入特征几乎相同的n个结果,训练隐藏层得到意想不到信息.信息检索领域,模型训练合理排序模型,输入特征,文档质量.文档点击历史.文档 ...
- 【问题解决方案】Keras手写数字识别-ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接
参考:台大李宏毅老师视频课程-Keras-Demo 在载入数据阶段报错: ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接 Google之 ...
随机推荐
- springMVC学习(10)-上传图片
需求:在修改商品页面,添加上传商品图片功能. SpringMVC中对多部件类型解析: 1)springmvc中配置: <!-- 文件上传 --> <bean id="mul ...
- Spring IOC - 控制反转(依赖注入) - 单例和多例
Spring容器管理的bean在默认情况下是单例的,即一个bean只会创建一个对象,存在map中,之后无论获取多少次该bean,都返回同一个对象. Spring默认采用单例方式,减少了对象的创建,从而 ...
- dubbo框架及dubbo环境搭建
https://blog.csdn.net/liuhaiabc/article/details/52781351 dubbo框架及dubbo环境搭建
- 9-16Jenkins-3可用的环境变量、参数化构建和依赖
1.环境变量 可以查看可用的环境量 执行构建 2.参数化构建 3.依赖 多个工程可以在按既定顺序执行 test1225-2的构建触发器设置
- 1061 Dating (20 分)
1061 Dating (20 分) Sherlock Holmes received a note with some strange strings: Let's date! 3485djDkxh ...
- 2天时间终于把ntopng装好了
1.环境centos6.7x642.安装步骤,首先把centos按优化步骤完成3.更改centos的yum源,更改为阿里云的源.4.[root@netmon ntopng]# cat /etc/yum ...
- centos 7.5 安装mongodb
MongoDB安装和启动 从官网下载最新对应的版本然后解压,本文以3.6.9为例,将文件拷贝到opt目录下,然后解压: [root@localhost opt]# tar zxvf mongodb-l ...
- EL中拼接字符串的方法
近期在项目中碰到一个需要在JSP页面中比较两String类型的值的问题,于是想当然的写了如下代码: <c:if test="${'p'+longValue=='p1'}"&g ...
- Lunce编程模型
问题的场景: 解决方案:都是来自于科技论文 ============================================================================== ...
- Linux---CentOS 定时运行脚本配置练手
1.安装crontab yum install vixie-cron yum install crontabs vixie-cron软件包是cron的主程序: crontabs软件包是用来安装.卸装. ...