본문 바로가기

DEVELOPMENT/TensorFlow

[TensorFlow] 기본 이미지 분류

기본 이미지 분류

 

 

🔎 개요

이미지 분류(Image Classification)는 컴퓨터가 일련의 이미지를 분석하고 해당 이미지가 어떤 범주에 속하는지 판단하게 만드는 것을 말한다. TensorFlow를 사용하면 간단하게 이미지 분류를 시작할 수 있으며 커스텀 모델을 구현하여 더 복잡하고 구체적인 문제를 해결할 수 있다. 

 

📌 주제

패션 MNIST 데이터셋을 사용하여 운동화나 셔츠 같은 옷 이미지를 분류하는 신경망 모델 훈련

 

📝 과정

① 패션 MNIST 데이터셋 임포트

② 데이터 탐색

③ 데이터 전처리

④ 모델 구성(층 설정, 모델 컴파일)

⑤ 모델 훈련(모델 맞추기, 정확도 평가, 예측)

⑥ 훈련된 모델 사용

 

💻 개발환경

구글 코랩(Colab) : 클라우드 기반의 무료 Jupyter 노트북 개발 환경

 

 

TensorFlow 설정

 

import tensorflow as tf

import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

 

1. Numpy

넘파이(Numpy)는 파이썬에서 수치 연산을 위한 핵심 라이브러리이다. 넘파이는 다차원 배열(ndarray) 객체와 이를 다루기 위한 다양한 함수와 도구를 제공하여 고성능의 수치 연산을 가능하게 한다

 

2. matplotlib.pyplot
데이터 시각화를 위한 파이썬 라이브러리인 matplotlib의 서브패키지이다. 주로 그래프를 그리는 기능을 제공하며, 선 그래프, 산점도, 막대 그래프, 히스토그램 등 다양한 종류의 시각화를 지원한다.

 

 

MNIST 데이터셋 임포트하기

 

# 패션 MNIST 데이터셋 사용
fashion_mnist = tf.keras.datasets.fashion_mnist 

# 훈련 세트, 테스트 세트 넘파이(Numpy) 배열 반환
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

# 데이터셋 클래스 이름 설정
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

 

 

데이터 탐색

 

train_images.shape # (60000, 28, 28)

len(train_labels) # 60000

train_labels # array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)

test_images.shape # (10000, 28, 28)

len(test_labels) # 10000

 

 

데이터 전처리

 

plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

# 신경망 모델 주입하기 전에 값의 범위를 0~1 사이로 조정
train_images = train_images / 255.0
test_images = test_images / 255.0

plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

 

 

모델 구성

 

# 모델의 층 구성
model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

# 모델 컴파일
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

 

 

모델 훈련

 

# 모델 맞추기
model.fit(train_images, train_labels, epochs=10)

# 정확도 평가
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
print('\nTest accuracy:', test_acc)

# 예측하기
probability_model = tf.keras.Sequential([model, 
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
predictions[0]
np.argmax(predictions[0])
test_labels[0]

# 이미지와 예측 결과 시각화 
def plot_image(i, predictions_array, true_label, img):
  true_label, img = true_label[i], img[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])

  plt.imshow(img, cmap=plt.cm.binary)

  predicted_label = np.argmax(predictions_array)
  if predicted_label == true_label:
    color = 'blue'
  else:
    color = 'red'

  plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                100*np.max(predictions_array),
                                class_names[true_label]),
                                color=color)
# 막대 그래프를 통해 예측 확률 시각화
def plot_value_array(i, predictions_array, true_label):
  true_label = true_label[i]
  plt.grid(False)
  plt.xticks(range(10))
  plt.yticks([])
  thisplot = plt.bar(range(10), predictions_array, color="#777777")
  plt.ylim([0, 1])
  predicted_label = np.argmax(predictions_array)

  thisplot[predicted_label].set_color('red')
  thisplot[true_label].set_color('blue')


# 예측 확인
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

i = 12
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions[i], test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions[i],  test_labels)
plt.show()

num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

 

 

훈련된 모델 사용

 

img = test_images[1]
print(img.shape) # (28, 28)

img = (np.expand_dims(img,0))
print(img.shape) # (1, 28, 28)

predictions_single = probability_model.predict(img)
print(predictions_single)

# 예측 확률 시각화 
plot_value_array(1, predictions_single[0], test_labels)
# 클래스 이름을 x축에 표시
_ = plt.xticks(range(10), class_names, rotation=45)
# 그래프 출력
plt.show()
# 가장 높은 예측 확률을 가진 클래스의 인덱스 구하기
np.argmax(predictions_single[0]) # 2

 

 

 

 

'DEVELOPMENT > TensorFlow' 카테고리의 다른 글

[TensorFlow] 워드 임베딩  (0) 2023.06.29
[TensorFlow] 기본 텍스트 분류  (0) 2023.06.29
[TensorFlow] 텐서플로 2.0 시작하기  (0) 2023.06.29