머신러닝

1-11 matplotlib 에 의한 MNIST 수기문자 28X28 픽셀 흑백 그래픽 출력

coding art 2020. 1. 28. 13:01
728x90

 

텐서플로우 1.15.0 버전에서 MNIST 코드를 실행하고 읽어 들인 수기 문자 중의 하나를 matplot 라이브러리를 사용 흑백으로 출력해 보자. 함수 gen_image(arr)에서 arrplaceholder에서 읽어 들이는 1X784 데이터 하나를 arr 로 넘겨주면 28X28 reshape 하여 출력한다. 함수 gen_image(arr)Session 모드에서 불러 사용한다.

 

 

 

placeholder 명령에 의해 읽어 들이는 수기 문자는 1X784 로서 28X28 픽셀로 변환하여 출력하도록 한다. 흑백 출력에서 배경색인 0은 흰색으로 글자에 해당하는 픽셀의 색은 255를 검정색으로 하여 출력된다.

 

 

 

텐서플로우에서는 Session 단계 이전에서는 플로우 챠트에 해당하는 Graph 처리 단계이며 Session 단계에서부터 전역 변수(global_variables)들을 초기화(initialization) 한 후 실제 연산이 수행된다.

mnist.train.next_batch(숫자) 또는 mnist.test.next_batch(숫자) 명령은 train 이나 test 데이터베이스에서 무작위로 숫자만큼 데이터를 샘플링하는 명령이다. 이 명령은 파이섡 명령이라기 보다는 MNIST 문자 데이터베이스를 읽어 내기 위한 특별한 명령으로서 tensorflow 2.0에서는 더 이상 지원이 되지 않으며 대신에 keras 기준으로 데이터베이스를 읽어 들이게끔 바뀌었다.

일반적으로 MNIST 수기문자 판독에서 각 숫자별로 10개씩의 데이터를 포함하는 100 단위 샘플링이 괜찮은 인식률을 보여준다. 튜플로 구성되는 batch_xs 는 픽셀 데이터를, batch_ys One-hot 코드로 처리된 라벨 값이 입력된다.

 

 

 

#mnist_matplotlib_01.py

 

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

def gen_image(arr):
    two_d = (np.reshape(arr, (28, 28)) * 255).astype(np.uint8)
    print(two_d)
    plt.imshow(two_d, cmap='Greys')
    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.placeholder(tf.float32, [None, 10])

learning_rate = 0.1
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
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(5000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    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}))