用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 #数据包,如 ...
随机推荐
- Oracle 与Sql Server常用函数对比
来自:http://topic.csdn.net/u/20080704/08/b2b8c42f-b0d6-4cda-98b1-6e4a279b4ff8.html 感谢楼主 函数 SQLServer和O ...
- c++模板函数声明定义分离编译错误详解
今天看到accelerated c++上有个简单的vector容器的实现Vec,就再vs2008上编译了下: ///// Vec.h #ifndef GUARD_VEC_H #define GUARD ...
- 打开TestFlight并链接到具体的应用下载界面
在我们应用正式上线前,许多时候都会有小流量的测试,选取部分核心用户抢先试用,在TestFlight出来之前,一般都是通过企业证书打包,然后提供给用户下载地址,安装测试使用,这个有个不爽之处就是,企业i ...
- Translate Exercises(4)
周五翻译课记录. ---------------------------------- (1)and it is imagined by many that the operations of the ...
- Nexus私服的安装与配置
Nexus的安装与配置 仅以此文,献给陷入懒癌晚期的小伙伴们. 本文基于nexus 3.xx .0. What?Why?When?Who?Where? Sonatype Nexus是一款maven仓库 ...
- Java Iterator的一般用法
Iterator(迭代器) 迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构.迭代器通常被称为“轻量级”对象,因为创建它的代价小. Java中的I ...
- paho.mqtt.embedded-c MQTTPacket transport.c hacking
/******************************************************************************* * paho.mqtt.embedde ...
- 通过Servlet设置文件下载
文件下载 1.获取要下载的文件的绝对路径 但是使用getServletContext().getRealPath()方法在不同的服务器上所获得的实现是不一样的 因为项目被打包入.war文件以后就失去了 ...
- 51Nod 1009:1009 数字1的数量 (思维)
1009 数字1的数量 基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题 收藏 关注 给定一个十进制正整数N,写下从1开始,到N的所有正数,计算出其中出现所有1的 ...
- 原型设计 Axure8.1 软件注册码
用户名:Koshy 注册码: wTADPqxn3KChzJxLmUr5jTTitCgsfRkftQQ1yIG9HmK83MYSm7GPxLREGn+Ii6xY