生活随笔
收集整理的這篇文章主要介紹了
DeepLearning:手动编辑python实现卷积操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目前的深度學習框架真正去實現卷積的時候,使用的是矩陣乘法的方式,使用im2col操作將輸入數據與權重展開成二維矩陣,然后直接做矩陣乘法, 缺點是占用許多內存。具體原理看下面這張圖就能明白:
圖片的上面三行是傳統的卷積實現,也就是我文章下面代碼的實現過程。
最下面的一行是目前框架中普遍使用的實現方式,可以看到它通過把輸入特征轉換為一個大矩陣,把卷積核也轉換為一個大矩陣,數據量經過復制后確實增加了很多,但是計算操作卻簡單了很多。
卷積代碼實現:
import time
import matplotlib
.pyplot
as plt
import pylab
import numpy
as np
def convolve(SourceImg
, Kernel
):""":param SourceImg::param Kernel::return:# 分成三個通道# 1.三通道數據分離# 2.三通道數據單獨卷積操作# 3.卷積結果合并"""h
= fil
.shape
[0] // 2 w
= fil
.shape
[1] // 2 img
= np
.pad
(SourceImg
, ((h
, h
), (w
, w
), (0, 0)), 'constant')conv_b
= ConvolveOperation
(img
[:, :, 0], Kernel
)conv_g
= ConvolveOperation
(img
[:, :, 1], Kernel
)conv_r
= ConvolveOperation
(img
[:, :, 2], Kernel
)composite_channel
= np
.dstack
([conv_b
, conv_g
, conv_r
]) return composite_channel
def ConvolveOperation(source_img
, kernel
):""":param source_img::param kernel::return:"""kernel_h
= kernel
.shape
[0]kernel_w
= kernel
.shape
[1]conver_result_h
= source_img
.shape
[0] - kernel_h
+ 1 conver_result_w
= source_img
.shape
[1] - kernel_w
+ 1conver_result
= np
.zeros
((conver_result_h
,conver_result_w
), dtype
='uint8')for i
in range(conver_result_h
):for j
in range(conver_result_w
):conver_result
[i
][j
] = Caculate
(source_img
[i
:i
+kernel_h
, j
:j
+kernel_w
],kernel
) return conver_result
def Caculate(img0
, kernel
):""":param img0::param kernel::return:"""res0
= (img0
* kernel
).sum()if res0
< 0:res0
= 0elif res0
> 255:res0
= 255return res0img
= plt
.imread
("001.jpg")
plt
.imshow
(img
)
pylab
.show
()fil
= np
.array
([[-1, -1, -1, 0, 1],[-1, -1, 0, 1, 1],[-1, 0, 1, 1, 1]])start
= time
.localtime
()
print(time
.strftime
("%Y-%m-%d %H:%M:%S", time
.localtime
()))res
= convolve
(img
, fil
)end
= time
.localtime
()
print(time
.strftime
("%Y-%m-%d %H:%M:%S", time
.localtime
()))plt
.imshow
(res
)
pylab
.show
()
總結
以上是生活随笔為你收集整理的DeepLearning:手动编辑python实现卷积操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。