본문 바로가기

implement_ml_models/CNN

impelment_CNN(stride)

필터가 적용되는 위치를 1픽셀이 아닌, 여러 픽셀씩 움직이며 계산하는 경우도 있다. 이 필터의 적용 위치 간격을 스트라이드라 부른다. 

스트라이드 값을 s라고 했을 때 출력 이미지의 픽셀값은 다음과 같이 계산되며,

출력 이미지의 크기는 약 1/s 배가 된다. 

출력 이미지의 정확한 크기는 다음과 같이 계산된다.

크기가 큰 입력 이미지를 다룰 때, 출력쪽 유닛 수가 너무 많아지는 것을 막기 위해 2 이상의 스트라이드 값을 적용하는 경우가 있다. 그러나 이는 이미지의 특징을 놓칠 가능성을 의미하여, 일반저긍로 성능을 악화시키는 방향으로 경우가 많아 피하는 것이 좋다.

input = np.random.random(16).reshape(4,4)
input
>>>
array([[0.44347376, 0.29017623, 0.62991373, 0.50209371],
       [0.63625638, 0.58489094, 0.8153437 , 0.67830812],
       [0.99001811, 0.15216859, 0.23262359, 0.32014961],
       [0.21619336, 0.33241801, 0.92530904, 0.02216692]])
       
#가중치 커널 생성

w = np.random.random(4).reshape(2,2)
w
>>>
array([[0.90716266, 0.06596578],
       [0.82393991, 0.79375542]])
       
result_arr = []
stride_row = 2
stride_col = 2

for matrix_row in range(0, input.shape[0]-w.shape[0]+1, stride_row):
  for matrix_col in range(0, input.shape[1]-w.shape[1]+1, stride_col):
    result = []
    for w_row in range(w.shape[0]):
      for w_col in range(w.shape[1]):
        result.append(input[matrix_row+w_row,matrix_col+w_col] * w[w_row, w_col])
    result_arr.append(np.sum(result))
    
result = np.array(result_arr).reshape(int(input.shape[0]-w.shape[0]+1/2),-1)
result
>>>
array([[1.40994192, 1.81476018],
       [1.35013431, 1.01214052]])

'implement_ml_models > CNN' 카테고리의 다른 글

implement_CNN(pooling)  (0) 2023.03.07
implement_CNN(start)  (0) 2023.03.07
implement_CNN(pooling)  (0) 2022.12.06
implement_CNN(padding)  (0) 2022.12.06
implement_CNN(basic)  (0) 2022.12.06