日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

DeepLearning:手动编辑python实现卷积操作

發布時間:2025/3/20 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 DeepLearning:手动编辑python实现卷积操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

目前的深度學習框架真正去實現卷積的時候,使用的是矩陣乘法的方式,使用im2col操作將輸入數據與權重展開成二維矩陣,然后直接做矩陣乘法, 缺點是占用許多內存。具體原理看下面這張圖就能明白:

圖片的上面三行是傳統的卷積實現,也就是我文章下面代碼的實現過程。
最下面的一行是目前框架中普遍使用的實現方式,可以看到它通過把輸入特征轉換為一個大矩陣,把卷積核也轉換為一個大矩陣,數據量經過復制后確實增加了很多,但是計算操作卻簡單了很多。
卷積代碼實現:

# date 2022-01-11 # 說明:比較手動實現卷積與TF實現卷積(有無GPU加速、有無cudnn加速的區別)import time import matplotlib.pyplot as plt import pylab import numpy as npdef convolve(SourceImg, Kernel):""":param SourceImg::param Kernel::return:# 分成三個通道# 1.三通道數據分離# 2.三通道數據單獨卷積操作# 3.卷積結果合并"""h = fil.shape[0] // 2 # = 1w = fil.shape[1] // 2 # = 2img = 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_channeldef 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 # mute step is 1conver_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_resultdef 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实现卷积操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。