卷積神經(jīng)網(wǎng)絡(luò)原理_第1頁
卷積神經(jīng)網(wǎng)絡(luò)原理_第2頁
卷積神經(jīng)網(wǎng)絡(luò)原理_第3頁
卷積神經(jīng)網(wǎng)絡(luò)原理_第4頁
卷積神經(jīng)網(wǎng)絡(luò)原理_第5頁
已閱讀5頁,還剩27頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、一、CNN卷積神經(jīng)網(wǎng)絡(luò)原理簡介本文主要是詳細地解讀CNN的實現(xiàn)代碼。如果你沒學習過CNN , 在此推薦周曉藝師兄的博文:,以及UFLDL上的、CNN的最大特點就是稀疏連接(局部感受)和權(quán)值共享,如下 面兩圖所示,左為稀疏連接,右為權(quán)值共享。稀疏連撕口權(quán)值共 享可以減少所要訓練的參數(shù),減少計算復雜度。至于CNN的結(jié)構(gòu),以經(jīng)典的LeNet5來說明:這個圖真是無處不在,一談CNN ,必說LeNet5 ,這圖來自于 這篇論文:,論文很長,第7頁那里開始講LeNet5這個結(jié)構(gòu), 建議看看那部分。我這里簡單說一下,LeNet5這張圖從左到右,先是input ,這 是輸入層,即輸入的圖片。input-lay

2、er到C1這部分就是一個 卷積原convolution運算),C1至IS2是一個子采樣段pooling 運算),關(guān)于卷積和子采樣的具體過程可以參考下圖:然后,S2到C3又是卷積,C3到S4又是子采樣,可以發(fā)現(xiàn), 卷積和子采樣都是成對出現(xiàn)的,卷積后面一般跟著子采樣。S4 到C5之間是全連接的,這就相當于一個MLP的隱含層了 (如 果你不清楚MLP ,參考)。C5到F6同樣是全連接,也是 相當于一個MLP的隱含層。最后從F6到輸出output ,其實就 是一個分類器,這一層就叫分類層。Ok z CNN的基本結(jié)構(gòu)大概就是這樣,由輸入、卷積層、子采樣 層、全連接層、分類層、輸出這些基本構(gòu)件組成,一般根

3、據(jù) 具體的應用或者問題,去確定要多少卷積層和子采樣層、采用什 么分類器。當確定好了結(jié)構(gòu)以后,如何求解層與層之間的連接參 數(shù)? 一般采用向前傳播(FP ) +向后傳播(BP )的方法來訓練。 具體可參考上面給出的鏈接。二、CNN卷積神經(jīng)網(wǎng)絡(luò)代碼詳細解讀(基于python+theano ) 代碼來自于深度學習教程:,這個代碼實現(xiàn)的是一個簡化了的 LeNet5 ,具體如下: 沒有實現(xiàn) location-specific gain and bias parameters 用的是 maxpooling ,而不是 average_pooling 分類器用的是softmax , LeNet5用的是rbf L

4、eNet5第二層并不是全連接的,本程序?qū)崿F(xiàn)的是全連接 另外,代碼里將卷積層和子采用層合在一起,定義為"LeNetConvPoolLayer "(卷積采樣層),這好理解,因為它 們總是成對出現(xiàn)。但是有個地方需要注意,代碼中將卷積后的輸 出直接作為子采樣層的輸入,而沒有加偏置b再通過sigmoid 函數(shù)進行映射,即沒有了下圖中fx后面的bx以及sigmoid映 射,也即直接由fx得至(J Cxe最后,代碼中第一個卷積層用的卷積核有20個,第二個卷積層 用50個,而不是上面那張LeNet5圖中所示的6個和16個。了解了這些,下面看代碼:(1)導入必要的模塊python1. imp

5、ortcPickle2. importgzip3. importos4. importsys5. importtime6. importnumpy7. importtheano8. importtheano. tensorasT9. . fromimportdownsample10. f romimportconv(2)定義CNN的基本”構(gòu)件“CNN的基本構(gòu)件包括卷積采樣層、隱含層、分類器,如下定義 LeNetConvPoolLayer (卷積+采樣層)見代碼注釋:pythonIt II2.3. 卷積+下采樣合成一個層LeNetConvPoolLayer4.5. rng:隨機數(shù)生成器,用于初始

6、化W6.7. ?8. filter_shape:(numberoffiltersnuminputfeaturemaps?filterheightfilter width)9. image_shape:(batchsize? numinputfeaturemaps imageheightimagewidth)10. poolsize:(#rows#cols)11. 12.13. classLeNetConvPoolLayer(object):14. def_init_(self,rng,input>filter_shapeimage_shape,poolsize=(2J15. 2):16.

7、 #assert?condition , condition 為 True ,則繼續(xù)往下執(zhí)行,condition 為 False r中斷程序17. #image_shapel和 filter_shapel.都是 numinputfeaturemaps,它們必須是一樣的。18. assertimage_shapel=filter_shapel19. self.input=input20. #每個隱層神經(jīng)元(即像素)與上一層的連接數(shù)為numinputfeaturemaps*filterheight*f ilterv/idth021. #可以用 d(filter_shapel:)來

8、求得22.23. fan_in=d(filter_shapel:)24. #lov/erlayer上每個神經(jīng)元獲得的梯度來自于:"numoutputfeaturemaps*filterheight*filterwidth"/poolingsize25 fan_out=(filter_shape0*d(filter_shape26.2:)/27. d(poolsize)28. #以上求得fan_in、fan_out ,將它們代入公式,以此來隨機初始化出W就是線性卷積核29. W_bound=numpy.sqrt(6./(f

9、an_in+fan_out)30. self.W=theano.shared(31. numpy.asarray(32. rng.uniform(lo/=-W_boundJhigh=W_bound)size=filter_shape)33.34. ),35. borrow=True36. )37.38. #thebiasisalDtensor-onebiasperoutputfeaturemap39. #偏置b是一維向量,每個輸出圖的特征圖都對應一個偏置,40.41. #而輸出的特征圖的個數(shù)由filter個數(shù)決定,因此用filter_shape0即numberoffilters 來初始化42.

10、 b_values=numpy.zeros(filter_shape043. self.b=theano.shared(value=b_values?borrow=True)44. #將輸入圖像與filter卷積f conv. conv2d函數(shù)45.46. #卷積完沒有加b再通過sigmoid ,這里是一處簡化。47.48. conv_out=conv.conv2d(49.input=input50 .filters=self.W,51 . filter_shape=filter_shape?52.image_shape=image_shape53. )54.55. #maxpooling ,

11、最大子采樣過程56.57. pooled_out=downsample.max_pool_2d(58.input=conv_out59.ds=poolsize1.1 ignore_border=T rue61. )62.63. #加偏置,再通過tanh映射,得到卷積+子采樣層的最終輸出64.65. #因為b是一維向量 這里用維度轉(zhuǎn)換函數(shù)dimshuffle將其reshape。比如b是(10,),66.67. #則 b.dimshuffleCx1, >xt/xt)M reshape 為(&T。,1,1)68. , self output=T. tanh(pooled_out+sel

12、f. b. dimshuffle(' x',69. 0,70. 'x71. X)72. #卷積+采樣層的參數(shù)73.74. self.params=self.W75.self.b定義隱含層HiddenLayer這個跟上一篇文章中的HiddenLayer是一致的,直接拿過 來:python tt2.3. 注釋:4.5. 這是定義隱藏層的類,首先明確:隱藏層的輸入即input,輸出即隱藏層的神經(jīng)元個數(shù)。 輸入層與隱藏層是全連接的。6.7. .假設(shè)輸入是n_in維的向量(也可以說時n_in個神經(jīng)元),隱藏層有n_out個神經(jīng)元, 則因為是全連接,8.9. 一共有n_in*n_o

13、ut個權(quán)重;故W大小時(n_in> n_out),n_in行n_out列,每一列對 應隱藏層的每一個神經(jīng)元的連接權(quán)重。10.11. b是偏置,隱藏層有n_out個神經(jīng)元,故b時n_out維向量。12.13. ?14. input訓練模型所用到的所有輸入,并不是MLP的輸入層,MLP的輸入層的神經(jīng)元個數(shù) 時n_in .而這里的參數(shù)input大小是(n_example n_in ),每一行一個樣本,即每一 行作為MLP的輸入層。15.16. activation:激活函數(shù),這里定義為函數(shù)tanh17.18. 19.20. classHiddenLayer(object):21. def_in

14、it_(selfrng,input,n_in,n_out>W=None”22. b=None?23. activation=T.tanh):24. self . input=input#類 HiddenLayer 的 input 即所傳遞進來的 input25. 26. 注釋:27. ?28. 另外,W的初始化有個規(guī)則:如果使用tanh函數(shù),則在-sqrt(6./(n_in+n_hidden)到 sqrt(6 . /(n_in+n_hidden)之間均勻29. 抽取數(shù)值來初始化W ,若時sigmoid函數(shù),則以上再乘4倍。30. 31. #如果W未初始化,則根據(jù)上述方法初始化。32. #

15、加入這個判斷的原因是:有時候我們可以用訓練好的參數(shù)來初始化W ,見我的上一篇文章。33. ifWisNone:34. W_values=numpy.asarray(35. rng.uniform(36. .low=-numpy.sqrt(6./(n_in+n_out),37. high=numpy.sqrt(6./(n_in+n_out)38. size=(n_inJn_out)39. ),40.41. )42.43. if44. W_values*=445. W=theano.shared(value=W_values?name='W,46. borrow=True)47. ifbi

16、sNone:48.49. b=theano.shared(value=b_values?name='b',50. borrow=True)51. #用上面定義的W、b來初始化類HiddenLayer的W、b52. self.W=W53. self.b=b54. #隱含層的輸出55. lin_output=T.dot(inputsself.W)+self.b?56.57. self.output=(58. lin_outputifactivationisNone59 . elseactivation(lin_output)60 .)61 .62 . #隱含層的參數(shù)63 .self

17、.params=self.W,64 .self.b定義分類器(Softmax回歸)采用Softmax ,這跟中的LogisticRegression是一樣的, 直接拿過來: python ” II2.3. 定義分類層 LogisticRegression r 也即 Softmax 回歸 4.5. . 在 deeplearning?tutorial 中,直接將 LogisticRegression 視為 Softmax ,6. 而我們所認識的二類別的邏輯回歸就是當n_out=2時的LogisticRegression 7.8. 9.10. #參數(shù)說明:11.12. #input ,大小就是(n_

18、example,n_in) r 其中 n_example 是一個 batch 的大小, 13.14. #因為我們訓練時用的是Minibatch?SGD ,因此input這樣定義15. #n_in)即上一層(隱含層)的輸出16.17. #n_out,輸出的類別數(shù)?18. classLogisticRegression(object):19. def_init_(selfinputn_in)n_out):20. #W大小是n_in行n_out列,b為n_out維向量。即:每個輸出對應W的一列以及b的一個元素。21. self.W=theano.shared(22. value=numpy.zero

19、s(23. (n_in,n_out)24.25. ),26. name=,W,27. borrow=True28. )29.30. self.b=theano.shared(31. value=numpy.zeros(32,(n-outj,33.34. ),35. name=*b'>36. borrow=True37. )38.39. #input 是(n_example»n_in),討是(n_in?n_out ) )點乘得到(n_example>n_out),加上偏置b .40.41.42. #故p)_given_x每一行代表每一個樣本被估計為各類別的概率?43

20、. #PS : b是n_out維向星,與(仁3叩12#_0a)矩陣相加,內(nèi)部其實是先復制n_example 個 b , 44.45. #然后(n_example,n_out)矩陣的每一行都加b46.47.selfself.W)+self.b)48. #argmax返回最大值下標,因為本例關(guān)集是MNIST ,下標剛好就是類別。axis=l表示按行操作。49.50. self ,y_pred=T.argmax(self. p_y_given_x>51. axis=l)52. #params , LogisticRegression 的參數(shù)?53. self.params=self.W, 54

21、. self.b到這里,CNN的基本構(gòu)件都有了 ,下面要用這些構(gòu)件組 裝成LeNet5 (當然,是簡化的,上面已經(jīng)說了),具體來說, 就是組裝成:LeNet5 = inputs LeNetConvPoolLayer_l+LeNetConvPoolLa yer_2 + HiddenLayer+LogisticRegression + outputo然后將其應用于MNIST數(shù)據(jù)集,用BP算法去解這個模型,得 到最優(yōu)的參數(shù)。(3)加載MNIST數(shù)據(jù)集()python ” “ 2.3. 加載MN工ST數(shù)據(jù)集load_data()4.5. 6.7. defload_data(dataset):8. #9

22、. dataset是數(shù)據(jù)集的路徑,程序首先檢測該路徑下有沒有工ST數(shù)據(jù)集,沒有的話就下 載MN工ST數(shù)據(jù)集10. #這一部分就不解釋了,與softmax回歸算法無關(guān)。11.12. ifdata_dir="Mandnot13. #Checkifdatasetisinthedatadirectory.14.15.0,16.17. ”二18. "data",19. dataset20. )21.22. ifordata file=:23. dataset=new_path24. if (notanddata_file=:25. importurllib26.origin

23、=(27.28. )29.30. print'Downloadingdatafrom%s'%origin31. urllib.urlretrieve(origin?dataset)32. . print" . loadingdata'33.34.35. #主要用到 python 里的 gzip.open()函數(shù),以及?cPickle.load()036. #,rb,衣示以二進制可談的方式打開文件37.38. f=gzip.open(dataset,'rb')39. train_set>valid_settest_set=cPickle.l

24、oad(f)40. f .close()41. #將數(shù)據(jù)設(shè)置成sharedvariablest主要時為了 GPU加速,只有sharedvariables才 能存到GPUmemory中42. #GPU里數(shù)據(jù)類型只能是float。而(12七2_7是類別,所以最后又轉(zhuǎn)換為int返回43.44. def shared_dataset(data_xyJ borrow=True):45. data-x data_y=data_xy46. shared_x=theano.shared(numpy.asarrayCdata-x47.48. borrow=borrow)49. shared_y=theano.s

25、hared(numpy.asarray(data_y,50.51. borrow=borrow)52. returnshared_x,T.cast(shared_y'int32")53. , test_set_xJtest_set_y=shared_dataset(test_set)54. valid-set-x,valid_set_y=shared_dataset(valid_set)55. . train_set_xtrain_set_y=shared_dataset(train_set)56. rval=(train_set-xtrain_set_y),(valid_s

26、et_x,valid_set_y)57. (test_set_x,test_set_y)58. returnrval(4 )實現(xiàn)LeNet5并測試python1. ” fl2.3. 實現(xiàn) LeNet54.5. LeNet5有兩個卷積層,第一個卷積層有20個卷積核,第二個卷積層有50個卷積核. defevaluate_lenet5(learning_rate=0.1,10. n_epochs=20011. dataset,12. nkerns=20>13. 50,14. batch_size=500):15. 16.17. 工earning/ate:學習速率,隨機梯度前的系數(shù)

27、。18. n_epochs訓練步數(shù),每一步都會遍歷所有batch ,即所有樣本19. batch_size,這里設(shè)置為500 ,即每遍歷完500個樣本,才計算悌度并更新參數(shù)20. nkerns=20) 50»每一個 LeNetConvPoolLayer 卷積核的個數(shù),第一個LeNetConvPoolLayer 有21. 20個卷積核,第二個有50個22. ” ” “23. 23455)24.25. #加載數(shù)據(jù)26. datasets=load_data(dataset)27. train_set_x,train_set_y=datasets028. valid_set_x,valid

28、_set_y=datasets129. test_set_xJtest_set_y=datasets230. #31. .計算bat ch的個數(shù)32. n_train_batches=train_set_x.get_value(borrov/=True).shape033. n_valid_batches=valid_set_x.get_value(borrov/=True).shape034. n_test_batches=test_set_x.get_value(borrow=True).shape035. n_train_batches/=batch_size36. n-valid_ba

29、tches/=batch_size37. n_test_batches/=batch_size,y對應其標簽38. #定義幾個變量,index表示batch下標,x表示輸入的訓練類1.1 index=T.lscalar()40. x=T.matrix('x')41. y=T.ivector('y')42. #43. #BUILDACTUALMODEL#44. #45. . print'.buildingthemodel46. #我們加載進來的batch大小的登是(batch_size,28*28)"旦是LeNetConvPoolLayer的輸入

30、是四維的,所以要reshape47. layer0_input=x.reshape(batch-size,1,48. 28,49. 28)50. #layer0 即第一個 LeNetConvPoolLayer 層51. #輸入的單張圖片(28,28),經(jīng)過 conv 得到(28-5+1,28-5+1) = (24,24),52. #經(jīng)過 maxpooling 得到(24/2,24/2) = (:12jl2)53. #因為每個 batch 有 batch-size 張圖,第一個 LeNetConvPoolLayer 層有 nkerns0個卷積核,54.55. #故 layer© 輸出為

31、(batch_size,nkerns0jl2,T2)1.1 layer0=LeNetConvPoolLayer(57. rng,58. input=layer0_input>59. image_shape=(batch_sizeJ1?60. 28,61. 28),62. filter_shape=(nkerns063. 1,64. 5,65.5),66. poolsize=(2,67. 2)68. )69.70. #layerl 即第二個 LeNetConvPoolLayer 層71.72. #輸入是layer©的輸出,每張?zhí)卣鲌D為(12,12),經(jīng)過conv得到(12-5+1

32、,12-5+1)=(8.8),73. #經(jīng)過 maxpooling 得到(8/2,8/2) = (4,4)74. #因為每個batch有batch_size張圖(特征圖),第二個LeNetConvPoolLayer層有nkernsl個卷積核75.76. # ,故 layerl 輸出為(batch_size,nkernsl>4,4)77.layerl=LeNetConvPoolLayer(78. rng,79.input=layer0.output,80, image_shape=(batch_sizeJnkerns0,81, 12,82. 12),#輸入nkerns0張?zhí)卣鲌D,即laye

33、r©輸出nkerns0張?zhí)卣鲌D83. filter_shape=(nkernsl,84. nkerns0?85. 5,86. 5),87. poolsize=(2J88. 2)89. )90.91. #前面定義好了兩個 LeNetConvPoolLayer( layer© 和 layerl ) Jayerl 后面接 layer2 ,這是一個全連接層,相當于MLP里面的隱含層92.93. #故可以用MLP中定義的HiddenLayer來初始化layer2 , layer2的輸入是二維的(batch_size,num_pixels),94. #故要將上層中同一張圖經(jīng)不同卷積核卷

34、積出來的特征圖合并為一維向量,95.96. #也就是將 layerl 的輸出(batch_sizenkernsflatten 為(batch_sizeJnkernsl*4*4) = (500 . 800),作為 layer2 的愉入。97. #(500 , 800)表示有500個樣本,每一行代表一個樣本。layer2的輸出大小是(batch_size n_out) = (50。,500)98.99. 2)100.101. layer2=HiddenLayer(102. rng,103. input=layer2_input?104. n_in=nkernsl*4*4J105. n out=50

35、0.106. activation=T.tanh107. )108.109. #最后一層layer3是分類層,用的是邏輯回歸中定義的LogisticRegression ,110.111. #laye3的輸入是layers的輸出(500,50。),layer3的輸出就是(batch_sizen_out) = (500?10)112.113. layer3=LogisticRegression(input=layer2.output,n_in=500?114. n_out=10)115. #代價函數(shù)NLL116.117. cost=layer3.negative_log_likelihood(y

36、)118. #test_model計算測試誤差f x、y根據(jù)給定的index具體化,然后調(diào)用layer3 r119. #layer3又會逐層地調(diào)用layer2s layerl、layer© r故test_model其實就是整個CNN結(jié)構(gòu),120.121. #test_model的輸入是x、y ,輸出是laye3.errors(y)的輸出,即誤差。122.123. test_model=theano.function(124. index125. Iayer3.errors(y),126. givens=127. x:test_set_xindex*bateh_size:(index+

37、l)*batch_size128. y:test_set_yindex*batch_size:(index+l)*batch_size129. 130.131. .)132.133. #validate_model ,瞼證模型r分析同上。134.135. validate_model=theano.function(136. index137. Iayer3.errors(y),138. givens=139. . x:valid_set_xindex*batch_size:(index+l)*batch_size140. y:valid_set_yindex*batch_size:(inde

38、x+1)*batch_size141. 142.143 )144.145. #下面是train_model ,涉及到優(yōu)化算法即SGD ,需要討算梯度、更新參數(shù)146.147. #參雌148. . params=layer3.params+layer2.params+layerl.params+layer0.params149. #對各個參數(shù)的梯度150. grads=T.grad(cost?params)151. #因為參數(shù)太多,在updates規(guī)則里面一個一個具體地寫出來是很麻煩的,所以下面用了一個 for. .in. ?自動生成規(guī)則對(param_ijparam_i-learning_pa

39、te*grad_i)152. updates=153 ,(param_i,param_i-learning_rate*grad_i)154. forparam_i?grad_iinzip(paramsgrads)155. 156.157. #train_model ,代碼分析同 tesjmodel。trainjnodel 里比 test_model、validation_model 多出 updates 規(guī)則#.159. train_model=theano.function(160. index161. cost,162. updates=updates>163. givens=164

40、. x:train_set_xindex*batch_size:(index+l)*batch_size165. y:train_set_yindex*batch_size:(index+l)*batch_size166. 167.168. )169.170. #171. #開始|練#172. #173. print,.174. training'175. patience=10000176. patience_increase=2177. improvement_threshold=0.995178. validation_frequency=min(n_train_batches,

41、patience/2)179. #這樣設(shè)置validation_frequency可以保證每一次epoch都會在驗證集上測試。180. best_validation_loss=numpy.inf#最好的瞼證集上的loss ,最好即最小181. best_iter=0182. #最好的迭代次數(shù),以batch為單位。比如besOter=10000,說明在訓練完第100。個 batch 時,達到 best_validation_loss183. test_score=0.184. start_time=time.clock()185. epoch=0186. done_looping=False1

42、87. #下面就是訓練過程了,while循環(huán)控制的時步數(shù)epoch ,一個epoch會遍歷所有的batch ,即所有的圖片。188.189. #for循環(huán)是遍歷一個個batch ,一次一個batch地訓練。for循環(huán)體里會用train_model(minibatch_index)去訓練模型,#.191. #train_model里面的updates會更新各個參數(shù)。192.193. #for循環(huán)里面會累加訓練過的batch數(shù)iter ,當iter是validation_f requency倍數(shù)時則會在驗證集上測試,194.195. #如果驗證集的損失this_validation_loss小于之

43、前最佳的損失best_validation_loss ,196.197. #則更新 best_validation_loss 和 best_iter ,同時在 testset 上測試。198.199. #如果驗證集的損失this_validation_loss小于best_validation_loss*improvement-threshold 時則更新 patienceo200.201. #當達到最大步數(shù)n_epoch時,或者patience<iter時;結(jié)束訓練202.203. while(epoch<n_epochs) and(notdone_looping):204. e

44、poch=epoch+l205. . forminibatch_indexinxrange(n_train_batches):206. iter=(epoch-l)*n_train_batches+minibatch_index207. ifiter%100=0:208. printf trainingiter=", iter209. . cost_ij=train_model(minibatch_index)210. 沒什么用,后面都沒有用到)只是為了調(diào)用train_model,而train_model有返回值211. if(iter+l)%validation_frequency

45、=0:212. #computezero-onelossonvalidationset213. validation_losses=validate_model(i)fori214. inxrange(n_valid_batches)215. . this_validation_loss=numpy.mean(validation_losses)216. . print('epoch%iminibatch%i/%iJvalidationerror%f%,%217. ,(epochs minibat ch_index+lnrain-batches218. this_validation_

46、loss*100.)219. . ifthis_validation_loss<best_validation_loss:220. ifthis_validation_loss<best_validation_loss*221. improvement_threshold:222. . patience=max(patience,iter*patience_increase)223. . best_validation_loss=this_validation_loss224. best_iter=iter225. test_losses=226. test_model(i)227

47、. foriinxrange(n_test_batches)228. 229.230 test_score=numpy.mean(test_losses)231 . print('epoch%iJminibatch%i/%i>testerrorof'232.'bestmodel%f%,)%233 ,(epochs minibatch-index+lnrain-batches234. test_score*100.)235. ifpatience<=iter:236. done_looping=True237. break238 end_time=time.c

48、lock()239. print( "Optimization?complete.')240.241. print(,Bestvalidationscoreof%f%obtainedatiteration%i>'242. 'withtestperformance%f%,%243,(best_validation_loss*100.?best_iter+ltest_score*100.)244. print>>sys.stderr>('Thecodeforfile'+245. 1+246. 'ranfor%.2fm

49、'%(end_time-start_time)/247. 60.)Convolutional Neural Networks (LeNet)The Convolution OperatorConvOp is the main workhorse for implementing a convolutional layer inTheano. ConvOp is used by, which takes two symbolic inputs: a 4D tensor corresponding to a mini-batch of input images. Theshape of t

50、he tensor is as follows: mini-batch size, number of input feature maps, image height, image width. a 4D tensor corresponding to the weight matrix。二 The shape of the tensor is: number of feature maps at layer m, number of feature maps at layer m-1, filter height, filter widthBelow is the Theano code

51、for implementing a convolutional layer similar to the one of Figure 1. The input consists of 3 features maps (an RGB color image) of size 120x160. We use two convolutional filters with 9x9 receptive fields.import theanofrom theano import tensor as T from import conv2d import numpyrng = numpy.random.

52、RandomState(23455) # instantiate 4D tensor for input input = T.tensor4(name='input1) # initiaLize shared variabLe for weights . w_shp = (2, 3, 9, 9) w_bound = numpy.sqrt(3 *9*9) W = theano.shared( numpy.asarray( rng.uniform(low=-l.0 / w_bound? high=l.0 / w_bound? size=w_shp) dtype=input. dtype)

53、? name =")# initiaLize shared variabLe for bias (ID tensor) with random vaLues # IMPORTANT: biases are usuaLLy initialized to zero. However in this # particuLar appLicationJ ive simpLy appLy the convoLutionaL Layer to# an image without Learning the parameters. We therefore initiaLize # them to

54、random vaLues to HsimuLateH Learning. b_shp = (2,) b = theano.shared(numpy.asarray(rng . uniform(low=一.5, high=.5, size二b_shp)dtype=input.dtype)name ='b')# buiLd symboLic expression that computes the convoLution of input with fitters in wconv_out = conv2d(input) W)# buiLd symboLic expression

55、 to add bias and appLy activation functionj i.e. produce neuraL net Layer output# # # # # # # # # # # # # # # # # #few words ondimshuffLe:''dimshuffLeis a powerful tooL in reshaping a tensor;what it allots you to do is to shuffle dimension around but atso to insert new ones aLong which the t

56、ensor iiLL be broadcastabLe;dimshuff Le( 'x '2'x'1)This LI work on 3d tensors with no broadcastabLe dimensions. The first dimension wit I be broadcastabLej then we will have the third dimension of the input tensor as the second of the resuLting tensorj etc. If the tensor has shape (20j 3。/40), the resuLting tensor will have dimensions (lj 40, 1J 20/30). (AxBxC tensor is mapped to IxCxlxA

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論