MNIST
#
Find similar titles
- 최초 작성자
- 최근 업데이트
Structured data
- Category
- Programming
Table of Contents
TensorFlow Tutorial #
텐서플로우(TensorFlow)를 설치한 후 머신러닝과 텐서플로우의 기본적인 내용을 연습을 목적으로 하는 튜토리얼이며, MNIST란 0~9까지 숫자들을 손글씨로 적은 데이터들이다.
Check #
우선 TensorFlow와 Python이 설치되어있는지 확인한다. import sys sys.version # 버젼 확인.
다음으로 Jupyter nootbook이 설치되어 있는지 확인하는데 만약 설치가 되어 있지 않다면 아래 링크를 통해 설치를 진행한다. Anaconda를 설치하면 Python과 Jupyter Nootbook이 같이 설치된다. 버젼은 3.5버젼 이상으로 설치하는 것을 권장한다.
- TensorFlow : https://www.tensorflow.org/install/
- Jupyter nootbook : https://www.anaconda.com/download/
MNIST #
MNIST란 손글씨 숫자 이미지들을 모아놓은 데이터로서 우선 해당 데이터가 어떻게 생겼는지 확인해보자.
Data import #
데이터를 불러온다.
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
- MNIST를 불러와서 train과 test 2가지로 나눔.
- train은 훈련시킬 데이터.
- test는 훈련시킨 모델의 테스트용 데이터.
- _images는 숫자 이미지의 정보.
- _labels는 숫자 이미지의 이름.
Data Check #
불러온 훈령용 데이터 train_images 의 타입과 길이를 출력해본다.
print('train_images type: {} / len: {}'.format(type(train_images), len(train_images)))
train_images type: <class 'numpy.ndarray'> / len: 60000 # 결과출력
- numpy.ndarray' : 숫자로 된 배열.
- len: 60000 : 배열들이 6만개가 있음.
이번엔 확인용 데이터 test_images 의 타입과 길이를 출력해본다.
print('test_images type: {} / len: {}'.format(type(test_images), len(test_images)))
test_images type: <class 'numpy.ndarray'> / len: 10000 # 결과출력
- numpy.ndarray : 숫자로 된 배열.
- len: 10000 : train은 6만개이지만 test는 1만개.
shape
명령어를 사용하여 배열 데이터를 확인해보도록 한다.
print(train_images.shape)
(60000, 28, 28) # 결과 출력
- 60000 : 개수가 6만개.
- 28, 28 : 하나의 배열은 28 x 28로 구성됨.
출처 : tensorflow. MNIST For ML Beginners.
Model #
from keras import models, layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))
network.add(layers.Dense(10, activation='softmax', input_shape=(512,)))
network.compile(
optimizer = 'adam',
loss = 'categorical_crossentropy',
metrics = ['accuracy'],)
우선 network를 추가하고, network.add를 통해 인풋과 아웃풋 데이터를 설정한다. 마지막으로 compile을 하면서 데이터를 훈련시킨다.
Data Regression #
머신러닝으로 훈련을 진행하기 전에 데이터 정규화 작업을 거쳐서 훈련가능한 형태로 변경한다.
Astype #
reshape
로 출력 데이터를 같은 양식으로 통일하는 작업을 진행한다. 배열을 구성하는 숫자가 0~255로 되어 있기 때문에 .astype('float')/ 255
를 이용하여 255로 나우어 0~1까지의 숫자로 변환한다.
train_X = train_images.reshape(60000, -1)
train_X = train_X.astype('float')/ 255
test_X = test_images.reshape(10000, -1)
test_X = test_X.astype('float')/ 255
One-Hot vectors #
labels 데이터들의 양식을 사용가능한 형태로 변환한다.to_categorical
은 라벨에 해당하는 숫자만 1로, 나머지는 0으로 변환시키며, 훈련시킨 결과값과 라벨값이 일치하는지 테스트하는 용도로 사용한다.
from keras.utils import to_categorical
train_Y = to_categorical(train_labels)
test_Y = to_categorical(test_labels)
출처 : tensorflow. MNIST For ML Beginners.
Training #
변환된 데이터를 가지고 훈련을 진행한다.
network.fit(train_X, train_Y, epochs=5, batch_size=128)
- epochs=5 : 총 5번 훈련.
- batch_size=128 : 한 번에 128개씩 훈련.
Evaluation #
테스트 데이터를 사용하여 훈련된 모델의 정확도를 측정한다.
test_loss, test_acc = network.evaluate(test_X, test_Y)
print('Accuracy : {:.3f}'.format(test_acc))
Accuracy : 0.981 # 결과 출력
정확도가 98.1%이라는 의미로, 100개중 2개 꼴로 인식하지 못하였다.
Loss Data #
correctly_predicted
을 출력해서 확인한다.
test_pred = network.predict_classes(test_X)
import numpy as np
correctly_predicted = np.equal(test_pred, test_labels)
- test_pred : 1만개의 test_X의 예측한 값
- correctly_predicted : 1만개의 예측된 값을 라벨값과 비교하여 참, 거짓 여부를 판단.
아래와 같은 결과가 출력되며, 총 1만 개의 라벨중 맞은 부분은 True, 틀린 부분은 False로 표시된다.
len(correctly_predicted), correctly_predicted
(10000, array([ True, True, True, ..., True, True, True])) # 결과 출력
Loss Data Check #
해당 출력값을 확인해 보면 149, 247, 321, 340, ... 등으로 예측이 틀린 이미지의 인덱스 번호를 확인할 수 있다.
wong_predictions = np.where(correctly_predicted == False)[0];
wong_predictions
- wong_predictions : 잘못 예측한 데이터를 모아놓은 배열.
잘 못 예측한 이미지들 중 아래와 같은 예시를 확인할 수 있다. 예측값은 8이지만 원본의 값은 9인 경우의 예시이다.
이미지1 | 이미지2 |
---|---|
출처 : MNIST 테스트 이미지.