# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(1337) #for reproducibility再现性
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential#按层
from keras.layers import Dense, Activation,Convolution2D, MaxPooling2D, Flatten
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop
from keras.optimizers import Adam

从mnist下载手写数字图片数据集,图片为28*28,将每个像素的颜色(0到255)改为(0倒1),将标签y变为10个长度,若为1,则在1处为1,剩下的都标为0。

#dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
#x shape (60000 28*28),y shape(10000,)
(x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集#data pre-processing
x_train = x_train.reshape(-1,1,28,28)#-1代表个数不限,1为高度,黑白照片高度为1
x_test = x_test.reshape(-1,1,28,28)
y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
y_test = np_utils.to_categorical(y_test,num_classes=10)

接下来搭建CNN

卷积->池化->卷积->池化

使图片从(1,28,28)->(32,28,28)->(32,14,14)-> (64,14,14) -> (64,7,7)

#Another way to build CNN
model = Sequential()#Conv layer 1 output shape (32,28,28)
model.add(Convolution2D(nb_filter =32,#滤波器装了32个,每个滤波器都会扫过这个图片,会得到另外一整张图片,所以之后得到的告诉是32层nb_row=5,nb_col=5,border_mode='same', #padding methodinput_shape=(1,      #channels  通道数28,28),  #height & width 长和宽
        ))
model.add(Activation('relu'))#Pooling layer 1 (max pooling) output shape (32,14,14)
model.add(MaxPooling2D(pool_size=(2,2), #2*2strides=(2,2),  #长和宽都跳两个再pool一次border_mode='same', #paddingmethod
        ))#Conv layers 2 output shape (64,14,14)
model.add(Convolution2D(64,5,5,border_mode='same'))
model.add(Activation('relu'))#Pooling layers 2 (max pooling) output shape (64,7,7)
model.add(MaxPooling2D(pool_size=(2,2), border_mode='same'))

构建全连接神经网络

#Fully connected layer 1 input shape (64*7*7) = (3136)
#Flatten 把三维抹成一维,全连接
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))#Fully connected layer 2 to shape (10) for 10 classes
model.add(Dense(10)) #输出10个单位
model.add(Activation('softmax')) #softmax用来分类#Another way to define optimizer
adam = Adam(lr=1e-4)# We add metrics to get more results you want to see
model.compile( #编译optimizer = adam,loss = 'categorical_crossentropy',metrics=['accuracy'], #在更新时同时计算一下accuracy)

训练和测试

print("Training~~~~~~~~")
#Another way to train the model
model.fit(x_train,y_train, epochs=1, batch_size=32) #训练2大批,每批32个print("\nTesting~~~~~~~~~~")
#Evalute the model with the  metrics we define earlier
loss,accuracy = model.evaluate(x_test,y_test)print('\ntest loss:',loss)
print('\ntest accuracy:', accuracy)

全代码:

# -*- coding: utf-8 -*-
import numpy as np
np.random.seed(1337) #for reproducibility再现性
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential#按层
from keras.layers import Dense, Activation,Convolution2D, MaxPooling2D, Flatten
import matplotlib.pyplot as plt
from keras.optimizers import RMSprop
from keras.optimizers import Adam#dowmload the mnisst the path '~/.keras/datasets/' if it is the first time to be called
#x shape (60000 28*28),y shape(10000,)
(x_train,y_train),(x_test,y_test) = mnist.load_data()#0-9的图片数据集#data pre-processing
x_train = x_train.reshape(-1,1,28,28)#-1代表个数不限,1为高度,黑白照片高度为1
x_test = x_test.reshape(-1,1,28,28)
y_train = np_utils.to_categorical(y_train, num_classes=10) #把标签变为10个长度,若为1,则在1处为1,剩下的都标为0
y_test = np_utils.to_categorical(y_test,num_classes=10)#Another way to build CNN
model = Sequential()#Conv layer 1 output shape (32,28,28)
model.add(Convolution2D(nb_filter =32,#滤波器装了32个,每个滤波器都会扫过这个图片,会得到另外一整张图片,所以之后得到的告诉是32层nb_row=5,nb_col=5,border_mode='same', #padding methodinput_shape=(1,      #channels  通道数28,28),  #height & width 长和宽
        ))
model.add(Activation('relu'))#Pooling layer 1 (max pooling) output shape (32,14,14)
model.add(MaxPooling2D(pool_size=(2,2), #2*2strides=(2,2),  #长和宽都跳两个再pool一次border_mode='same', #paddingmethod
        ))#Conv layers 2 output shape (64,14,14)
model.add(Convolution2D(64,5,5,border_mode='same'))
model.add(Activation('relu'))#Pooling layers 2 (max pooling) output shape (64,7,7)
model.add(MaxPooling2D(pool_size=(2,2), border_mode='same'))#Fully connected layer 1 input shape (64*7*7) = (3136)
#Flatten 把三维抹成一维,全连接
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))#Fully connected layer 2 to shape (10) for 10 classes
model.add(Dense(10)) #输出10个单位
model.add(Activation('softmax')) #softmax用来分类#Another way to define optimizer
adam = Adam(lr=1e-4)# We add metrics to get more results you want to see
model.compile( #编译optimizer = adam,loss = 'categorical_crossentropy',metrics=['accuracy'], #在更新时同时计算一下accuracy
        )print("Training~~~~~~~~")
#Another way to train the model
model.fit(x_train,y_train, epochs=1, batch_size=32) #训练2大批,每批32个print("\nTesting~~~~~~~~~~")
#Evalute the model with the  metrics we define earlier
loss,accuracy = model.evaluate(x_test,y_test)print('\ntest loss:',loss)
print('\ntest accuracy:', accuracy)

View Code

输出:

转载于:https://www.cnblogs.com/caiyishuai/p/9603645.html

用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)...相关推荐

  1. DL之CNN:利用卷积神经网络算法(2→2,基于Keras的API-Functional)利用MNIST(手写数字图片识别)数据集实现多分类预测

    DL之CNN:利用卷积神经网络算法(2→2,基于Keras的API-Functional)利用MNIST(手写数字图片识别)数据集实现多分类预测 目录 输出结果 设计思路 核心代码 输出结果 下边两张 ...

  2. DL之CNN:利用卷积神经网络算法(2→2,基于Keras的API-Sequential)利用MNIST(手写数字图片识别)数据集实现多分类预测

    DL之CNN:利用卷积神经网络算法(2→2,基于Keras的API-Sequential)利用MNIST(手写数字图片识别)数据集实现多分类预测 目录 输出结果 设计思路 核心代码 输出结果 1.10 ...

  3. TF:基于CNN(2+1)实现MNIST手写数字图片识别准确率提高到99%

    TF:基于CNN(2+1)实现MNIST手写数字图片识别准确率提高到99% 导读 与Softmax回归模型相比,使用两层卷积的神经网络模型借助了卷积的威力,准确率高非常大的提升. 目录 输出结果 代码 ...

  4. DL之NN:利用(本地数据集50000张数据集)调用自定义神经网络network.py实现手写数字图片识别94%准确率

    DL之NN:利用(本地数据集50000张数据集)调用自定义神经网络network.py实现手写数字图片识别94%准确率 目录 输出结果 代码设计 输出结果 更新-- 代码设计 import mnist ...

  5. TF之CNN:利用sklearn(自带手写数字图片识别数据集)使用dropout解决学习中overfitting的问题+Tensorboard显示变化曲线

    TF之CNN:利用sklearn(自带手写数字图片识别数据集)使用dropout解决学习中overfitting的问题+Tensorboard显示变化曲线 目录 输出结果 设计代码 输出结果 设计代码 ...

  6. DL之NN/CNN:NN算法进阶优化(本地数据集50000张训练集图片),六种不同优化算法实现手写数字图片识别逐步提高99.6%准确率

    DL之NN/CNN:NN算法进阶优化(本地数据集50000张训练集图片),六种不同优化算法实现手写数字图片识别逐步提高99.6%准确率 目录 设计思路 设计代码 设计思路 设计代码 import mn ...

  7. 深度篇—— CNN 卷积神经网络(四) 使用 tf cnn 进行 mnist 手写数字 代码演示项目

    返回主目录 返回 CNN 卷积神经网络目录 上一章:深度篇-- CNN 卷积神经网络(三) 关于 ROI pooling 和 ROI Align 与 插值 本小节,细说 使用 tf cnn 进行 mn ...

  8. 简单神经网络实现手写数字图片识别

    文章目录 1.Mnist数据集神经网络实现流程 2.代码实现 1.Mnist数据集神经网络实现流程 准备数据 全连接结果计算 损失优化 模型评估(计算准确性) 2.代码实现 # @XST1520203 ...

  9. 深度学习——CNN实现MNIST手写数字的识别

    ​活动地址:CSDN21天学习挑战赛 目录 知识点介绍 MNIST 介绍 下载 数据的简单处理 CNN神经网络 CNN的作用 CNN的主要特征 CNN的神经网络结构 CNN的相关参数 MNIST识别的 ...

最新文章

  1. Dubbo源码分析(六)服务引用的具体流程
  2. 玩转Google开源C++单元测试框架Google Test系列(gtest)(总)
  3. 软件工程作业2.1:阐述对软件工程的理解,学完这门课自己能学到什么,学完后能做什么...
  4. weka arff稀疏数据写法
  5. match_phrase搜不出来,怎么办?
  6. mysql 备份 一张表_mysql 备份表的一个方法
  7. 传京东将收购格力电器5%股权 官方回应:消息不实
  8. leetcode 93.复原IP地址 dfs解法
  9. arcgis视频教程 定制技术服务_坐标转换_等高线生成各种问题远程解决
  10. SharePoint 2019 图文安装教程
  11. scratch编程体感游戏
  12. vba操作word删除某些页面
  13. 搭建测试环境详细步骤
  14. Python 自动批量生成发卡平台卡密信息并导入数据库
  15. html字幕文本,HTML字幕
  16. iOS 集成Facebook登陆
  17. 计算机系统删除一点会怎么样,怎么样清理C盘的多余文件?
  18. 虚拟机安装centos7上网设置总结
  19. 快速响应 智慧应急|大势智慧亮相第三届武汉国际安全应急博览会
  20. Android(Java)加载SO文件

热门文章

  1. Oracle的join默认为,oracle join用法
  2. CentOS8安装jdk1.8
  3. java对象与json对象间的相互转换的方法
  4. MYSQL5.6服务启动不起来
  5. Android开发笔记(四十四)动态UI事件
  6. 致传统企业朋友:不够痛就别微服务,有坑 (1)
  7. HTML和CSS 基本要点必看
  8. AI-多云互联,网络通信的“自动驾驶
  9. git快速入门 push/clone/reset/merge/切换分支全都有
  10. ASP.NET MVC5+EF6+EasyUI 后台管理系统(90)-EF 扩展操作