티스토리 뷰
오늘은 유명한 Tensorflow 예제 'MNIST for beginner'를 해 보겠습니다.
이 예제는 28X28 Dotmatrix의 숫자 이미지를 학습시켜 그림을 보여주고 이게 숫자 몇인지 맞추는 것 입니다.
이미지의 각 Dot는 0~255까지의 숫자로 나뉘어 있고
0은 하얀색,255는 검정색을 나타내고 그 사이는 그 중간의 밝기가 됩니다.
실행 방법은 아래 링크에 자세히 나와있습니다.
https://www.tensorflow.org/tutorials/mnist/beginners/
일단 실행 코드는 아래와 같습니다.
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
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])
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)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
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}))
실행 결과는 아래와 같습니다.
19줄로 학습을 시키고 결과까지 볼수 있으니 참 좋습니다.
게다가 정확도도 91.78%이고요
한 줄씩 따라가 보겠습니다.
from tensorflow.examples.tutorials.mnist import input_data
input_data module을 import 합니다.
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
이 코드는 현재 코드가 실행되는 폴더에 MNIST_data 폴더를 생성하고 압축을 풀어 줍니다.
그리고 mnist 변수에 데이터를 저장합니다.
우리가 지금 학습 시키는 모델의 구조는 아래와 같습니다.
결과(Y)는 One Hot encoding으로
[1,0,0,0,0,0,0,0,0,0] 이면 0을 나타내고
[0,1,0,0,0,0,0,0,0,0] 이면 1을 나타내는 식 입니다.
x = tf.placeholder(tf.float32, [None, 784])
그림 숫자 X 그림의 Dot 숫자로 입력 데이터가 저장될 공간을 생성 해 줍니다.
28*28 이어서 784의 공간이 필요하고
None으로 설정한 곳은 그림의 숫자가 아직 확정되지 않았기 때문 입니다.
W = tf.Variable(tf.zeros([784, 10]))
이 모델에서는 1층짜리 full connected layer를 사용하고 출력이 10개 이므로
input 하나마다 10개의 weight가 필요합니다.
그래서 Input숫자 X Output 숫자 의 배열이 Weight로 필요합니다.
b = tf.Variable(tf.zeros([10]))
Bias는 Output의 숫자 만큼만 필요하므로 10개가 필요합니다.
y = tf.nn.softmax(tf.matmul(x, W) + b)
y 는 출력으로 해당 Matrix의 행렬곱에 Bias를 더한 값을 Softmax 함수를 취한 결과 입니다.
input과 Weight 행렬곱 연산의 결과로
[1,784]*[784,10] =>[1,10] 의 행렬이 생기고
여기에 bias [1,10]을 더해줍니다.
그리고 이 결과에 Softmax를 취해 줍니다.
y_ = tf.placeholder(tf.float32, [None, 10])
sess = tf.Session()
sess.run(init)
Session을 생성하고 이를 실행합니다.
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
train data set에서 100개의 그림을 랜덤하게 가져와서 batch_xs에 이미지를, batch_ys 에 Label을 넣습니다.
그리고 Cross_entropy가 줄어드는 방향으로 학습시키는 것을
1000번 반복합니다.
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
예측이 맞으면 true, 틀리면 false로 만들어내고
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
이것을 평균내서 정확도를 측정합니다.
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
'Tensorflow Step By Step' 카테고리의 다른 글
Tensorflow CSV File Read 1 (0) | 2017.02.16 |
---|---|
Tensorboard 사용하기 2 (0) | 2017.02.12 |
Tensorboard 사용하기 1 (5) | 2017.02.12 |
Windows Tensorflow 환경 구축 2 (Tensorflow 설치) (3) | 2017.01.26 |
Windows Tensorflow 환경 구축 1 (Anaconda 설치) (1) | 2017.01.26 |
- Total
- Today
- Yesterday