【深度学习系列】PaddlePaddle之手写数字识别
- CPU版本安装
pip install paddlepaddle
- GPU版本安装
pip install paddlepaddle-gpu
导入数据---->定义网络结构---->训练模型---->保存模型---->测试结果
- #coding:utf-8
- import os
- from PIL import Image
- import numpy as np
- import paddle.v2 as paddle
- # 设置是否用gpu,0为否,1为是
- with_gpu = os.getenv('WITH_GPU', '') != ''
- # 定义网络结构
- def convolutional_neural_network_org(img):
- # 第一层卷积层
- conv_pool_1 = paddle.networks.simple_img_conv_pool(
- input=img,
- filter_size=5,
- num_filters=20,
- num_channel=1,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 第二层卷积层
- conv_pool_2 = paddle.networks.simple_img_conv_pool(
- input=conv_pool_1,
- filter_size=5,
- num_filters=50,
- num_channel=20,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 全连接层
- predict = paddle.layer.fc(
- input=conv_pool_2, size=10, act=paddle.activation.Softmax())
- return predict
- def main():
- # 初始化定义跑模型的设备
- paddle.init(use_gpu=with_gpu, trainer_count=1)
- # 读取数据
- images = paddle.layer.data(
- name='pixel', type=paddle.data_type.dense_vector(784))
- label = paddle.layer.data(
- name='label', type=paddle.data_type.integer_value(10))
- # 调用之前定义的网络结构
- predict = convolutional_neural_network_org(images)
- # 定义损失函数
- cost = paddle.layer.classification_cost(input=predict, label=label)
- # 指定训练相关的参数
- parameters = paddle.parameters.create(cost)
- # 定义训练方法
- optimizer = paddle.optimizer.Momentum(
- learning_rate=0.1 / 128.0,
- momentum=0.9,
- regularization=paddle.optimizer.L2Regularization(rate=0.0005 * 128))
- # 训练模型
- trainer = paddle.trainer.SGD(
- cost=cost, parameters=parameters, update_equation=optimizer)
- lists = []
- # 定义event_handler,输出训练过程中的结果
- def event_handler(event):
- if isinstance(event, paddle.event.EndIteration):
- if event.batch_id % 100 == 0:
- print "Pass %d, Batch %d, Cost %f, %s" % (
- event.pass_id, event.batch_id, event.cost, event.metrics)
- if isinstance(event, paddle.event.EndPass):
- # 保存参数
- with open('params_pass_%d.tar' % event.pass_id, 'w') as f:
- parameters.to_tar(f)
- result = trainer.test(reader=paddle.batch(
- paddle.dataset.mnist.test(), batch_size=128))
- print "Test with Pass %d, Cost %f, %s\n" % (
- event.pass_id, result.cost, result.metrics)
- lists.append((event.pass_id, result.cost,
- result.metrics['classification_error_evaluator']))
- trainer.train(
- reader=paddle.batch(
- paddle.reader.shuffle(paddle.dataset.mnist.train(), buf_size=8192),
- batch_size=128),
- event_handler=event_handler,
- num_passes=10)
- # 找到训练误差最小的一次结果
- best = sorted(lists, key=lambda list: float(list[1]))[0]
- print 'Best pass is %s, testing Avgcost is %s' % (best[0], best[1])
- print 'The classification accuracy is %.2f%%' % (100 - float(best[2]) * 100)
- # 加载数据
- def load_image(file):
- im = Image.open(file).convert('L')
- im = im.resize((28, 28), Image.ANTIALIAS)
- im = np.array(im).astype(np.float32).flatten()
- im = im / 255.0
- return im
- # 测试结果
- test_data = []
- cur_dir = os.path.dirname(os.path.realpath(__file__))
- test_data.append((load_image(cur_dir + '/image/infer_3.png'), ))
- probs = paddle.infer(
- output_layer=predict, parameters=parameters, input=test_data)
- lab = np.argsort(-probs) # probs and lab are the results of one batch data
- print "Label of image/infer_3.png is: %d" % lab[0][0]
- if __name__ == '__main__':
- main()
上面的代码看起来很长,但结构还是很清楚的。下面我们用实际数据测试一下,看一下效果到底怎么样~
- def convolutional_neural_network_org(img):
- # 第一层卷积层
- conv_pool_1 = paddle.networks.simple_img_conv_pool(
- input=img,
- filter_size=5,
- num_filters=20,
- num_channel=1,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 第二层卷积层
- conv_pool_2 = paddle.networks.simple_img_conv_pool(
- input=conv_pool_1,
- filter_size=5,
- num_filters=50,
- num_channel=20,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 全连接层
- predict = paddle.layer.fc(
- input=conv_pool_2, size=10, act=paddle.activation.Softmax())
- return predict
输出结果如下:
- I1023 13:45:46.519075 34144 Util.cpp:166] commandline: --use_gpu=True --trainer_count=1
- [INFO 2017-10-23 13:45:52,667 layers.py:2539] output for __conv_pool_0___conv: c = 20, h = 24, w = 24, size = 11520
- [INFO 2017-10-23 13:45:52,667 layers.py:2667] output for __conv_pool_0___pool: c = 20, h = 12, w = 12, size = 2880
- [INFO 2017-10-23 13:45:52,668 layers.py:2539] output for __conv_pool_1___conv: c = 50, h = 8, w = 8, size = 3200
- [INFO 2017-10-23 13:45:52,669 layers.py:2667] output for __conv_pool_1___pool: c = 50, h = 4, w = 4, size = 800
- I1023 13:45:52.675750 34144 GradientMachine.cpp:85] Initing parameters..
- I1023 13:45:52.686153 34144 GradientMachine.cpp:92] Init parameters done.
- Pass 0, Batch 0, Cost 3.048408, {'classification_error_evaluator': 0.890625}
- Pass 0, Batch 100, Cost 0.188828, {'classification_error_evaluator': 0.0546875}
- Pass 0, Batch 200, Cost 0.075183, {'classification_error_evaluator': 0.015625}
- Pass 0, Batch 300, Cost 0.070798, {'classification_error_evaluator': 0.015625}
- Pass 0, Batch 400, Cost 0.079673, {'classification_error_evaluator': 0.046875}
- Test with Pass 0, Cost 0.074587, {'classification_error_evaluator': 0.023800000548362732}
- ```
- ```
- ```
- Pass 4, Batch 0, Cost 0.032454, {'classification_error_evaluator': 0.015625}
- Pass 4, Batch 100, Cost 0.021028, {'classification_error_evaluator': 0.0078125}
- Pass 4, Batch 200, Cost 0.020458, {'classification_error_evaluator': 0.0}
- Pass 4, Batch 300, Cost 0.046728, {'classification_error_evaluator': 0.015625}
- Pass 4, Batch 400, Cost 0.030264, {'classification_error_evaluator': 0.015625}
- Test with Pass 4, Cost 0.035841, {'classification_error_evaluator': 0.01209999993443489}
- Best pass is 4, testing Avgcost is 0.0358410408473
- The classification accuracy is 98.79%
- Label of image/infer_3.png is: 3
- real 0m31.565s
- user 0m20.996s
- sys 0m15.891s
可以看到,第一行输出选择的设备是否是gpu,这里我选择的是gpu,所以等于1,如果是cpu,就是0。接下来四行输出的是网络结构,然后开始输出训练结果,训练结束,我们把这几次迭代中误差最小的结果输出来,98.79%,效果还是很不错的,毕竟只迭代了5次。最后看一下输出时间,非常快,约31秒。然而这个结果我并不是特别满意,因为之前用keras做的时候调整的网络模型训练往后准确率能够达到99.72%,不过速度非常慢,迭代69次大概需要30分钟左右,所以我觉得这个网络结构还是可以改进一下的,所以我对这个网络结构改进了一下,请看改进版
改进版
- def convolutional_neural_network(img):
- # 第一层卷积层
- conv_pool_1 = paddle.networks.simple_img_conv_pool(
- input=img,
- filter_size=5,
- num_filters=20,
- num_channel=1,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 加一层dropout层
- drop_1 = paddle.layer.dropout(input=conv_pool_1, dropout_rate=0.2)
- # 第二层卷积层
- conv_pool_2 = paddle.networks.simple_img_conv_pool(
- input=drop_1,
- filter_size=5,
- num_filters=50,
- num_channel=20,
- pool_size=2,
- pool_stride=2,
- act=paddle.activation.Relu())
- # 加一层dropout层
- drop_2 = paddle.layer.dropout(input=conv_pool_2, dropout_rate=0.5)
- # 全连接层
- fc1 = paddle.layer.fc(input=drop_2, size=10, act=paddle.activation.Linear())
- bn = paddle.layer.batch_norm(input=fc1,act=paddle.activation.Relu(),
- layer_attr=paddle.attr.Extra(drop_rate=0.2))
- predict = paddle.layer.fc(input=bn, size=10, act=paddle.activation.Softmax())
- return predict
在改进版里我们加了一些dropout层来避免过拟合。分别在第一层卷积层和第二层卷积层后加了dropout,阈值设为0.5。改变网络结构也非常简单,直接在定义的网络结构函数里对模型进行修改即可,这一点其实和keras的网络结构定义方式还是挺像的,易用性很高。下面来看看效果:
- I1023 14:01:51.653827 34244 Util.cpp:166] commandline: --use_gpu=True --trainer_count=1
- [INFO 2017-10-23 14:01:57,830 layers.py:2539] output for __conv_pool_0___conv: c = 20, h = 24, w = 24, size = 11520
- [INFO 2017-10-23 14:01:57,831 layers.py:2667] output for __conv_pool_0___pool: c = 20, h = 12, w = 12, size = 2880
- [INFO 2017-10-23 14:01:57,832 layers.py:2539] output for __conv_pool_1___conv: c = 50, h = 8, w = 8, size = 3200
- [INFO 2017-10-23 14:01:57,833 layers.py:2667] output for __conv_pool_1___pool: c = 50, h = 4, w = 4, size = 800
- I1023 14:01:57.842871 34244 GradientMachine.cpp:85] Initing parameters..
- I1023 14:01:57.854014 34244 GradientMachine.cpp:92] Init parameters done.
- Pass 0, Batch 0, Cost 2.536199, {'classification_error_evaluator': 0.875}
- Pass 0, Batch 100, Cost 1.668236, {'classification_error_evaluator': 0.515625}
- Pass 0, Batch 200, Cost 1.024846, {'classification_error_evaluator': 0.375}
- Pass 0, Batch 300, Cost 1.086315, {'classification_error_evaluator': 0.46875}
- Pass 0, Batch 400, Cost 0.767804, {'classification_error_evaluator': 0.25}
- Pass 0, Batch 500, Cost 0.545784, {'classification_error_evaluator': 0.1875}
- Pass 0, Batch 600, Cost 0.731662, {'classification_error_evaluator': 0.328125}
- ```
- ```
- ```
- Pass 49, Batch 0, Cost 0.415184, {'classification_error_evaluator': 0.09375}
- Pass 49, Batch 100, Cost 0.067616, {'classification_error_evaluator': 0.0}
- Pass 49, Batch 200, Cost 0.161415, {'classification_error_evaluator': 0.046875}
- Pass 49, Batch 300, Cost 0.202667, {'classification_error_evaluator': 0.046875}
- Pass 49, Batch 400, Cost 0.336043, {'classification_error_evaluator': 0.140625}
- Pass 49, Batch 500, Cost 0.290948, {'classification_error_evaluator': 0.125}
- Pass 49, Batch 600, Cost 0.223433, {'classification_error_evaluator': 0.109375}
- Pass 49, Batch 700, Cost 0.217345, {'classification_error_evaluator': 0.0625}
- Pass 49, Batch 800, Cost 0.163140, {'classification_error_evaluator': 0.046875}
- Pass 49, Batch 900, Cost 0.203645, {'classification_error_evaluator': 0.078125}
- Test with Pass 49, Cost 0.033639, {'classification_error_evaluator': 0.008100000210106373}
- Best pass is 48, testing Avgcost is 0.0313018567383
- The classification accuracy is 99.28%
- Label of image/infer_3.png is: 3
- real 5m3.151s
- user 4m0.052s
- sys 1m8.084s

【深度学习系列】PaddlePaddle之手写数字识别的更多相关文章
- NN:利用深度学习之神经网络实现手写数字识别(数据集50000张图片)—Jason niu
import mnist_loader import network training_data, validation_data, test_data = mnist_loader.load_dat ...
- TensorFlow 卷积神经网络手写数字识别数据集介绍
欢迎大家关注我们的网站和系列教程:http://www.tensorflownews.com/,学习更多的机器学习.深度学习的知识! 手写数字识别 接下来将会以 MNIST 数据集为例,使用卷积层和池 ...
- 实现手写数字识别(数据集50000张图片)比较3种算法神经网络、灰度平均值、SVM各自的准确率—Jason niu
对手写数据集50000张图片实现阿拉伯数字0~9识别,并且对结果进行分析准确率, 手写数字数据集下载:http://yann.lecun.com/exdb/mnist/ 首先,利用图片本身的属性,图片 ...
- 【深度学习系列】手写数字识别卷积神经--卷积神经网络CNN原理详解(一)
上篇文章我们给出了用paddlepaddle来做手写数字识别的示例,并对网络结构进行到了调整,提高了识别的精度.有的同学表示不是很理解原理,为什么传统的机器学习算法,简单的神经网络(如多层感知机)都可 ...
- 【PaddlePaddle系列】手写数字识别
最近百度为了推广自家编写对深度学习框架PaddlePaddle不断推出各种比赛.百度声称PaddlePaddle是一个“易学.易用”的开源深度学习框架,然而网上的资料少之又少.虽然百度很用心地提供 ...
- 深度学习之 mnist 手写数字识别
深度学习之 mnist 手写数字识别 开始学习深度学习,先来一个手写数字的程序 import numpy as np import os import codecs import torch from ...
- 深度学习之PyTorch实战(3)——实战手写数字识别
上一节,我们已经学会了基于PyTorch深度学习框架高效,快捷的搭建一个神经网络,并对模型进行训练和对参数进行优化的方法,接下来让我们牛刀小试,基于PyTorch框架使用神经网络来解决一个关于手写数字 ...
- 用MXnet实战深度学习之一:安装GPU版mxnet并跑一个MNIST手写数字识别
用MXnet实战深度学习之一:安装GPU版mxnet并跑一个MNIST手写数字识别 http://phunter.farbox.com/post/mxnet-tutorial1 用MXnet实战深度学 ...
- 深度学习面试题12:LeNet(手写数字识别)
目录 神经网络的卷积.池化.拉伸 LeNet网络结构 LeNet在MNIST数据集上应用 参考资料 LeNet是卷积神经网络的祖师爷LeCun在1998年提出,用于解决手写数字识别的视觉任务.自那时起 ...
随机推荐
- 201521123119《Java程序设计》第4周学习总结
1. 本周学习总结 2.书面作业 1.注释的应用 使用类的注释与方法的注释为前面编写的类与方法进行注释,并在Eclipse中查看.(截图) 2.面向对象设计(大作业1,非常重要) 2.1 将在网上商城 ...
- 201521123049 《JAVA程序设计》 第3周学习总结
1. 本周学习总结 1.学习了对象与类的定义: 2.掌握了构造函数与其重载: 3.学会了this关键字的利用: 4.明白了静态变量与非静态变量的区分. 下面是对本周学习的图片小结: 2. 书面作业 Q ...
- 201521123113 《Java程序设计》第2周学习总结
1.本周学习总结 学习了各种java数据类型以及各种运算符的使用 string类之所以好用是因为这是人可以看得懂的类型,操作简便 Scanner扫描器与标准输出输入用法上的不同,Scanner较标准输 ...
- 201521123122 《java程序设计》第九周学习总结
201521123122 <java程序设计>第九周实验总结 1. 本周学习总结 以你喜欢的方式(思维导图或其他)归纳总结集合相关内容. 2. 书面作业 常用异常 题目5-1 1.1 截图 ...
- 多线程:head first Thread.join()
不使用Thread.join() 测试线程 先上代码: /** * Created by Zero on 2017/8/23. */ public class TestJoin implements ...
- Spring-Struts2-基本集成
步骤: 1,导入struts2的相关jar包(检查是否有冲突的包,即同一个包有不同的几个版本存在) 2,导入struts2和spring的整合包 struts2-spring-plugin-2.3.4 ...
- 凸包GiftWrapping GrahamScan 算法实现
开始 游戏内有需求做多边形碰撞功能,但是接入box2d相对游戏的需求来说太重度了.所以准备自己实现碰撞. 确定多边形,必然要用到凸包的算法.在github上也找到了一些lua实现,但是这里的算法没有考 ...
- jquery模板下载网站
jquery模板下载网站 http://www.jqshare.com/
- JS设计模式(三) 数据访问对象模式
引言 HTML5 提供了两种在客户端存储数据的新方法:localStorage.sessionStorage,他们是Web Storage API 提供的两种存储机制,区别在于前者属于永久性存储,而后 ...
- Merge Two Binary Trees
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of t ...