✨ 딥러닝·머신러닝

합성곱 신경망(CNN) - 합성곱 신경망을 구현해 보자 (CIFAR-10)

Vento AI Lab 2026. 6. 10.
반응형

1. 합성곱 신경망 개요

합성곱 신경망(Convolutional Neural Network)은 이미지 인식 분야에서 매우 효과적인 딥러닝 알고리즘 중 하나이다. CNN은 이미지 학습에 특화된 모델이며 이미지 데이터를 처리하여 효율적인 학습을 돕는다. 이미지에 필터(Filter)를 적용하여 유용한 특징(Feature)을 드러나게 한다. 그 과정에서 이미지를 데이터화하여 특징맵(Feature map)을 만든다.

CNN은 이미지의 각 위치에서 작은 필터(filter)를 적용하여 특징 맵(feature map)을 생성하며, 이를 통해 이미지의 특징을 추출한다. 합성곱 연산은 필터를 이미지의 모든 위치에 적용하고, 필터와 이미지의 각 위치의 곱을 합하여 특징 맵을 생성한다. 이후, 특징 맵에서 풀링 연산을 적용하여 이미지를 축소하고, 특징을 보존한다. CNN은 다양한 종류의 필터를 사용하여 이미지에서 다양한 특징을 추출하며, 이를 결합하여 더욱 복잡한 특징을 학습할 수 있다. 이러한 특징 추출 과정을 통해 CNN은 이미지의 클래스를 예측하는데 사용된다.

2. 이미지 데이터 준비

CNN(Convolution Neural Network)을 구현하기 위해 Keras를 설치해보자. 그리고 이미지 데이터는 이미지 분류에 많이 사용되는 CIFAR-10 dataset을 사용한다. 32 x 32 크기의 컬러 이미지로 10가지 분류로 되어 있고 5만개의 훈련이미지와 1만개의 테스트이미지로 구성되어 있다.

https://www.cs.toronto.edu/~kriz/cifar.html

 

CIFAR-10 and CIFAR-100 datasets

< Back to Alex Krizhevsky's home page The CIFAR-10 and CIFAR-100 datasets are labeled subsets of the 80 million tiny images dataset. CIFAR-10 and CIFAR-100 were created by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton. The CIFAR-10 dataset The CIFAR-10

www.cs.toronto.edu

 
 
Label
Class Name
0
airplane
1
automobile
2
bird
3
cat
4
deer
5
dog
6
frog
7
horse
8
ship
9
truck

3. 테스트 이미지 확인

아래의 코드로 테스트 이미지 25개를 먼저 확인해 보자. 합성곱 신경망에서 10개의 이미지를 예측하는데 사용한다.

import tensorflow as tf
from tensorflow.keras.datasets import cifar10
import matplotlib.pyplot as plt

# CIFAR-10 데이터 로드
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()

# CIFAR-10 클래스 레이블 정의
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

# 이미지 표시 함수
def plot_images(images, labels):
    plt.figure(figsize=(9, 9))
    for i in range(25):
        plt.subplot(5, 5, i + 1)
        plt.xticks([])
        plt.yticks([])
        plt.grid(False)
        plt.imshow(images[i])
        plt.xlabel(class_names[labels[i][0]])

# 이미지 표시
plot_images(train_images, train_labels)
plt.show()

 

실행결과

이미지는 cat, ship, ship, airplane, frog, flog, automobile, flog, cat, automobile 로 라벨값은 3 8 8 0 6 6 1 6 3 1 이다.

4. 합성곱 신경망 예제

합성곱 신경망은 이미지의 공간 정보를 보존하면서 특징을 추출하는데 우수한 성능을 보인다. 입력 이미지에 대해 합성곱 연산(Convolution)과 풀링 연산(Pooling)을 반복적으로 수행하여 이미지에서 특징을 추출하는 방식으로 동작한다. 합성곱 신경망은 합성곱 계층, 폴링 계층, 활성 함수를 N번 반복하가 평탄화, 전결합 계층, 렐루 함수, 전결합 계층, 소프트맥스 함수를 통해 분류 결과를 출력한다.

 

특징 추출 및 폴링

 

평탄화 및 분류

아래는 합성곱 신경망으로 훈련 이미지 데이터로 학습하고 주어진 이미지를 예측하는 예제이다.

from tensorflow import keras
from keras.datasets import cifar10
import numpy as np

# CIFAR-10 데이터 로드
(train_images, train_labels), (test_images, test_labels) = cifar10.load_data()

# 데이터 정규화
train_images = train_images / 255.0
test_images = test_images / 255.0

# 모델 생성
## Feature Extraction : Convolution
model = keras.Sequential()
model.add(keras.layers.Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(keras.layers.MaxPooling2D(2, 2))
model.add(keras.layers.Dropout(0.2))
model.add(keras.layers.Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(keras.layers.MaxPooling2D(2, 2))
model.add(keras.layers.Conv2D(64, kernel_size=(3, 3), activation='relu'))
model.add(keras.layers.Dropout(0.2))
## Fully Connected Neural Network
model.add(keras.layers.Flatten())
model.add(keras.layers.Dense(64, activation='relu'))
model.add(keras.layers.Dense(10, activation='softmax'))

# 모델 요약
model.summary()

# 모델 컴파일
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics='accuracy')

# 모델 훈련
model.fit(train_images, train_labels, epochs=5)

# 모델 평가
loss, accuracy = model.evaluate(test_images, test_labels)
print("loss = ", loss)
print("accuracy = ", accuracy)

# 10개 테스트 이미지
test_batch = test_images[:10]

# 모델 예측
preds = model.predict(test_batch)

# 예측 출력
print("preds =", preds)
print()

# 예측 라벨값
for i in range(0, 10):
    print(np.argmax(preds[i]))
 

 

실행 결과

테스트 이미지는 cat, ship, ship, airplane, frog, flog, automobile, flog, cat, automobile 이다.

테스트 이미지의 라벨값과 합성곱 신경망의 예측값을 비교해 보면 10개의 이미지를 정확하게 예측했다.

테스트 이미지 라벨값

3 8 8 0 6

6 1 6 3 1

합성곱 신경망 예측값

3 8 8 0 6

6 1 6 3 1

 

Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz
170498071/170498071 [==============================] - 34s 0us/step

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 conv2d (Conv2D)             (None, 30, 30, 32)        896

 max_pooling2d (MaxPooling2  (None, 15, 15, 32)        0
 D)

 dropout (Dropout)           (None, 15, 15, 32)        0

 conv2d_1 (Conv2D)           (None, 13, 13, 64)        18496

 max_pooling2d_1 (MaxPoolin  (None, 6, 6, 64)          0
 g2D)

 conv2d_2 (Conv2D)           (None, 4, 4, 64)          36928

 dropout_1 (Dropout)         (None, 4, 4, 64)          0

 flatten (Flatten)           (None, 1024)              0

 dense (Dense)               (None, 64)                65600

 dense_1 (Dense)             (None, 10)                650

=================================================================
Total params: 122570 (478.79 KB)
Trainable params: 122570 (478.79 KB)
Non-trainable params: 0 (0.00 Byte)
_________________________________________________________________
Epoch 1/5
1563/1563 [==============================] - 46s 29ms/step - loss: 1.5604 - accuracy: 0.4272
Epoch 2/5
1563/1563 [==============================] - 47s 30ms/step - loss: 1.2069 - accuracy: 0.5683
Epoch 3/5
1563/1563 [==============================] - 43s 28ms/step - loss: 1.0648 - accuracy: 0.6224
Epoch 4/5
1563/1563 [==============================] - 47s 30ms/step - loss: 0.9749 - accuracy: 0.6571
Epoch 5/5
1563/1563 [==============================] - 44s 28ms/step - loss: 0.9117 - accuracy: 0.6771
313/313 [==============================] - 3s 9ms/step - loss: 0.9223 - accuracy: 0.6769
loss =  0.9222956895828247
accuracy =  0.6769000291824341
1/1 [==============================] - 0s 141ms/step
preds = [[2.12204014e-03 9.34139825e-04 3.83830816e-02 7.69994736e-01
  5.73902042e-04 5.87728955e-02 8.62530619e-02 7.26653205e-04
  3.93953696e-02 2.84419325e-03]
 [1.20820396e-01 2.46473476e-01 3.11851340e-06 2.18974992e-06
  1.00799662e-06 3.65487068e-07 3.05865092e-06 7.89417811e-08
  6.24216318e-01 8.48003570e-03]
 [1.91791415e-01 7.85917416e-02 4.41406202e-03 3.67735000e-03
  1.41761103e-03 5.72392019e-04 5.72392857e-03 4.87502984e-04
  6.33386016e-01 7.99379423e-02]
 [9.10928547e-01 6.11062977e-04 8.30099452e-03 2.11701705e-03
  8.98183044e-03 3.39142425e-04 4.04776598e-04 1.49067127e-04
  6.70998544e-02 1.06779474e-03]
 [2.48496576e-06 2.65965605e-06 2.65350845e-03 1.77433603e-02
  2.42467858e-02 5.10739163e-04 9.54778135e-01 3.62141327e-05
  7.36488801e-06 1.87366877e-05]
 [6.00482826e-06 8.31578018e-06 1.39598008e-02 1.24198701e-02
  1.82837551e-03 3.59785324e-03 9.68078136e-01 8.31470534e-05
  3.03824459e-06 1.53850324e-05]
 [9.52167343e-03 3.94392163e-01 8.52625221e-02 1.27099141e-01
  1.05408055e-03 2.81977803e-01 1.68763623e-02 1.40300039e-02
  1.06445525e-03 6.87216818e-02]
 [2.05631688e-04 7.23919147e-05 7.29793385e-02 2.29640827e-02
  1.61500648e-02 2.30957172e-03 8.84632826e-01 1.16336683e-04
  1.43148296e-04 4.26613231e-04]
 [7.80785194e-05 6.47245179e-06 2.36559846e-02 7.91743279e-01
  3.33231799e-02 1.36230141e-01 1.07297590e-02 4.10477631e-03
  2.10447524e-05 1.07178843e-04]
 [2.04259008e-02 8.03451002e-01 4.40182368e-04 8.63097375e-05
  2.45232834e-04 2.59398566e-05 5.06271794e-03 1.30778808e-05
  2.25285697e-03 1.67996660e-01]]

3
8
8
0
6
6
1
6
3
1

 

 

반응형

댓글