# -*- 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 method
input_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*2
strides=(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 method
input_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*2
strides=(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)

输出:

用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)的更多相关文章

  1. 吴裕雄 python神经网络 手写数字图片识别(5)

    import kerasimport matplotlib.pyplot as pltfrom keras.models import Sequentialfrom keras.layers impo ...

  2. 用Keras搭建神经网络 简单模版(四)—— RNN Classifier 循环神经网络(手写数字图片识别)

    # -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) from keras.datasets import mnist fro ...

  3. 吴裕雄 python 神经网络——TensorFlow 卷积神经网络手写数字图片识别

    import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_N ...

  4. 用python实现数字图片识别神经网络--启动网络的自我训练流程,展示网络数字图片识别效果

    上一节,我们完成了网络训练代码的实现,还有一些问题需要做进一步的确认.网络的最终目标是,输入一张手写数字图片后,网络输出该图片对应的数字.由于网络需要从0到9一共十个数字中挑选出一个,于是我们的网络最 ...

  5. keras和tensorflow搭建DNN、CNN、RNN手写数字识别

    MNIST手写数字集 MNIST是一个由美国由美国邮政系统开发的手写数字识别数据集.手写内容是0~9,一共有60000个图片样本,我们可以到MNIST官网免费下载,总共4个.gz后缀的压缩文件,该文件 ...

  6. [Python]基于CNN的MNIST手写数字识别

    目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...

  7. 第三节,CNN案例-mnist手写数字识别

    卷积:神经网络不再是对每个像素做处理,而是对一小块区域的处理,这种做法加强了图像信息的连续性,使得神经网络看到的是一个图像,而非一个点,同时也加深了神经网络对图像的理解,卷积神经网络有一个批量过滤器, ...

  8. NN:神经网络算法进阶优化法,进一步提高手写数字识别的准确率—Jason niu

    上一篇文章,比较了三种算法实现对手写数字识别,其中,SVM和神经网络算法表现非常好准确率都在90%以上,本文章进一步探讨对神经网络算法优化,进一步提高准确率,通过测试发现,准确率提高了很多. 首先,改 ...

  9. tensorflow学习之(十)使用卷积神经网络(CNN)分类手写数字0-9

    #卷积神经网络cnn import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #数据包,如 ...

随机推荐

  1. 大数据技术Hadoop面试题

    1. 下面哪个程序负责 HDFS 数据存储.答案C datanode a)NameNodeb)Jobtrackerc)Datanode d)secondaryNameNodee)tasktracker ...

  2. selenium安装后,需要安装浏览器驱动

    google的驱动:chromedriver.exe 驱动版本与chrome版本对应的目录: http://npm.taobao.org/mirrors/chromedriver/2.32/notes ...

  3. DevExpress v17.2新版亮点——VCL篇(二)

    用户界面套包DevExpress v17.2日前终于正式发布,本站将以连载的形式为大家介绍各版本新增内容.本文将介绍了DevExpress VCL v17.2 的新功能,快来下载试用新版本! DPI ...

  4. tomcat部署和启动3

    点击STATUES,弹出登陆框 You are not authorized to view this page. If you have not changed any configuration ...

  5. 图解SQL的inner join、left join、right join、full outer join、union、union all的区别【转载】

    对于SQL的Join,在学习起来可能是比较乱的.我们知道,SQL的Join语法有很多inner的,有outer的,有left的,有时候,对于Select出来的结果集是什么样子有点不是很清楚.Codin ...

  6. 设计Popup Window

    设计一个Popup window, 在其中实现分享到Facebook 和Twitter 功能. popup window 名称为 ShareView.xaml, 代码如下: <phone:Pho ...

  7. Struck: Structured Output Tracking with Kernels

    reference: Struck: Structured Output Tracking with Kernels hot topic: tracking-by-detection methods, ...

  8. 只需 5 秒钟,你就能取到 WPF 程序的超高分辨率超高清截图

    我想要截取一个 WPF 程序的图标,但是它太小了.如果我就这样截屏截下来,是很不高清的.由于我需要制作一份课件,所以我需要超高清版本,可是,如何做才能最快速拿到 WPF 程序的超高清截图呢? 本文分享 ...

  9. 2015 PHP框架调查结果出炉,Laravel最受欢迎!

    日前,SitePoint花了一个月时间进行了有关PHP框架使用情况的调查,通过调查结果所示,无论是在团队项目还是个人项目:无论是国家或是年龄层次,Laravel都是使用最多的一款框架. 其中,最流行的 ...

  10. 使用python的Paramiko模块登陆SSH

    使用python的Paramiko模块登陆SSH paramiko是用Python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接. python的paramiko模块 ...