머신러닝

1-12 Anaconda3 spyder3 MNIST 학습에 의한 숫자인식 예제 숫자 그래픽 출력

coding art 2018. 7. 22. 12:17
728x90

______________________________________________________________________________________________________________________________



MNIST 수기 숫자 머신 러낭 코드를 사용하여 인식율을 계산해 보자. 너무나 잘 알려진 MNIST 파이선 코드는 헤더 영역에서 tensorflow 모듈 즉 라이브러리를 설정한 후에 MNIST 데이터를 불러 압축을 해제한다.

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

압축이 해제되는 MNIST 데이터는 7만개의 데이터로 구성이 되며 개개의 데이터는 25X28 즉 784개의 픽셀 데이터로 이루어진다.

따라서 이 수기 숫자 이미지 데이터를 tensorflow로 분석하기 위해서는 기본적으로 100개 단위로 임의로 추출된 배치학습을 1000번 하도록 실행하도록 한다.
그 결과 약 ≅92% 수준의 인식율이 계산된다.

이러한 과정에서 임의로 추출하는 첫 배치학습을 위한 데이터 중 일부를 matplotlib 모듈에 의해 출력해 보기로 하자. 다음 부분을 헤더 영역에 추가하자.
from matplotlib import pyplot as plt
import numpy as np

아울러 이미지 출력을 위해서 MNIST 어레이 데이터를  출력 가능한 형태로 처리할 수 있도록 코드 초반에 함수 gen_image(arr)를 배치하여 session 에서 불러 쓰기로 한다.
def gen_image(arr):
    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
    plt.imshow(two_d, interpolation='nearest')
    return plt


이미지 출력을 위한 명령과 session에서 배치 위치는 아래 그림의 코드에서 보듯이 sess.run(init) 과 for i in range(10) 사이이다. 배치 샘플 수를 5로 잡았고 학습 횟수가 10회면 총 50개의 샘플을 학습을 위해 불러내게 된다.

이 중에서 첫 배치 샘플 중 5개를 출력하는 프로그램이다. 아울러 배치 샘플 수 가 5로서 대단히 적고 학습 횟수도 매우 적어 인식율도 ≅40% 수준으로 형편없이 줄어든다는 사실에 유의하자. 



임의 추출 방식이기 때문에 매번 코드를 실행할 때마다 출력되는 숫자 이미지가 변동됨에 유의하자. 위 커버 타이틀 밑의 출력 사례는 세로로 출력된 결과를 가로로 편집한 결과이다. 가로로 출력하려면 matplotlib 용법을 수정해야 한다.

배치샘플을 모조리 출력하려면 loop 내부에서 출력하도록 코드를 수정할 필요가 있다.

사이트에 첨부된 다음의 코드를 spyder3 이나 쥬티처 노트북에서 실행해 보자.


//MNIST_02


# -*- coding: utf-8 -*-

# MNIST 데이터를 다운로드 한다.
from matplotlib import pyplot as plt
import numpy as np

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# TensorFlow 라이브러리를 추가한다.
import tensorflow as tf

def gen_image(arr):
    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
    plt.imshow(two_d, interpolation='nearest')
    return plt

# 변수들을 설정한다.
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
#y = tf.nn.sigmoid(tf.matmul(x, W) + b)

# cross-entropy 모델을 설정한다.
y_ = tf.placeholder(tf.float32, [None, 10])
learning_rate = 0.5
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#cost = tf.reduce_mean( tf.square(y-y_))
#train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# 경사하강법으로 모델을 학습한다.
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
batch_xs, batch_ys = mnist.test.next_batch(5)
gen_image(batch_xs[0]).show()
gen_image(batch_xs[1]).show()
gen_image(batch_xs[2]).show()
gen_image(batch_xs[3]).show()
gen_image(batch_xs[4]).show()
for i in range(10):

  batch_xs, batch_ys = mnist.train.next_batch(5)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

   
# 학습된 모델이 얼마나 정확한지를 출력한다.
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))