Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

TensorFlow를 활용해 Python으로 Fashion MNIST 데이터셋 예측하는 방법


TensorFlow는 Google이 제공하는 머신러닝 프레임워크입니다. 오픈소스로 공개되어 있으며, Python과 함께 사용해 다양한 알고리즘과 딥러닝 애플리케이션을 손쉽게 구현할 수 있습니다. 연구 목적뿐 아니라 실제 프로덕션 환경에서도 널리 활용되고 있습니다.

TensorFlow는 복잡한 수학 연산을 빠르게 처리할 수 있는 최적화 기법을 갖추고 있는데, 이는 내부적으로 NumPy와 다차원 배열을 활용하기 때문입니다. 이러한 다차원 배열을 '텐서(tensor)'라고 부릅니다.

TensorFlow 설치하기

Windows 환경에서는 아래 명령어 한 줄로 'tensorflow' 패키지를 설치할 수 있습니다.

pip install tensorflow

텐서는 TensorFlow의 핵심 데이터 구조로, 데이터 흐름 그래프(Data Flow Graph)에서 노드들을 연결하는 역할을 합니다. 텐서란 결국 다차원 배열 또는 리스트를 의미합니다.

Fashion MNIST 데이터셋이란?

'Fashion MNIST' 데이터셋은 다양한 종류의 의류 이미지를 담고 있는 데이터셋입니다. 10개의 서로 다른 카테고리에 속하는 7만 장 이상의 흑백(grayscale) 이미지로 구성되어 있으며, 각 이미지의 해상도는 28 x 28 픽셀로 낮은 편입니다.

이 글의 코드는 Google Colaboratory(줄여서 Colab)에서 실행됩니다. Google Colab은 브라우저에서 바로 Python 코드를 실행할 수 있게 해주며, 별도의 설정 없이 무료로 GPU(그래픽 처리 장치)까지 사용할 수 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.

예측 코드 예제

다음은 학습된 모델을 사용해 예측을 수행하는 코드 스니펫입니다.

예제 코드

probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print("The predictions are being made ")
print(predictions[0])

np.argmax(predictions[0])
print("The test labels are")
print(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('green')

코드 출처 - https://www.tensorflow.org/tutorials/keras/classification

실행 결과

The predictions are being made
[1.3008227e-07 9.4930819e-10 2.0181861e-09 5.4944155e-10 3.8257373e-11
1.3896286e-04 1.4776078e-08 3.1724274e-03 9.4210514e-11 9.9668854e-01]
The test labels are
9

코드 설명

  • 모델 학습이 완료되면, 해당 모델이 제대로 동작하는지 반드시 테스트해야 합니다.

  • 테스트는 학습된 모델을 사용해 이미지에 대한 예측을 수행하는 방식으로 진행됩니다.

  • 모델에는 선형 출력인 로짓(logits)과 소프트맥스(softmax) 레이어가 추가로 연결됩니다.

  • 소프트맥스 레이어는 로짓 값을 확률 값으로 변환하는 역할을 담당합니다.

  • 이렇게 확률로 변환하면 모델이 내린 예측 결과를 훨씬 직관적으로 해석할 수 있습니다.

  • 'plot_value_array' 메서드는 실제 값과 예측 값을 막대그래프 형태로 시각화하여 비교해 보여주는 함수입니다.