본문 바로가기

implement_ml_models/CNN

implement_CNN(basic)

합성곱 신경망은 입력 쪽에서 출력 쪽을 향해 합성곱층과 풀링층이 쌍을 이루며, 이 쌍이 여러 번 반복된다. 

합성곱

이미지 사이즈를 W * W 라고 했을 때, 픽셀을 인덱스 (i,j) 로 나타내기로 한다.

필터라는 작은 크기의 이미지를 상정하고, 그 크기를 H * H 라고 하자. 

이미지의 합성곱이란, 이미지와 필터 사이에 정의되는 다음과 같은 연산이다.

합성곱의 작용

이미지의 합성곱은 필터의 명암 패턴과 유사한 명함 패턴이 입력된 이미지 어디에 있는지를 검출하는 작용을 한다. 즉, 필터가 나타내는 특징적인 명암 구조를 이미지로부터 추출하는 작용을 한다.

# 입력 데이터 생성
input = np.random.random(16).reshape(4,4)
input
>>>
array([[0.69630105, 0.98062141, 0.31126132, 0.60385103],
       [0.41160081, 0.65936305, 0.67091633, 0.79464866],
       [0.25562064, 0.3772345 , 0.0579391 , 0.97562818],
       [0.74501807, 0.378548  , 0.8962382 , 0.21717298]])
       
# 가중치 커널 생성
w = np.random.random(4).reshape(2,2)
w
>>>
array([[0.47915972, 0.0276349 ],
       [0.21120514, 0.91373281]])
       
result_arr = []

for matrix_row in range(input.shape[0]-w.shape[0]+1):
  for matrix_col in range(input.shape[1]-w.shape[1]+1):
    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(input.shape[0]-w.shape[0]+1,-1)
result
>>>
array([[1.05015265, 1.23077507, 1.03362878],
       [0.61412389, 0.46709564, 1.24713663],
       [0.63615132, 1.08123025, 0.44245166]])

커널의 크기인 w_row, w_col 이 이미지에서 위치를 옮겨가며 합성곱 연산을 수행한다. 

'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
impelment_CNN(stride)  (0) 2022.12.06
implement_CNN(padding)  (0) 2022.12.06