用Keras搭建神经网络 简单模版(三)—— CNN 卷积神经网络(手写数字图片识别)
# -*- 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 卷积神经网络(手写数字图片识别)的更多相关文章
- 吴裕雄 python神经网络 手写数字图片识别(5)
import kerasimport matplotlib.pyplot as pltfrom keras.models import Sequentialfrom keras.layers impo ...
- 用Keras搭建神经网络 简单模版(四)—— RNN Classifier 循环神经网络(手写数字图片识别)
# -*- coding: utf-8 -*- import numpy as np np.random.seed(1337) from keras.datasets import mnist fro ...
- 吴裕雄 python 神经网络——TensorFlow 卷积神经网络手写数字图片识别
import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_N ...
- 用python实现数字图片识别神经网络--启动网络的自我训练流程,展示网络数字图片识别效果
上一节,我们完成了网络训练代码的实现,还有一些问题需要做进一步的确认.网络的最终目标是,输入一张手写数字图片后,网络输出该图片对应的数字.由于网络需要从0到9一共十个数字中挑选出一个,于是我们的网络最 ...
- keras和tensorflow搭建DNN、CNN、RNN手写数字识别
MNIST手写数字集 MNIST是一个由美国由美国邮政系统开发的手写数字识别数据集.手写内容是0~9,一共有60000个图片样本,我们可以到MNIST官网免费下载,总共4个.gz后缀的压缩文件,该文件 ...
- [Python]基于CNN的MNIST手写数字识别
目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...
- 第三节,CNN案例-mnist手写数字识别
卷积:神经网络不再是对每个像素做处理,而是对一小块区域的处理,这种做法加强了图像信息的连续性,使得神经网络看到的是一个图像,而非一个点,同时也加深了神经网络对图像的理解,卷积神经网络有一个批量过滤器, ...
- NN:神经网络算法进阶优化法,进一步提高手写数字识别的准确率—Jason niu
上一篇文章,比较了三种算法实现对手写数字识别,其中,SVM和神经网络算法表现非常好准确率都在90%以上,本文章进一步探讨对神经网络算法优化,进一步提高准确率,通过测试发现,准确率提高了很多. 首先,改 ...
- tensorflow学习之(十)使用卷积神经网络(CNN)分类手写数字0-9
#卷积神经网络cnn import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #数据包,如 ...
随机推荐
- PSP个人软件开发系统面向对象需求分析与设计文档
1.引言 1.1编写的目的 编写该文档的目的是,对产品进行定义,详尽说明该产品的软件需求,简述我们对 PSP个人软件开发系统的初步设想,及划分的各功能模块以及各模块的实体图和数据流图. 1.2预期的读 ...
- Android Mms专题之:Mms源码结构
从软件的功能角度来讲,Mms分为对话列表,消息列表,短信编辑,彩信编辑,短信显示,彩信显示和配置. 从实现的角度来看,它分为GUI展示层,发送/接收,彩信解析,彩信附件,信息数据等,这些分类对应着源码 ...
- 接下来将介绍C#如何设置子窗体在主窗体中居中显示,本文提供详细的操作步骤,需要的朋友可以参考下
接下来将介绍C#如何设置子窗体在主窗体中居中显示,本文提供详细的操作步骤,需要的朋友可以参考下 其实表面上看是很简单的 开始吧,现在有两个窗体Form1主窗体,Form2子窗体 而且我相信大部分人都会 ...
- 《利用Python进行数据分析》笔记---第6章数据加载、存储与文件格式
写在前面的话: 实例中的所有数据都是在GitHub上下载的,打包下载即可. 地址是:http://github.com/pydata/pydata-book 还有一定要说明的: 我使用的是Python ...
- cocos2dx 3.1.1移植安卓apk (lua项目交叉编译 mac环境下)
cocos2dx 3.1.1 lua项目安卓交叉编译 mac环境下 本文基于ant,sdk,ndk,adt等软件和环境已经事前设置好 1\新建项目 在mac的终端下输入命令: cocos new te ...
- POJ 2367:Genealogical tree(拓扑排序模板)
Genealogical tree Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 7285 Accepted: 4704 ...
- element组件知识点总结
1:单选框与多选框的change事件,html代码 <div id="app"> <div class="demo box"> < ...
- java环境变量 Path 与CLASSPATH
1.Windows操作系统根据Path环境变量来查找命令,Linux操作系统则根据PATH环境变量来查找命令 因为Windows操作系统不区分大小写,设置Path和PATH并没有区别,而Linux系统 ...
- List和json数组的转换(赋源代码)
public class a11111111 { //参数obj可以是 json对象,字符串, list public static void fun(Object obj){ JSONArray d ...
- Patch打补丁学习笔记
1.基本命令语法: patch [-R] {-p(n)} [--dry-run] < patch_file_name p:为path的缩写. n:指将patch文件中的path第n条’/’及其左 ...