Numpy实现卷积神经网络的方法-创新互联

Numpy实现卷积神经网络的方法?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

创新互联建站主营宁晋网站建设的网络公司,主营网站建设方案,重庆APP开发,宁晋h5微信小程序开发搭建,宁晋网站营销推广欢迎宁晋等地区企业咨询
import numpy as np
import sys


def conv_(img, conv_filter):
  filter_size = conv_filter.shape[1]
  result = np.zeros((img.shape))
  # 循环遍历图像以应用卷积运算
  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)):
      # 卷积的区域
      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

    # 裁剪结果矩阵的异常值
  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):
  # 检查图像通道的数量是否与过滤器深度匹配
  if len(img.shape) > 2 or len(conv_filter.shape) > 3:
    if img.shape[-1] != conv_filter.shape[-1]:
      print("错误:图像和过滤器中的通道数必须匹配")
      sys.exit()

  # 检查过滤器是否是方阵
  if conv_filter.shape[1] != conv_filter.shape[2]:
    print('错误:过滤器必须是方阵')
    sys.exit()

  # 检查过滤器大小是否是奇数
  if conv_filter.shape[1] % 2 == 0:
    print('错误:过滤器大小必须是奇数')
    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, :]

    # 检查单个过滤器是否有多个通道。如果有,那么每个通道将对图像进行卷积。所有卷积的结果加起来得到一个特征图。
    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

名称栏目:Numpy实现卷积神经网络的方法-创新互联
网页路径:http://scjbc.cn/article/cddded.html

其他资讯