用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 #数据包,如 ...
随机推荐
- SharePoint Visio Graphics Service-PowerShell
1. 配置托管服务账户 Set-SPVisioExternalData -VisioServiceApplication "Visio Graphics Service" –Una ...
- Android手机使用广播监听手机收到的短信
我们使用的Android手机在收到短信的时候会发出一条系统广播.该条广播中存放着接收到的短信的详细信息.本文将详细介绍如何通过动态注册广播来监听短信. 注册广播有两种方式,一种是动态注册,另一种是静态 ...
- poj-1112 (二分图染色+dp分组)
#include <iostream> #include <algorithm> #include <cstring> using namespace std; ; ...
- CF1143F/1142C U2
CF1143F/1142C U2 巧妙的思维题.注意到这里只用两个点就可以确定一根抛物线,联想到两点确定一条直线,尝试转化. \(y=x^2+bx+c\) 就可以写成 \(y-x^2=bx+c\) , ...
- BZOJ1369/BZOJ2865 【后缀数组+线段树】
Description XX在进行字符串研究的时候,遇到了一个十分棘手的问题. 在这个问题中,给定一个字符串S,与一个整数K,定义S的子串T=S(i, j)是关于第K位的识别子串,满足以下两个条件: ...
- gcd模板(欧几里得与扩展欧几里得、拓展欧几里得求逆元)
gcd(欧几里得算法辗转相除法): gcd ( a , b )= d : 即 d = gcd ( a , b ) = gcd ( b , a mod b ):以此式进行递归即可. 之前一直愚蠢地以为辗 ...
- gridview 自动序号 合计
第一种方式,直接在Aspx页面GridView模板列中.这种的缺点是到第二页分页时又重新开始了. <asp:TemplateField HeaderText="序号" Ins ...
- sprintf拼接字符串的问题
] = {}; char a1[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G'}; char a2[] = {'H', 'I', 'J', 'K', 'L', 'M', ...
- 基于 FastAdmin 开发后台流程 (持续更新)
使用 git init 初始化 增加一个自己的git 原始仓库,用于存放自己的代码. 增加一个 fastadmin 的仓库,为了方便以后与官方同步. 自己修改的代码 git Push 到自己的仓库 将 ...
- 【转】每天一个linux命令(51):lsof命令
原文网址:http://www.cnblogs.com/peida/archive/2013/02/26/2932972.html lsof(list open files)是一个列出当前系统打开文件 ...