用PaddlePaddle和Tensorflow进行图像分类

作者:Charlotte77数学系的数据挖掘民工

博客专栏:http://www.cnblogs.com/charlotte77/

个人公众号:Charlotte数据挖掘(ID:CharlotteDataMining)

上个月发布了四篇文章,主要讲了深度学习中的“hello world”----mnist图像识别,以及卷积神经网络的原理详解,包括基本原理、自己手写CNN和paddlepaddle的源码解析。这篇主要跟大家讲讲如何用PaddlePaddle和Tensorflow做图像分类。所有程序都在我的github里,可以自行下载训练。

在卷积神经网络中,有五大经典模型,分别是:LeNet-5,AlexNet,GoogleNet,Vgg和ResNet。本文首先自己设计一个小型CNN网络结构来对图像进行分类,再了解一下LeNet-5网络结构对图像做分类,并用比较流行的Tensorflow框架和百度的PaddlePaddle实现LeNet-5网络结构,并对结果对比。

什么是图像分类

图像分类是根据图像的语义信息将不同类别图像区分开来,是计算机视觉中重要的基本问题,也是图像检测、图像分割、物体跟踪、行为分析等其他高层视觉任务的基础。图像分类在很多领域有广泛应用,包括安防领域的人脸识别和智能视频分析等,交通领域的交通场景识别,互联网领域基于内容的图像检索和相册自动归类,医学领域的图像识别等(引用自官网)

cifar-10数据集

CIFAR-10分类问题是机器学习领域的一个通用基准,由60000张32*32的RGB彩色图片构成,共10个分类。50000张用于训练集,10000张用于测试集。其问题是将32X32像素的RGB图像分类成10种类别:飞机,手机,鸟,猫,鹿,狗,青蛙,马,船和卡车。更多信息可以参考CIFAR-10和Alex Krizhevsky的演讲报告。常见的还有cifar-100,分类物体达到100类,以及ILSVRC比赛的100类。

自己设计CNN

了解CNN的基本网络结构后,首先自己设计一个简单的CNN网络结构对cifar-10数据进行分类。

 网络结构

 代码实现

1.网络结构:simple_cnn.py

#coding:utf-8

'''

Created by huxiaoman 2017.11.27

simple_cnn.py:自己设计的一个简单的cnn网络结构

'''

import os

from PIL import Image

import numpy as np

import paddle.v2 as paddle

from paddle.trainer_config_helpers import *

with_gpu = os.getenv('WITH_GPU', '0') != '1'

def simple_cnn(img):

input=img,

filter_size=5,

num_filters=20,

num_channel=3,

pool_size=2,

pool_stride=2,

act=paddle.activation.Relu())

input=conv_pool_1,

filter_size=5,

num_filters=50,

num_channel=20,

pool_size=2,

pool_stride=2,

act=paddle.activation.Relu())

input=conv_pool_2, size=512, act=paddle.activation.Softmax())

2.训练程序:train_simple_cnn.py

#coding:utf-8

'''

Created by huxiaoman 2017.11.27

train_simple—_cnn.py:训练simple_cnn对cifar10数据集进行分类

'''

import sys, os

import paddle.v2 as paddle

from simple_cnn import simple_cnn

with_gpu = os.getenv('WITH_GPU', '0') != '1'

def main():

datadim = 3 * 32 * 32

classdim = 10

# PaddlePaddle init

paddle.init(use_gpu=with_gpu, trainer_count=7)

name="image", type=paddle.data_type.dense_vector(datadim))

# Add neural network config

# option 1. resnet

# net = resnet_cifar10(image, depth=32)

# option 2. vgg

net = simple_cnn(image)

input=net, size=classdim, act=paddle.activation.Softmax())

name="label", type=paddle.data_type.integer_value(classdim))

# Create parameters

# Create optimizer

momentum_optimizer = paddle.optimizer.Momentum(

momentum=0.9,

regularization=paddle.optimizer.L2Regularization(rate=0.0002 * 128),

learning_rate=0.1 / 128.0,

learning_rate_decay_a=0.1,

learning_rate_decay_b=50000 * 100,

learning_rate_schedule='discexp')

# End batch and end pass event handler

def event_handler(event):

if isinstance(event, paddle.event.EndIteration):

if event.batch_id % 100 == 0:

print "\nPass %d, Batch %d, Cost %f, %s" % (

event.pass_id, event.batch_id, event.cost, event.metrics)

else:

if isinstance(event, paddle.event.EndPass):

# save parameters

with open('params_pass_%d.tar' % event.pass_id, 'w') as f:

parameters.to_tar(f)

result = trainer.test(

reader=paddle.batch(

feeding={'image': 0,

'label': 1})

print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

# Create trainer

trainer = paddle.trainer.SGD(

cost=cost, parameters=parameters, update_equation=momentum_optimizer)

# Save the inference topology to protobuf.

inference_topology = paddle.topology.Topology(layers=out)

with open("inference_topology.pkl", 'wb') as f:

inference_topology.serialize_for_inference(f)

trainer.train(

reader=paddle.batch(

batch_size=128),

num_passes=200,

event_handler=event_handler,

feeding={'image': 0,

'label': 1})

# inference

from PIL import Image

import numpy as np

import os

def load_image(file):

im = Image.open(file)

im = im.resize((32, 32), Image.ANTIALIAS)

im = np.array(im).astype(np.float32)

# The storage order of the loaded image is W(widht),

# H(height), C(channel). PaddlePaddle requires

# the CHW order, so transpose them.

im = im.transpose((2, 0, 1)) # CHW

# In the training phase, the channel order of CIFAR

# image is B(Blue), G(green), R(Red). But PIL open

# image in RGB mode. It must swap the channel order.

im = im[(2, 1, 0), :, :] # BGR

im = im.flatten()

im = im / 255.0

return im

test_data = []

test_data.append((load_image(cur_dir + '/image/dog.png'), ))

# users can remove the comments and change the model name

# with open('params_pass_50.tar', 'r') as f:

# parameters = paddle.parameters.Parameters.from_tar(f)

probs = paddle.infer(

output_layer=out, parameters=parameters, input=test_data)

lab = np.argsort(-probs) # probs and lab are the results of one batch data

print "Label of image/dog.png is: %d" % lab[0][0]

if __name__ == '__main__':

main()

3.结果输出

I1128 21:44:30.218085 14733 Util.cpp:166] commandline: --use_gpu=True --trainer_count=7

[INFO 2017-11-28 21:44:35,874 layers.py:2539] output for __conv_pool_0___conv: c = 20, h = 28, w = 28, size = 15680

[INFO 2017-11-28 21:44:35,874 layers.py:2667] output for __conv_pool_0___pool: c = 20, h = 14, w = 14, size = 3920

[INFO 2017-11-28 21:44:35,875 layers.py:2539] output for __conv_pool_1___conv: c = 50, h = 10, w = 10, size = 5000

[INFO 2017-11-28 21:44:35,876 layers.py:2667] output for __conv_pool_1___pool: c = 50, h = 5, w = 5, size = 1250

I1128 21:44:35.881502 14733 MultiGradientMachine.cpp:99] numLogicalDevices=1 numThreads=7 numDevices=8

I1128 21:44:35.928449 14733 GradientMachine.cpp:85] Initing parameters..

I1128 21:44:36.056259 14733 GradientMachine.cpp:92] Init parameters done.

Pass 0, Batch 0, Cost 2.302628, {'classification_error_evaluator': 0.9296875}

................................................................................

```

Pass 199, Batch 200, Cost 0.869726, {'classification_error_evaluator': 0.3671875}

...................................................................................................

Pass 199, Batch 300, Cost 0.801396, {'classification_error_evaluator': 0.3046875}

..........................................................................................I1128 23:21:39.443141 14733 MultiGradientMachine.cpp:99] numLogicalDevices=1 numThreads=7 numDevices=8

Label of image/dog.png is: 9

我开了7个线程,用了8个Tesla K80 GPU训练,batch_size = 128,迭代次数200次,耗时1h37min,错误分类率为0.5248,这个结果,emm,不算很高,我们可以把它作为一个baseline,后面对其进行调优。

LeNet-5网络结构

Lenet-5网络结构来源于Yan LeCun提出的,原文为《Gradient-based learning applied to document recognition》,论文里使用的是mnist手写数字作为输入数据(32 * 32)进行验证。我们来看一下网络结构。

‍‍ LeNet-5一共有8层: 1个输入层+3个卷积层(C1、C3、C5)+2个下采样层(S2、S4)+1个全连接层(F6)+1个输出层,每层有多个feature map(自动提取的多组特征)。‍‍‍‍‍‍

 Input输入层

cifar10 数据集,每一张图片尺寸:32 * 32

C1 卷积层

6个feature_map,卷积核大小 5 * 5 ,feature_map尺寸:28 * 28

每个卷积神经元的参数数目:5 * 5 = 25个和一个bias参数

连接数目:(5*5+1)* 6 *(28*28) = 122,304

参数共享:每个feature_map内共享参数,∴∴共(5*5+1)*6 = 156个参数

S2 下采样层(池化层)

6个14*14的feature_map,pooling大小 2* 2

每个单元与上一层的feature_map中的一个2*2的滑动窗口连接,不重叠,因此S2每个feature_map大小是C1中feature_map大小的1/4

连接数:(2*2+1)*1*14*14*6 = 5880个

参数共享:每个feature_map内共享参数,有2 * 6 = 12个训练参数

C3 卷积层

这层略微复杂,S2神经元与C3是多对多的关系,比如最简单方式:用S2的所有feature map与C3的所有feature map做全连接(也可以对S2抽样几个feature map出来与C3某个feature map连接),这种全连接方式下:6个S2的feature map使用6个独立的5×5卷积核得到C3中1个feature map(生成每个feature map时对应一个bias),C3中共有16个feature map,所以该层需要学习的参数个数为:(5×5×6+1)×16=2416个,神经元连接数为:2416×8×8=154624个。

S4 下采样层

同S2,如果采用Max Pooling/Mean Pooling,则该层需要学习的参数个数为0个,神经元连接数为:(2×2+1)×16×4×4=1280个。

C5卷积层

类似C3,用S4的所有feature map与C5的所有feature map做全连接,这种全连接方式下:16个S4的feature map使用16个独立的1×1卷积核得到C5中1个feature map(生成每个feature map时对应一个bias),C5中共有120个feature map,所以该层需要学习的参数个数为:(1×1×16+1)×120=2040个,神经元连接数为:2040个。

F6 全连接层

将C5层展开得到4×4×120=1920个节点,并接一个全连接层,考虑bias,该层需要学习的参数和连接个数为:(1920+1)*84=161364个。

输出层

该问题是个10分类问题,所以有10个输出单元,通过softmax做概率归一化,每个分类的输出单元对应84个输入。

LeNet-5的PaddlePaddle实现

1.网络结构lenet.py‍‍‍‍‍‍‍‍

#coding:utf-8

'''

Created by huxiaoman 2017.11.27

lenet.py:LeNet-5

'''

import os

from PIL import Image

import numpy as np

import paddle.v2 as paddle

from paddle.trainer_config_helpers import *

with_gpu = os.getenv('WITH_GPU', '0') != '1'

def lenet(img):

input=img,

filter_size=5,

num_filters=6,

num_channel=3,

pool_size=2,

pool_stride=2,

act=paddle.activation.Relu())

input=conv_pool_1,

filter_size=5,

num_filters=16,

pool_size=2,

pool_stride=2,

act=paddle.activation.Relu())

conv_3 = img_conv_layer(

input = conv_pool_2,

filter_size = 1,

num_filters = 120,

stride = 1)

input=conv_3, size=84, act=paddle.activation.Sigmoid())

return fc

2.训练代码train_lenet.py

#coding:utf-8

'''

Created by huxiaoman 2017.11.27

train_lenet.py:训练LeNet-5对cifar10数据集进行分类

'''

import sys, os

import paddle.v2 as paddle

from lenet import lenet

with_gpu = os.getenv('WITH_GPU', '0') != '1'

def main():

datadim = 3 * 32 * 32

classdim = 10

# PaddlePaddle init

paddle.init(use_gpu=with_gpu, trainer_count=7)

name="image", type=paddle.data_type.dense_vector(datadim))

# Add neural network config

# option 1. resnet

# net = resnet_cifar10(image, depth=32)

# option 2. vgg

net = lenet(image)

input=net, size=classdim, act=paddle.activation.Softmax())

name="label", type=paddle.data_type.integer_value(classdim))

# Create parameters

# Create optimizer

momentum_optimizer = paddle.optimizer.Momentum(

momentum=0.9,

regularization=paddle.optimizer.L2Regularization(rate=0.0002 * 128),

learning_rate=0.1 / 128.0,

learning_rate_decay_a=0.1,

learning_rate_decay_b=50000 * 100,

learning_rate_schedule='discexp')

# End batch and end pass event handler

def event_handler(event):

if isinstance(event, paddle.event.EndIteration):

if event.batch_id % 100 == 0:

print "\nPass %d, Batch %d, Cost %f, %s" % (

event.pass_id, event.batch_id, event.cost, event.metrics)

else:

if isinstance(event, paddle.event.EndPass):

# save parameters

with open('params_pass_%d.tar' % event.pass_id, 'w') as f:

parameters.to_tar(f)

result = trainer.test(

reader=paddle.batch(

feeding={'image': 0,

'label': 1})

print "\nTest with Pass %d, %s" % (event.pass_id, result.metrics)

# Create trainer

trainer = paddle.trainer.SGD(

cost=cost, parameters=parameters, update_equation=momentum_optimizer)

# Save the inference topology to protobuf.

inference_topology = paddle.topology.Topology(layers=out)

with open("inference_topology.pkl", 'wb') as f:

inference_topology.serialize_for_inference(f)

trainer.train(

reader=paddle.batch(

batch_size=128),

num_passes=200,

event_handler=event_handler,

feeding={'image': 0,

'label': 1})

# inference

from PIL import Image

import numpy as np

import os

def load_image(file):

im = Image.open(file)

im = im.resize((32, 32), Image.ANTIALIAS)

im = np.array(im).astype(np.float32)

# The storage order of the loaded image is W(widht),

# H(height), C(channel). PaddlePaddle requires

# the CHW order, so transpose them.

im = im.transpose((2, 0, 1)) # CHW

# In the training phase, the channel order of CIFAR

# image is B(Blue), G(green), R(Red). But PIL open

# image in RGB mode. It must swap the channel order.

im = im[(2, 1, 0), :, :] # BGR

im = im.flatten()

im = im / 255.0

return im

test_data = []

test_data.append((load_image(cur_dir + '/image/dog.png'), ))

# users can remove the comments and change the model name

# with open('params_pass_50.tar', 'r') as f:

# parameters = paddle.parameters.Parameters.from_tar(f)

probs = paddle.infer(

output_layer=out, parameters=parameters, input=test_data)

lab = np.argsort(-probs) # probs and lab are the results of one batch data

print "Label of image/dog.png is: %d" % lab[0][0]

if __name__ == '__main__':

main()

 3.结果输出

I1129 14:52:44.314946 15153 Util.cpp:166] commandline: --use_gpu=True --trainer_count=7

[INFO 2017-11-29 14:52:50,490 layers.py:2539] output for __conv_pool_0___conv: c = 6, h = 28, w = 28, size = 4704

[INFO 2017-11-29 14:52:50,491 layers.py:2667] output for __conv_pool_0___pool: c = 6, h = 14, w = 14, size = 1176

[INFO 2017-11-29 14:52:50,491 layers.py:2539] output for __conv_pool_1___conv: c = 16, h = 10, w = 10, size = 1600

[INFO 2017-11-29 14:52:50,492 layers.py:2667] output for __conv_pool_1___pool: c = 16, h = 5, w = 5, size = 400

[INFO 2017-11-29 14:52:50,493 layers.py:2539] output for __conv_0__: c = 120, h = 5, w = 5, size = 3000

I1129 14:52:50.498749 15153 MultiGradientMachine.cpp:99] numLogicalDevices=1 numThreads=7 numDevices=8

I1129 14:52:50.545882 15153 GradientMachine.cpp:85] Initing parameters..

I1129 14:52:50.651103 15153 GradientMachine.cpp:92] Init parameters done.

Pass 0, Batch 0, Cost 2.331898, {'classification_error_evaluator': 0.9609375}

```

......

Pass 199, Batch 300, Cost 0.004373, {'classification_error_evaluator': 0.0}

..........................................................................................I1129 16:17:08.678097 15153 MultiGradientMachine.cpp:99] numLogicalDevices=1 numThreads=7 numDevices=8

Label of image/dog.png is: 7

同样是7个线程,8个Tesla K80 GPU,batch_size = 128,迭代次数200次,耗时1h25min,错误分类率为0.3957,相比与simple_cnn的0.5248提高了12.91%。当然,这个结果也并不是很好,如果输出详细的日志,可以看到在训练的过程中loss先降后升,说明有一定程度的过拟合,对于如何防止过拟合,我们在后面会详细讲解。

有一个可视化CNN的网站可以对mnist和cifar10分类的网络结构进行可视化,这是cifar-10 BaseCNN的网络结构:

LeNet-5的Tensorflow实现

tensorflow版本LeNet-5版本可以参照:

models/tutorials/image/cifar10/(https://github.com/tensorflow/models/tree/master/tutorials/image/cifar10)的步骤来训练,不过这里面的代码包含了很多数据处理、权重衰减以及正则化的一些方法防止过拟合。按照官方写的,batch_size=128时在Tesla K40上迭代10w次需要4小时,准确率能达到86%。不过如果不对数据做处理,直接跑的话,效果应该没有这么好。不过可以仔细借鉴cifar10_inputs.py里的distorted_inouts函数对数据预处理增大数据集的思想,以及cifar10.py里对于权重和偏置的衰减设置等。目前迭代到1w次左右,cost是0.98,acc是78.4%

对于未进行数据处理的cifar10我准备也跑一次,看看效果如何,与paddle的结果对比一下。不过得等到周末再补上了 = =

总结

本节用常规的cifar-10数据集做图像分类,用了三种实现方式,第一种是自己设计的一个简单的cnn,第二种是LeNet-5,第三种是Tensorflow实现的LeNet-5,对比速度可以见一下表格:

可以看到LeNet-5相比于原始的simple_cnn在准确率和速度方面都有一定的的提升,等tensorflow版本跑完后可以把结果加上去再对比一下。不过用Lenet-5网络结构后,结果虽然有一定的提升,但是还是不够理想,在日志里看到loss的信息基本可以推断出是过拟合,对于神经网络训练过程中出现的过拟合情况我们应该如何避免,下期我们讲着重讲解。此外在下一节将介绍AlexNet,并对分类做一个实验,对比其效果。

参考文献

1.LeNet-5论文:《Gradient-based learning applied to document recognition》

2.可视化CNN:http://shixialiu.com/publications/cnnvis/demo/

  • 发表于:
  • 原文链接:http://kuaibao.qq.com/s/20180108G0JG6100?refer=cp_1026

扫码关注云+社区