Numpy實現(xiàn)卷積神經(jīng)網(wǎng)絡(luò)的方法?針對這個問題,這篇文章詳細(xì)介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
創(chuàng)新互聯(lián)建站主營寧晉網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā),寧晉h5微信小程序開發(fā)搭建,寧晉網(wǎng)站營銷推廣歡迎寧晉等地區(qū)企業(yè)咨詢import numpy as np import sys def conv_(img, conv_filter): filter_size = conv_filter.shape[1] result = np.zeros((img.shape)) # 循環(huán)遍歷圖像以應(yīng)用卷積運(yùn)算 for r in np.uint16(np.arange(filter_size/2.0, img.shape[0]-filter_size/2.0+1)): for c in np.uint16(np.arange(filter_size/2.0, img.shape[1]-filter_size/2.0+1)): # 卷積的區(qū)域 curr_region = img[r-np.uint16(np.floor(filter_size/2.0)):r+np.uint16(np.ceil(filter_size/2.0)), c-np.uint16(np.floor(filter_size/2.0)):c+np.uint16(np.ceil(filter_size/2.0))] # 卷積操作 curr_result = curr_region * conv_filter conv_sum = np.sum(curr_result) # 將求和保存到特征圖中 result[r, c] = conv_sum # 裁剪結(jié)果矩陣的異常值 final_result = result[np.uint16(filter_size/2.0):result.shape[0]-np.uint16(filter_size/2.0), np.uint16(filter_size/2.0):result.shape[1]-np.uint16(filter_size/2.0)] return final_result def conv(img, conv_filter): # 檢查圖像通道的數(shù)量是否與過濾器深度匹配 if len(img.shape) > 2 or len(conv_filter.shape) > 3: if img.shape[-1] != conv_filter.shape[-1]: print("錯誤:圖像和過濾器中的通道數(shù)必須匹配") sys.exit() # 檢查過濾器是否是方陣 if conv_filter.shape[1] != conv_filter.shape[2]: print('錯誤:過濾器必須是方陣') sys.exit() # 檢查過濾器大小是否是奇數(shù) if conv_filter.shape[1] % 2 == 0: print('錯誤:過濾器大小必須是奇數(shù)') sys.exit() # 定義一個空的特征圖,用于保存過濾器與圖像的卷積輸出 feature_maps = np.zeros((img.shape[0] - conv_filter.shape[1] + 1, img.shape[1] - conv_filter.shape[1] + 1, conv_filter.shape[0])) # 卷積操作 for filter_num in range(conv_filter.shape[0]): print("Filter ", filter_num + 1) curr_filter = conv_filter[filter_num, :] # 檢查單個過濾器是否有多個通道。如果有,那么每個通道將對圖像進(jìn)行卷積。所有卷積的結(jié)果加起來得到一個特征圖。 if len(curr_filter.shape) > 2: conv_map = conv_(img[:, :, 0], curr_filter[:, :, 0]) for ch_num in range(1, curr_filter.shape[-1]): conv_map = conv_map + conv_(img[:, :, ch_num], curr_filter[:, :, ch_num]) else: conv_map = conv_(img, curr_filter) feature_maps[:, :, filter_num] = conv_map return feature_maps def pooling(feature_map, size=2, stride=2): # 定義池化操作的輸出 pool_out = np.zeros((np.uint16((feature_map.shape[0] - size + 1) / stride + 1), np.uint16((feature_map.shape[1] - size + 1) / stride + 1), feature_map.shape[-1])) for map_num in range(feature_map.shape[-1]): r2 = 0 for r in np.arange(0, feature_map.shape[0] - size + 1, stride): c2 = 0 for c in np.arange(0, feature_map.shape[1] - size + 1, stride): pool_out[r2, c2, map_num] = np.max([feature_map[r: r+size, c: c+size, map_num]]) c2 = c2 + 1 r2 = r2 + 1 return pool_out