TensorFlow 1.n 버전에서 tf.layers 를 사용한 CNN 모델 구현
2025. 5. 27. 04:56ㆍ인공지능/CNN
바로 전 글에선 CNN 모델을 저수준에서 구현해보았다.
https://roseandg1324.tistory.com/32
CNN 구현
이 글은 아래 글을 보고 와야 이해할 수 있다.https://roseandg1324.tistory.com/30 CNN 의 기본 구조는 아래와 같다.위 이미지를 설명하자면 2차원 구조의 숫자 3 이미지(예: 32x32 크기)가 CNN에 입력된다. convo
roseandg1324.tistory.com
이 글에서는 TensorFlow 1.x 버전에서 가능한 tf.layers API를 통해 MNIST 데이터를 활용하여 CNN 모델을 직접 구현한다.
먼저 데이터를 불러오자
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 데이터 로드
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
기본적인 placeholder를 정의한다.
# mnist 데이터는 가로 새로가 각 28의 해상도이기 때문에
# 데이터가 들어올 수 있는 공간을 준비한다.
X = tf.placeholder(tf.float32, [None, 28, 28, 1])
# 정답 데이터는 0 ~ 9이기 때문에 10개의 공간만 만들어 놓는다.
Y = tf.placeholder(tf.float32, [None, 10])
# Dropout 비율을 위한 변수
keep_prob = tf.placeholder(tf.float32)
이제 tf.layers 를 사용하여 모델을 구성한다.
# 이 층 입력 X는 [batch_size, 28, 28, 1]의 mnist 데이터이다.
# batch_size = B 로 쓰겠다.
# 3x3사이즈의 Filter를 32개 사용한다.
# 나머지 인자는 전 내용을 봤다면 알 것이다.
conv1 = tf.layers.conv2d(input=X, filters=32, kernel_size=[3,3], padding='SAME', activation=tf.nn.relu)
# 입력 : [B, 28, 28, 32]
# 2x2의 Max pooling : 해상도 반으로 감소
pool1 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2,2], strides=2)
# 입력 : [B, 14, 14, 32]
conv2 = tf.layers.conv2d(input=pool1, filters=64, kernel_size=[3,3], padding='SAME', activation=tf.nn.relu)
# 입력 : [B, 14, 14, 64]
pool2 = tf.layers.max_pooling2d(inputs=conv1, pool_size=[2,2], strides=2)
# 출력 : [B, 7, 7, 64]
# Conv + Maxpooling 연산의 최종 결과는 4차원이다.
# (7 * 7 * 64 = 3136)
# 이제 FC에 삽입해야 하기 때문에 [B, 3136] 으로 일렬로 펼친다.
flat = tf.layers.flatten(pool2)
# 이제 FC인 dense 층으로 전달한다.
# units 는 뉴런의 개수이다.
# 입력 : [B, 3136]
dense = tf.layers.dense(inputs=flat, units=128, activation=tf.nn.relu)
# 출력 : [B, 128]
dropout = tf.layers.dropout(inputs=dense, rate=1-keep_prob)
# 10개 클래스로 최종 분류
logits = tf.layers.dense(inputs=dropout, units=10)
# softmax 적용하여 확률 값 얻기
prediction = tf.nn.softmax(logits)
모델 구조를 정의했으니 다음은 Loss function과, Optimizer를 정의한다.
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=Y))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)
다음은 측정 지표를 정의한다.
correct_pred = tf.equal(tf.argmax(prediction, 1), tf.argmax(Y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
이제 훈련을 시켜보도록 하자
for epoch in range(15):
avg_cost = 0
total_batch = int(mnist.train.num_examples / 100)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
batch_xs = batch_xs.reshape([-1, 28, 28, 1]) # 이미지 형태로 reshape
feed_dict = {X: batch_xs, Y: batch_ys, keep_prob: 0.7}
c, _ = sess.run([cost, optimizer], feed_dict=feed_dict)
avg_cost += c / total_batch
print("Epoch:", '%02d' % (epoch + 1), "cost = {:.9f}".format(avg_cost))
이제 Validation을 하는 코드를 추가하고 실행하면 될 것이다.
test_images = mnist.test.images.reshape([-1, 28, 28, 1])
test_accuracy = sess.run(accuracy, feed_dict={X: test_images, Y: mnist.test.labels, keep_prob: 1.0})
print("Test Accuracy:", test_accuracy)
MLP나 DNN보다 훨씬 잘 나온 Accuracy를 볼 수 있다.

'인공지능 > CNN' 카테고리의 다른 글
| tensorflow를 사용한 CNN 저수준 구현 (0) | 2025.05.27 |
|---|---|
| CNN 추론에 대한 이론 이해 (0) | 2025.05.01 |