합성곱 연산을 사용하는 신경망
row = []
matrix = []
for matrix_row in range(input.shape[0]-w.shape[0]+1):
for matrix_col in range(input.shape[1]-w.shape[1]+1):
matrix = []
for w_row in range(w.shape[0]):
row = []
for w_col in range(w.shape[0]):
row.append(input[matrix_row+w_row,matrix_col+w_col])
matrix.append(row)
print(matrix)
각 커널에 대한 합성곱 연산을 할 행렬, matrix의 생성, 이는 가중치 행렬과 동일한 크기다.
row = []
matrix = []
result = []
for matrix_row in range(input.shape[0]-w.shape[0]+1):
for matrix_col in range(input.shape[1]-w.shape[1]+1):
matrix = []
for w_row in range(w.shape[0]):
row = []
for w_col in range(w.shape[0]):
row.append(input[matrix_row+w_row,matrix_col+w_col])
matrix.append(row)
result.append(matrix*w)
result = np.array(result)
result.reshape(9,-1)
result
>>>
array([[[0.08696687, 0.78912802],
[0.55418332, 0.44576419]],
[[0.9076278 , 0.36782108],
[0.29988894, 0.06308654]],
[[0.4230551 , 0.67371227],
[0.04244163, 0.79072746]],
[[0.88224343, 0.41508316],
[0.23808613, 0.5482694 ]],
[[0.47741432, 0.05874443],
[0.36884957, 0.88970222]],
[[0.06756581, 0.73630332],
[0.59854934, 0.82270165]],
[[0.37902607, 0.51053315],
[0.39487136, 0.31777099]],
[[0.5871976 , 0.82846585],
[0.21378121, 0.6028543 ]],
[[0.95287281, 0.76607679],
[0.4055717 , 0.72192621]]])
matrix의 크기에 따라 용량을 많이 요구할 수도 있기 때문에 생성과 동시에 연산을 수행하는 것이 더 나을 것
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_arr
>>>
[1.8760423945638465,
1.6384243652554065,
1.9299364610860785,
2.083682123609485,
1.7947105381568158,
2.225120122119695,
1.6022015709429518,
2.2322989528570516,
2.8464475164067666]
동일한 연산 결과 확인, 불필요한 반복의 제거
result = np.array(result_arr).reshape(input.shape[0]-w.shape[0]+1,-1)
result
>>>
array([[1.87604239, 1.63842437, 1.92993646],
[2.08368212, 1.79471054, 2.22512012],
[1.60220157, 2.23229895, 2.84644752]])
리스트의 행렬 변환 수행,
'implement_ml_models' 카테고리의 다른 글
implement_stride (0) | 2022.11.22 |
---|---|
implement_padding (0) | 2022.11.22 |
implement_activation (0) | 2022.11.21 |
implement_multiLayerPerceptron (0) | 2022.11.21 |
implement_perceptron (0) | 2022.11.21 |