本文结合Deep learning的一个应用,Convolution Neural Network 进行一些基本应用,参考Lecun的Document 0.1进行部分拓展,与结果展示(in python)。

分为以下几部分:

1. Convolution(卷积)

2. Pooling(降采样过程)

3. CNN结构

4.  跑实验

下面分别介绍。

PS:本篇blog为ese机器学习短期班参考资料(20140516课程),本文只是简要讲最naive最simple的思想,重在实践部分,原理课上详述。

1. Convolution(卷积)

类似于高斯卷积,对imagebatch中的所有image进行卷积。对于一张图,其所有feature map用一个filter卷成一张feature map。 如下面的代码,对一个imagebatch(含两张图)进行操作,每个图初始有3张feature map(R,G,B), 用两个9*9的filter进行卷积,结果是,每张图得到两个feature map。

卷积操作由theano的conv.conv2d实现,这里我们用随机参数W,b。结果有点像edge detector是不是?

Code: (详见注释)

[python] view plain copy  
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat May 10 18:55:26 2014
  4. @author: rachel
  5. Function: convolution option of two pictures with same size (width,height)
  6. input: 3 feature maps (3 channels <RGB> of a picture)
  7. convolution: two 9*9 convolutional filters
  8. """
  9. from theano.tensor.nnet import conv
  10. import theano.tensor as T
  11. import numpy, theano
  12. rng = numpy.random.RandomState(23455)
  13. # symbol variable
  14. input = T.tensor4(name = 'input')
  15. # initial weights
  16. w_shape = (2,3,9,9) #2 convolutional filters, 3 channels, filter shape: 9*9
  17. w_bound = numpy.sqrt(3*9*9)
  18. W = theano.shared(numpy.asarray(rng.uniform(low = -1.0/w_bound, high = 1.0/w_bound,size = w_shape),
  19. dtype = input.dtype),name = 'W')
  20. b_shape = (2,)
  21. b = theano.shared(numpy.asarray(rng.uniform(low = -.5, high = .5, size = b_shape),
  22. dtype = input.dtype),name = 'b')
  23. conv_out = conv.conv2d(input,W)
  24. #T.TensorVariable.dimshuffle() can reshape or broadcast (add dimension)
  25. #dimshuffle(self,*pattern)
  26. # >>>b1 = b.dimshuffle('x',0,'x','x')
  27. # >>>b1.shape.eval()
  28. # array([1,2,1,1])
  29. output = T.nnet.sigmoid(conv_out + b.dimshuffle('x',0,'x','x'))
  30. f = theano.function([input],output)
  31. # demo
  32. import pylab
  33. from PIL import Image
  34. #minibatch_img = T.tensor4(name = 'minibatch_img')
  35. #-------------img1---------------
  36. img1 = Image.open(open('//home//rachel//Documents//ZJU_Projects//DL//Dataset//rachel.jpg'))
  37. width1,height1 = img1.size
  38. img1 = numpy.asarray(img1, dtype = 'float32')/256. # (height, width, 3)
  39. # put image in 4D tensor of shape (1,3,height,width)
  40. img1_rgb = img1.swapaxes(0,2).swapaxes(1,2).reshape(1,3,height1,width1) #(3,height,width)
  41. #-------------img2---------------
  42. img2 = Image.open(open('//home//rachel//Documents//ZJU_Projects//DL//Dataset//rachel1.jpg'))
  43. width2,height2 = img2.size
  44. img2 = numpy.asarray(img2,dtype = 'float32')/256.
  45. img2_rgb = img2.swapaxes(0,2).swapaxes(1,2).reshape(1,3,height2,width2) #(3,height,width)
  46. #minibatch_img = T.join(0,img1_rgb,img2_rgb)
  47. minibatch_img = numpy.concatenate((img1_rgb,img2_rgb),axis = 0)
  48. filtered_img = f(minibatch_img)
  49. # plot original image and two convoluted results
  50. pylab.subplot(2,3,1);pylab.axis('off');
  51. pylab.imshow(img1)
  52. pylab.subplot(2,3,4);pylab.axis('off');
  53. pylab.imshow(img2)
  54. pylab.gray()
  55. pylab.subplot(2,3,2); pylab.axis("off")
  56. pylab.imshow(filtered_img[0,0,:,:]) #0:minibatch_index; 0:1-st filter
  57. pylab.subplot(2,3,3); pylab.axis("off")
  58. pylab.imshow(filtered_img[0,1,:,:]) #0:minibatch_index; 1:1-st filter
  59. pylab.subplot(2,3,5); pylab.axis("off")
  60. pylab.imshow(filtered_img[1,0,:,:]) #0:minibatch_index; 0:1-st filter
  61. pylab.subplot(2,3,6); pylab.axis("off")
  62. pylab.imshow(filtered_img[1,1,:,:]) #0:minibatch_index; 1:1-st filter
  63. pylab.show()

2. Pooling(降采样过程)

最常用的Maxpooling. 解决了两个问题:

1. 减少计算量

2. 旋转不变性 (原因自己悟)

PS:对于旋转不变性,回忆下SIFT,LBP:采用主方向;HOG:选择不同方向的模版

Maxpooling的降采样过程会将feature map的长宽各减半。(下面结果图中没有体现出来,python自动给拉到一样大了,但实际上像素数是减半的)

Code: (详见注释)

[python] view plain copy  
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat May 10 18:55:26 2014
  4. @author: rachel
  5. Function: convolution option
  6. input: 3 feature maps (3 channels <RGB> of a picture)
  7. convolution: two 9*9 convolutional filters
  8. """
  9. from theano.tensor.nnet import conv
  10. import theano.tensor as T
  11. import numpy, theano
  12. rng = numpy.random.RandomState(23455)
  13. # symbol variable
  14. input = T.tensor4(name = 'input')
  15. # initial weights
  16. w_shape = (2,3,9,9) #2 convolutional filters, 3 channels, filter shape: 9*9
  17. w_bound = numpy.sqrt(3*9*9)
  18. W = theano.shared(numpy.asarray(rng.uniform(low = -1.0/w_bound, high = 1.0/w_bound,size = w_shape),
  19. dtype = input.dtype),name = 'W')
  20. b_shape = (2,)
  21. b = theano.shared(numpy.asarray(rng.uniform(low = -.5, high = .5, size = b_shape),
  22. dtype = input.dtype),name = 'b')
  23. conv_out = conv.conv2d(input,W)
  24. #T.TensorVariable.dimshuffle() can reshape or broadcast (add dimension)
  25. #dimshuffle(self,*pattern)
  26. # >>>b1 = b.dimshuffle('x',0,'x','x')
  27. # >>>b1.shape.eval()
  28. # array([1,2,1,1])
  29. output = T.nnet.sigmoid(conv_out + b.dimshuffle('x',0,'x','x'))
  30. f = theano.function([input],output)
  31. # demo
  32. import pylab
  33. from PIL import Image
  34. from matplotlib.pyplot import *
  35. #open random image
  36. img = Image.open(open('//home//rachel//Documents//ZJU_Projects//DL//Dataset//rachel.jpg'))
  37. width,height = img.size
  38. img = numpy.asarray(img, dtype = 'float32')/256. # (height, width, 3)
  39. # put image in 4D tensor of shape (1,3,height,width)
  40. img_rgb = img.swapaxes(0,2).swapaxes(1,2) #(3,height,width)
  41. minibatch_img = img_rgb.reshape(1,3,height,width)
  42. filtered_img = f(minibatch_img)
  43. # plot original image and two convoluted results
  44. pylab.figure(1)
  45. pylab.subplot(1,3,1);pylab.axis('off');
  46. pylab.imshow(img)
  47. title('origin image')
  48. pylab.gray()
  49. pylab.subplot(2,3,2); pylab.axis("off")
  50. pylab.imshow(filtered_img[0,0,:,:]) #0:minibatch_index; 0:1-st filter
  51. title('convolution 1')
  52. pylab.subplot(2,3,3); pylab.axis("off")
  53. pylab.imshow(filtered_img[0,1,:,:]) #0:minibatch_index; 1:1-st filter
  54. title('convolution 2')
  55. #pylab.show()
  56. # maxpooling
  57. from theano.tensor.signal import downsample
  58. input = T.tensor4('input')
  59. maxpool_shape = (2,2)
  60. pooled_img = downsample.max_pool_2d(input,maxpool_shape,ignore_border = False)
  61. maxpool = theano.function(inputs = [input],
  62. outputs = [pooled_img])
  63. pooled_res = numpy.squeeze(maxpool(filtered_img))
  64. #pylab.figure(2)
  65. pylab.subplot(235);pylab.axis('off');
  66. pylab.imshow(pooled_res[0,:,:])
  67. title('down sampled 1')
  68. pylab.subplot(236);pylab.axis('off');
  69. pylab.imshow(pooled_res[1,:,:])
  70. title('down sampled 2')
  71. pylab.show()

3. CNN结构

想必大家随便google下CNN的图都滥大街了,这里拖出来那时候学CNN的时候一张图,自认为陪上讲解的话画得还易懂(<!--囧-->)

废话不多说了,直接上Lenet结构图:(从下往上顺着箭头看,最下面为底层original input)

4. CNN代码

去资源里下载吧,我放上去了喔~(in python)
这里贴少部分代码,仅表示建模的NN:

[python] view plain copy  
  1. rng = numpy.random.RandomState(23455)
  2. # transfrom x from (batchsize, 28*28) to (batchsize,feature,28,28))
  3. # I_shape = (28,28),F_shape = (5,5),
  4. N_filters_0 = 20
  5. D_features_0= 1
  6. layer0_input = x.reshape((batch_size,D_features_0,28,28))
  7. layer0 = LeNetConvPoolLayer(rng, input = layer0_input, filter_shape = (N_filters_0,D_features_0,5,5),
  8. image_shape = (batch_size,1,28,28))
  9. #layer0.output: (batch_size, N_filters_0, (28-5+1)/2, (28-5+1)/2) -> 20*20*12*12
  10. N_filters_1 = 50
  11. D_features_1 = N_filters_0
  12. layer1 = LeNetConvPoolLayer(rng,input = layer0.output, filter_shape = (N_filters_1,D_features_1,5,5),
  13. image_shape = (batch_size,N_filters_0,12,12))
  14. # layer1.output: (20,50,4,4)
  15. layer2_input = layer1.output.flatten(2) # (20,50,4,4)->(20,(50*4*4))
  16. layer2 = HiddenLayer(rng,layer2_input,n_in = 50*4*4,n_out = 500, activation = T.tanh)
  17. layer3 = LogisticRegression(input = layer2.output, n_in = 500, n_out = 10)

layer0, layer1 :分别是卷积+降采样

layer2+layer3:组成一个MLP(ANN)

训练模型:

[python] view plain copy  
  1. cost = layer3.negative_log_likelihood(y)
  2. params = layer3.params + layer2.params + layer1.params + layer0.params
  3. gparams = T.grad(cost,params)
  4. updates = []
  5. for par,gpar in zip(params,gparams):
  6. updates.append((par, par - learning_rate * gpar))
  7. train_model = theano.function(inputs = [minibatch_index],
  8. outputs = [cost],
  9. updates = updates,
  10. givens = {x: train_set_x[minibatch_index * batch_size : (minibatch_index+1) * batch_size],
  11. y: train_set_y[minibatch_index * batch_size : (minibatch_index+1) * batch_size]})

根据cost(最上层MLP的输出NLL),对所有层的parameters进行训练

剩下的具体见代码和注释。

PS:数据为MNIST所有数据

final result:
Optimization complete. Best validation score of 0.990000 % obtained at iteration 122500, with test performance 0.950000 %
from: http://blog.csdn.net/abcjennifer/article/details/25912675

卷积神经网络Convolution Neural Network (CNN) 原理与实现相关推荐

  1. 卷积神经网络(Convolutional Neural Network, CNN)

    卷积神经网络(Convolutional Neural Network, CNN) 目录 卷积神经网络(Convolutional Neural Network, CNN) 概述: 结构: 卷积层:

  2. 卷积神经网络Convolutional Neural Network (CNN)

    卷积神经网络 转载请注明:http://blog.csdn.net/stdcoutzyx/article/details/41596663 自今年七月份以来,一直在实验室负责卷积神经网络(Convol ...

  3. 机器学习 卷积神经网络 Convolutional Neural Network(CNN)

    Convolutional Neural Network(CNN)- 卷积神经网络 CNN专用在影像上的神经网络,目的是作影像辨识.影像分类,即通过输入的影像,输出影像中的内容. 对于CNN,有两种解 ...

  4. 【面向代码】学习 Deep Learning Convolution Neural Network(CNN)

    转载自: [面向代码]学习 Deep Learning(三)Convolution Neural Network(CNN) - DarkScope从这里开始 - 博客频道 - CSDN.NET htt ...

  5. 深度学习之卷积神经网络(Convolutional Neural Networks, CNN)(二)

    前面我们说了CNN的一般层次结构, 每个层的作用及其参数的优缺点等内容.深度学习之卷积神经网络(Convolutional Neural Networks, CNN)_fenglepeng的博客-CS ...

  6. 深度学习之卷积神经网络(Convolutional Neural Networks, CNN)

    前面, 介绍了DNN及其参数求解的方法(深度学习之 BP 算法),我们知道DNN仍然存在很多的问题,其中最主要的就是BP求解可能造成的梯度消失和梯度爆炸.那么,人们又是怎么解决这个问题的呢?本节的卷积 ...

  7. 深度学习(Deep Learning)——卷积神经网络 (Convolutional Neural Networks / CNN)

    一.卷积神经网络的概述 1.卷积神经网络与普通神经网络非常相似,它们都由具有可学习的权重w和偏置常量(biases)的神经元组成.每个神经元都接收一些输入,并做一些点积计算,输出是每个分类的分数,普通 ...

  8. 卷积神经网络, Convolutional Neural Networks , CNN

    1,简介 CNN是deep learning在图像处理领域的一个应用 由具有可学习的权重和偏置常量(biases)的神经元组成,是deeplearning在图像处理的一个应用 2,卷积层(Convol ...

  9. 2021李宏毅 机器学习 Convolutional Neural Network (CNN)

    应用1:影像辨识 一张图片是一个三维的Tensor,一维是长,一维是宽,一维是channel (channel=3代表RGB的三种颜色,长和宽代表解析度,像素的数目) 模型的弹性越大,越容易过拟合. ...

最新文章

  1. OpenCV C++ 10 - Invert Images
  2. 【信息系统项目管理师】常用网络标准与网络协议
  3. OCS (错误代码: 0-1-492)
  4. 2019年ICPC银川区域赛 Easy Problem(简单莫比乌斯函数 + 欧拉降幂)
  5. mysql 集群怎么卸载节点_Greenplum移除节点
  6. 华为慧通值不值得去_华为 Mate 40太难抢,上半年的P40Pro还香吗?
  7. jq中使用promise封装ajax
  8. Java编程思想第四版——第十五天
  9. YARN调试过程中的常见问题
  10. 如何做项目竞标的PPT?
  11. 计算机组成原理课程设计
  12. 指数函数及其性质教学设计
  13. C# Udp测试工具开发
  14. 如何选择注塑机动力系统
  15. 赠人玫瑰,手有余香, 下面请听仙居义工专题报道
  16. Up in the Air-16
  17. 线性代数---(2)n维向量组
  18. 共享 || 19份2020关于直播的报告
  19. SQL语法之PRIMARY KEY 约束
  20. Arduino案例实操 -- 智能巡防小车(四)火焰检测功能扩展

热门文章

  1. word2vec如何得到词向量
  2. 第14章 用BERT实现中文语句分类
  3. 使用keras的cifar10.load_data()总是会自动下载问题的解决
  4. 专访平安科技首席科学家肖京:平安智能化的甜蜜与辛酸
  5. 蚂蚁金服张洁:基于深度学习的支付宝人脸识别技术解秘-1
  6. matlab绘制三维图形现状,MATLAB绘制三维图形
  7. Apache ZooKeeper - Leader 选举 如何保证分布式数据的一致性
  8. 并发编程-08安全发布对象之发布与逸出
  9. android收费知乎,知乎 Android 端的一次重设计练习
  10. python的目的及应用_python Django中的apps.py的目的是什么_python_脚本之家