CNN (합성곱신경망)
작은 필터를 순환 시키는 방식
이미지 패턴이 아닌 특징을 중점으로 인식
convolution layer -> pooling layer -> fullyconnected layer(Dense)
입력이미지의 특징을 추출, 븐류하는 과정으로 동작
이미지에서 어떠한 특징이 있는지 구하는 과정
필터가 이미지를 이동하며 새로운 이미지(미쳐맵)를 생성
피쳐맵의 크기 변형:Padding, Striding
Padding 원본 이미지의 상하좌우에 한 줄 씩 추가
Striding 필터를 이동시키는 거리(Stride)설정
Pooling layer
이미지의 왜곡 영향(노이즈)를 축소하는 과정
Max Pooling
Average Pooling
Fully Connected layer
추출된 특징을 사용 하여 이미지를 분류
분류를 위한 softmax 활성화 함수
object detection & segmentation
superresolution(SR) -> 선명하게 하는 것
MNIST 분류 CNN 모델 - 모델 구현
[실습1]에 이어서 이번 실습에서는 CNN 모델을 구현하고 학습해보겠습니다.
Keras에서 CNN 모델을 만들기 위해 필요한 함수/메서드
- CNN 레이어
tf.keras.layers.Conv2D(filters, kernel_size, activation, padding)
Copy
: 입력 이미지의 특징, 즉 처리할 특징 맵(map)을 추출하는 레이어입니다.
- filters : 필터(커널) 개수
- kernel_size : 필터(커널)의 크기
- activation : 활성화 함수
- padding : 이미지가 필터를 거칠 때 그 크기가 줄어드는 것을 방지하기 위해서 가장자리에 0의 값을 가지는 픽셀을 넣을 것인지 말 것인지를 결정하는 변수. ‘SAME’ 또는 ‘VALID’
- Maxpool 레이어
tf.keras.layers.MaxPool2D(padding)
Copy
: 처리할 특징 맵(map)의 크기를 줄여주는 레이어입니다.
- padding : ‘SAME’ 또는 ‘VALID’
- Flatten 레이어
tf.keras.layers.Flatten()
Copy
: Convolution layer 또는 MaxPooling layer의 결과는 N차원의 텐서 형태입니다. 이를 1차원으로 평평하게 만들어줍니다.
- Dense 레이어
tf.keras.layers.Dense(node, activation)
Copy
- node : 노드(뉴런) 개수
- activation : 활성화 함수
지시사항
- keras를 활용하여 CNN 모델을 설정합니다.
- 분류 모델에 맞게 마지막 레이어의 노드 수는 10개, activation 함수는 ‘softmax’로 설정합니다.
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
from visual import *
from elice_utils import EliceUtils
elice_utils = EliceUtils()
import logging, os
logging.disable(logging.WARNING)
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
# 동일한 실행 결과 확인을 위한 코드입니다.
np.random.seed(123)
tf.random.set_seed(123)
# MNIST 데이터 세트를 불러옵니다.
mnist = tf.keras.datasets.mnist
# MNIST 데이터 세트를 Train set과 Test set으로 나누어 줍니다.
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# Train 데이터 5000개와 Test 데이터 1000개를 사용합니다.
train_images, train_labels = train_images[:5000], train_labels[:5000]
test_images, test_labels = test_images[:1000], test_labels[:1000]
# CNN 모델의 입력으로 사용할 수 있도록 (샘플개수, 가로픽셀, 세로픽셀, 1) 형태로 변환합니다.
train_images = tf.expand_dims(train_images, -1)
test_images = tf.expand_dims(test_images, -1)
"""
1. CNN 모델을 설정합니다.
분류 모델에 맞게 마지막 레이어의 노드 수는 10개, activation 함수는 'softmax'로 설정합니다.
"""
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(filters = 32, kernel_size = (3,3), activation = 'relu', padding = 'SAME', input_shape = (28,28,1)),
tf.keras.layers.MaxPool2D(padding = 'SAME'),
tf.keras.layers.Conv2D(filters = 32, kernel_size = (3,3), activation = 'relu', padding = 'SAME'),
tf.keras.layers.MaxPool2D(padding = 'SAME'),
tf.keras.layers.Conv2D(filters = 32, kernel_size = (3,3), activation = 'relu', padding = 'SAME'),
tf.keras.layers.MaxPool2D(padding = 'SAME'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(64, activation = 'relu'),
tf.keras.layers.Dense(10, activation = 'softmax')
])
# CNN 모델 구조를 출력합니다.
print(model.summary())
# CNN 모델의 학습 방법을 설정합니다.
model.compile(loss = 'sparse_categorical_crossentropy',
optimizer = 'adam',
metrics = ['accuracy'])
# 학습을 수행합니다.
history = model.fit(train_images, train_labels, epochs = 20, batch_size = 512)
# 학습 결과를 출력합니다.
Visulaize([('CNN', history)], 'loss')
"""
1. 평가용 데이터를 활용하여 모델을 평가합니다.
loss와 accuracy를 계산하고 loss, test_acc에 저장합니다.
"""
loss, test_acc = model.evaluate(test_images, test_labels, verbose = 2)
#dim으로 조절 된 데이터를 넣어야함
"""
2. 평가용 데이터에 대한 예측 결과를 predictions에 저장합니다.
"""
predictions = model.predict_classes(test_images)
# 모델 평가 및 예측 결과를 출력합니다.
print('\nTest Loss : {:.4f} | Test Accuracy : {}'.format(loss, test_acc))
print('예측한 Test Data 클래스 : ',predictions[:10])
# 평가용 데이터에 대한 레이어 결과를 시각화합
'DL' 카테고리의 다른 글
영화 리뷰 긍정/부정 분류 RNN 모델 - 모델 학습 (0) | 2022.11.25 |
---|---|
자연어 처리를 위한 데이터 전처리 (0) | 2022.11.25 |
CNN 모델 전처리 (0) | 2022.11.25 |
텐서플로우 학습 모델만들기 layer구성 및 평가 및 예측 (0) | 2022.11.25 |
텐서플로우를 활용하여 신경망 구현하기 - 모델 학습 (0) | 2022.11.25 |