우 육시 엉이 - 자연 신경망 태어나 깊은 실제 파이썬 + Keras + TensorFlow 학습 : 회선 신경망의 기본 원칙을

DEF conv_ (IMG, conv_filter) 
    filter_size = conv_filter.shape [1 ] 
    결과 = numpy.zeros ((img.shape))
     프린트 ( ' 루프 R : ' , numpy.uint16 (numpy.arange (filter_size / 2.0 IMG. 형상 [0] -filter_size / 2.0 + 1 )))
     # 화상 통해 반복은 컨볼 루션 연산을 적용한다. 
    위한 연구 에서 numpy.uint16 (numpy.arange (filter_size / 2.0 img.shape [0] -filter_size / 2.0 + 1 ))
         에 대한 C  numpy.uint16 (numpy.arange (filter_size / 2.0 , 
                                           img.shape [1] -filter_size / 2.0 + 1 )) :
            # 필터 곱해 얻을 현재 영역 얻기. 
            # 기반으로 지역 이미지를 통해 루프를 얻을 방법 
            # 이미지와 파일러 크기 회선의 가장 까다로운 부분이다. 
            curr_region IMG = [R-numpy.uint16 (numpy.floor (filter_size은 / 2.0)) : R + numpy.uint16 (numpy.ceil (filter_size / 2.0 )), 
                              C -numpy.uint16 (numpy.floor (filter_size / 2.0) ) C + numpy.uint16 (numpy.ceil (filter_size / 2.0 ))]
             # 현재 영역과 필터 사이 소자 현명한 승산. 
            curr_result = curr_region * conv_filter의 
            conv_sum= numpy.sum (curr_result) # 승산의 결과를 합산. 
            결과 [R을, C = conv_sum
             # 컨벌루션 층 기능 맵 합산 저장. 
            # 결과 행렬의 특이 패스. 
    인쇄 ( " 결과 : ' , 결과) 
    final_result = 결과 [numpy.uint16 (filter_size / 2.0) result.shape [0] - numpy.uint16 (filter_size / 2.0 ) 
                          numpy.uint16 (filter_size /2.0):result.shape [1] - numpy.uint16 (filter_size은 / 2.0 )]
     final_result 
  
DEF   컨벌루션 (IMG, conv_filter)
   '' '
  화상 크기 [img_height, img_width, 필터 사양 [filter_height, filter_width]이면 
  . Filter_width +1 - 수평 방향 img_width의 회선 필터 측면 이동 시간의 다음 번호 
  수직 방향으로 상하 이동이 filter_height + 1 - 필터 컨볼 루션 연산 주파수 image_hieght이다. 
  '' 
  move_steps_vertical = img.shape [0] - conv_filter.shape [0] + 1. 
  move_steps_horizontal = img.shape [1.] -. conv_filter.shape [. 1] + 1 
  
  결과 = numpy.zeros ((move_steps_vertical, move_steps_horizontal)) 
 
  에 대한 vertical_index 범위 (move_steps_vertical)
      horizontal_index 범위 (move_steps_horizontal)
       '' '  
      시작의 상단에서 시작, 회선 필터 3 * 3 타일을 선택합니다 및 수평 방향 변환 부.
      도착 수평 이동, 왼쪽으로 복귀하지만, 하나 개의 유닛을 우측 하강 후 위의 단계를 반복 
      회선 
      '' '을
      지역 = IMG [vertical_index : vertical_index + conv_filter.shape [0] 
                  horizontal_index : horizontal_index + conv_filter.shape [1. ] 
      
      # 카운터 다음 두 문장을 참고 할 수는 이해되어야하는 코드 로직 디버깅 
      #의 ( '영역 인덱스'인쇄, vertical_index , horizontal_index) 
      #에 인쇄 ( "현재 지역 ', 지역) 
      
      의 CURRENT_RESULT = 지역 * conv_filter 
      conv_sum = 의 np.sum (CURRENT_RESULT)
       IF conv_sum < 0 
        conv_sum의 = 0
      [horizontal_index vertical_index] 결과 = conv_sum의 
      
  복귀 결과
      
      
에서 google.colab 수입 드라이브 
drive.mount ( ' / 내용 / G 드라이브 ' )

 

 

가져올 순이익으로 NumPy와
 수입 NumPy와 

IMG = np.array ([ 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0,0], 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0] 
]) 

필터 = np.array ( 
    [ 
        [ 1, 0, -1 ], 
        [ 1, 0, -1 ], 
        [ 1, 0, -1 ] 
    ] 
  
)

FILTER1 = np.array ( 
    [ 
        [ 1, 1, 1 ], 
        [0, 0, 0], 
        [ -1, -1, -1 ] 
    ] 
  
) 

conv_img = 컨벌루션 (IMG, 필터)
 인쇄 (conv_img) 

IMG = np.array ([ 
    [ 10, 10, 10, 10, 10, 10 ], 
    [ 10 , 0, 0, 0, 0, 0], 
    [ 10 , 0, 0, 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0], 
    [ 10, 10, 10 , 0, 0, 0] 
])

conv_img = 컨벌루션 (IMG, 필터 1)
 인쇄 (conv_img)

# 로드 픽처만을 포함하는 화소 값에 그레이 스케일 이미지로 변환 
오기   skimage.data 

IMAGE_PATH를 = ' / 콘텐츠 / G 드라이브 / 드라이브 내 / dog.jpg ' 
#의 로드 포토 RGB 화상을 그레이 스케일로 변환되는 동안 
= skimage.data.load의 IMG는 (IMAGE_PATH는 as_grey는 = 참) 

반입 하기 matplotlib를
 으로부터 하기 matplotlib 오기 PLT의 AS pyplot 
plt.axis ( " OFF " ) 
plt.imshow (IMG) 
) plt.show (

 

 

# 두 필터 준비는 (3,3)의 각 필터 사양 
= 필터 np.array ([ 
    [ 
        [이 -1, 0 ,. 1 ], 
        [ -1, 0 ,. 1 ], 
        [ -1, 0 1. ] 
    ], 
    [ 
        [ 1 ,. 1 ,. 1이다. ] 
        [0,0,0], 
        [ -1, -1, -1 ] 
    ] 
]) 

DEF   회선 (IMG, conv_filter)
   '' ' 
  의 경우 이미지 크기 [img_height, img_width, 필터 사양 [filter_height, filter_width]는 
  다음 횡 컨벌루션 img_width의 개수의 수평 방향 이동은 -. filter_width +1 
  수직 컨볼 루션 연산 시간의 수직 방향으로 이동 image_hieght - filter_height + 1. 
  '' '
  move_steps_vertical = img.shape [0] - conv_filter.shape [0] + 1. 
  move_steps_horizontal = img.shape [1.] - conv_filter.shape [. 1] + 1 개. 
  
  결과 = numpy.zeros ((move_steps_vertical, move_steps_horizontal)) 
 
  에 대한 vertical_index 범위 (move_steps_vertical)
      horizontal_index 에서 : 범위 (move_steps_horizontal)
       '' ' 
      , 수평 방향의 시작 상단 선택 편 동작 파라미터의 3 * 3 회선 및 변환 부에서 시작. 
      우단 도착의 수평 이동이 있지만, 가장 왼쪽으로 복귀 한 부 하강 때, 위의 과정을 반복 
      컨벌루션 
      '' 
      지역 = IMG [vertical_index을 : vertical_index + conv_filter.shape [0],
                  horizontal_index : horizontal_index [. 1 + conv_filter.shape ] 
      
       
      의 CURRENT_RESULT = 영역 * conv_filter 
      conv_sum = np.sum (의 CURRENT_RESULT) 
      
      # 개 는이 문제를 활성화 함수는 후자의 구현 해결되므로이 제거합니다이 conv_sum <0, 판정 유의 
      
      vertical_index [결과, horizontal_index] = conv_sum의 
      
  복귀 결과 

DEF   CONV (IMG, conv_filter)
   '' ' 
  필터 어레이 이미지에 교대로 작용 # 
  ' ' 
  #의 feature_map 효과 이미지 결과에 동작 파라미터 후에 얻어지는 
  feature_maps = np.zeros (( img.shape [0] - conv_filter.shape [. 1] + 1. , 
                           img.shape [ 1.] -. conv_filter.shape [. 1] + 1, 
                           conv_filter.shape [0])) 
  에 대한 filter_num 범위 (conv_filter.shape [0]) 
    curr_filter = conv_filter [filter_num :] 
    conv_map = 컨벌루션 (IMG, curr_filter) 
    feature_maps [: : filter_num] = conv_map의 
    
  복귀 feature_maps

= IMAGE_PATH ' / 콘텐츠 / G 드라이브 / 내 문서 / dog.jpg ' 
#의 RGB 화상이 그레이 스케일 이미지로 변환하는 동안로드 포토 
IMG = skimage.data.load (IMAGE_PATH, as_grey = 참)
 # 부하 동작 파라미터의 두 세트에인가 계조에 
l1_feature_map = CONV (IMG, 필터) 

# 대상 화상의 수직 에지 추출 화상의 결과에 작용하는 동작 파라미터의 제 1 세트의 표시 
, 필립스, AX1 = matplotlib.pyplot.subplots (NROWS = 1, = 2 명으로 ncols ) 
AX1 [0] .imshow (l1_feature_map [: : 0]). set_cmap ( " 그레이 " ) 
AX1 [0] .get_xaxis () set_ticks ([]). 
AX1 [0] .get_yaxis (). set_ticks ([]) 
AX1 [0] .set_title ( " LL-MAP1 " ) 

# 오브젝트 에지 화상 레벨을 추출 화상의 결과에 작용하는 동작 파라미터의 제 2 세트를 표시
AX1 [1] .imshow (l1_feature_map [:, : 1). set_cmap ( " 회색 " ) 
AX1 [ 1 .] .get_xaxis () set_ticks ([]) 
AX1 [ 1 .] .get_yaxis () set_ticks ([] ) 
AX1 [ 1] .set_title ( " L1-Map2에 " )

'''
模拟relu运算,它的逻辑简单,如果给定数值小于0,那就将它设置为0,如果大于0,那就保持不变
'''
def  relu(feature_map):
  relu_out = np.zeros(feature_map.shape)
  for map_num in range(feature_map.shape[-1]):
    for r in np.arange(0, feature_map.shape[0]):
      for c in np.arange(0, feature_map.shape[1]):
        relu_out[r, c, map_num] = np.max([feature_map[r, c, map_num], 0])
        
  return relu_out
#显示第一幅图relu运算后的结果
fig1, ax1 = matplotlib.pyplot.subplots(nrows=1, ncols=2)
reluMap = relu(l1_feature_map)
ax1[0].imshow(reluMap[:, :, 0]).set_cmap("gray")
ax1[0].get_xaxis().set_ticks([])
ax1[0].get_yaxis().set_ticks([])
ax1[0].set_title("L1-MapRelu1")

#显示第二幅图relu运算后结果的结果
ax1[1].imshow(reluMap[:, :, 1]).set_cmap("gray")
ax1[1].get_xaxis().set_ticks([])
ax1[1].get_yaxis().set_ticks([])
ax1[1].set_title("L1-MapRelu2")

'''
模拟MaxPooling操作实现数据压缩
'''
def  pooling(feature_map, size = 2, stride = 2):
  #size表示将上下左右4个元素进行比较,每次操作在水平和竖直方向上移动2个单位
  pool_out_height = np.uint16((feature_map.shape[0] - size + 1) / stride + 1) 
  pool_out_width = np.uint16((feature_map.shape[1] - size + 1) / stride + 1)
  
  pool_out = np.zeros((pool_out_height, pool_out_width, feature_map.shape[-1]))
  
  #现在水平方向上平移,每次间隔2个单位,然后在竖直方向平移,每次间隔2个单位
  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
#显示第一幅图relu运算,再做max pooling结果
fig1, ax1 = matplotlib.pyplot.subplots(nrows=1, ncols=2)
poolingMap = pooling(reluMap)
ax1[0].imshow(poolingMap[:, :, 0]).set_cmap("gray")
ax1[0].get_xaxis().set_ticks([])
ax1[0].get_yaxis().set_ticks([])
ax1[0].set_title("L1-pooling1")

#显示第二幅图relu运算后,再做max pooling结果的结果
ax1[1].imshow(poolingMap[:, :, 1]).set_cmap("gray")
ax1[1].get_xaxis().set_ticks([])
ax1[1].get_yaxis().set_ticks([])
ax1[1].set_title("L1-pooling2")

filters2 = np.random.rand(2, 5, 5)
print('adding conv layer 2')
feature_map_2 = conv(poolingMap[:,:, 0], filters2)
print('ReLU')
relu_map_2 = relu(feature_map_2)
print('max pooling')
poolingMap_2 = pooling(relu_map_2)
print('End of conv layer 2')

#显示第二层卷积层运算后第一幅图
fig1, ax1 = matplotlib.pyplot.subplots(nrows=1, ncols=2)

ax1[0].imshow(poolingMap_2[:, :, 0]).set_cmap("gray")
ax1[0].get_xaxis().set_ticks([])
ax1[0].get_yaxis().set_ticks([])
ax1[0].set_title("Layer 2, L1-pooling1")

#显示第二层卷积层运算后第二幅图
ax1[1].imshow(poolingMap_2[:, :, 1]).set_cmap("gray")
ax1[1].get_xaxis().set_ticks([])
ax1[1].get_yaxis().set_ticks([])
ax1[1].set_title("Layer 2, L1-pooling2")

filters3 = np.random.rand(2, 7, 7)
print('adding conv layer 3')
feature_map_3 = conv(poolingMap_2[:,:, 0], filters3)
print('ReLU')
relu_map_3 = relu(feature_map_3)
print('max pooling')
poolingMap_3 = pooling(relu_map_3)
print('End of conv layer 3')

#显示第三层卷积层运算后第一幅图
fig1, ax1 = matplotlib.pyplot.subplots(nrows=1, ncols=2)

ax1[0].imshow(poolingMap_3[:, :, 0]).set_cmap("gray")
ax1[0].get_xaxis().set_ticks([])
ax1[0].get_yaxis().set_ticks([])
ax1[0].set_title("Layer 2, L1-pooling1")

#显示第三层卷积层运算后第二幅图
ax1[1].imshow(poolingMap_3[:, :, 1]).set_cmap("gray")
ax1[1].get_xaxis().set_ticks([])
ax1[1].get_yaxis().set_ticks([])
ax1[1].set_title("Layer 2, L1-pooling2")

 

추천

출처www.cnblogs.com/tszr/p/12232664.html