머신러닝

1-13 Anaconda3 spyder3 MNIST 학습에 의한 그래픽 출력 데이터 픽셀 값 관찰

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

______________________________________________________________________________________________________________________________


MNIST 데이터 베이스를 사용함에 있어서 수많은 데이터 중에 하나를 선택하여 그 이미지를 출력해보자. 물론 batch 크기를 100, looping을 1000로 하면 ≅92% 수준의 인식율이 달성되지만 이 규모를 축소하면 인식율이 급격히 떨어지게 된다. 하지만 이 규모 축소는 인식율 향상이 목표가 아니라 사용하는 데이터 베이스의 규모를 인위적으로 줄인 후 선택된 하나의 데이터 세트를 대상으로 구체적인 픽셀 정보를 알아보기 위한 것이다. 즉 다음과 같이 코드를 변경하도록 하자.


⏺⏺⏺
sess.run(init)
batch_xs, batch_ys = mnist.test.next_batch(1)
gen_image(batch_xs[0]).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})
⏺⏺⏺
   
batch 샘플링을 한번에 5회로 제한하고 looping을 10으로 제한한 후 이미지 출력은 batch_xs(0) 즉 첫 번째 하나만 출력하기로 한다.

이와 대응하여 선택된 하나의 숫자 이미지 출력을 담당하는 함수 gen_image(arr)을 수정하여 이미지 데이터를 구성하는 데이터 숫자를 구체적으로 출력해 보기로 하자.

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

이 함수에서 784개로 구성되는 어레이 데이터 즉 arr을 28X28 로 reshape 하여 원 데이터를 출력해보기 위해서는 다음의 명령을 two_d 앞에 넣어 실행시켜 보자.

t_d = np.reshape(arr, (28, 28))
print(t_d)

출력 결과 임의로 숫자 “8”이 셈플링되었고 이때의 인식율이 ≅26%로 계산됨과 아울러 이 “8”에 대한 리스트형 그래픽 데이터가 추출되었는데 0.0∼1.0 사이의 값을 가지는 28개의 데이터 세트가 28개 들어있는 것으로 파악된다.



그렇다면 이 데이터를 사용해 28X28 픽셀로 reshape하여 이미지 처리 소프트웨어로 비쥬얼라이제이션 하기 위해서는 784개의 데이타를 reshape 작업을 한 후 각각의 데이터에 256을 곱해 8비트 unsigned 형 정수(uint8)로 처리할 필요가 있다. 물론 이 결과를 matplotlib 라이브러리를 사용하여 imshow() 명령으로 위와 같이 콘솔에서 가시적으로 볼 수도 있으며, imshow 이미지를 간단하게 plt.savefig(‘batch.png’) 명령으로 저장한 후 그림과 같이 그림판 소프트웨어로 관찰해 보는 것도 가능하다.



사이트에 첨부된 파이선 코드를 아나콘다 스파이더에서 실행해 보자. 파이선 코드의 설명을 위한 코멘트 기호가 샤프인 관계로 코드를 올리면 해당라인의 글자 폰트가 크게 출력되는데 사용자가 가져다 실행하기 전에 원래의 샤프 기호로 복원할 필요성이 있다.






//mnist_02.py

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

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

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

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


def gen_image(arr):
    t_d = np.reshape(arr, (28, 28))
    print(t_d)
    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
    plt.imshow(two_d, interpolation='nearest')
    plt.savefig('batch.png')
    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(1)
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}))