건조젤리의 저장소

7-4. Tensorflow를 이용한 MNIST 실습 본문

공부 기록/모두를 위한 딥러닝 (Basic)

7-4. Tensorflow를 이용한 MNIST 실습

건조젤리 2019. 11. 7. 21:49

김성훈 교수님의 강의내용을 정리한 내용입니다.

출처 : http://hunkim.github.io/ml/

 

모두를 위한 머신러닝/딥러닝 강의

 

hunkim.github.io


MNIST데이터는 손글씨 숫자 데이터로 위와 같은 학습/테스트 세트로 구성되어있다.

하나의 손글씨는 784개의 픽셀로 이루어져있다.

이 데이터를 받을 수 있는 placeholder를 선언하자.

MNIST 데이터 세트는 텐서플로에서 제공된다.

 

텐서플로를 이용해 계산할때 Session.run을 이용하는 대신 eval을 사용할 수 있다.

 

  • epoch: 데이터 세트를 몇번 학습할지
  • batch size: 한번에 학습시키는 데이터의 양

랜덤한 데이터로 테스트 및 확인

 


텐서플로우 상위버전에서는 위의 코드를 실행시키는데 어려움이 있다.

(Mnist data 불러오기, next_batch 등 여러 함수들이 없어졌음)

 

따라서 아래의 코드를 이용하자.

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import tensorflow as tf
import matplotlib.pyplot as plt
import random
 
tf.set_random_seed(777)  # for reproducibility
 
data_train, data_test = tf.keras.datasets.mnist.load_data()
 
# Parse images and labels
(images_train, labels_train) = data_train
images_train = images_train.reshape([-1,28*28])/255
labels_train = tf.keras.utils.to_categorical(labels_train,10)
train_dataset = tf.data.Dataset.from_tensor_slices((images_train, labels_train))
 
(images_test, labels_test) = data_test
images_test = images_test.reshape([-1,28*28])/255
labels_test = tf.keras.utils.to_categorical(labels_test,10)
 
nb_classes = 10
 
# MNIST data image of shape 28 * 28 = 784
= tf.placeholder(tf.float32, [None, 784])
# 0 - 9 digits recognition = 10 classes
= tf.placeholder(tf.float32, [None, nb_classes])
 
= tf.Variable(tf.random_normal([784, nb_classes]))
= tf.Variable(tf.random_normal([nb_classes]))
 
# Hypothesis (using softmax)
hypothesis = tf.nn.softmax(tf.matmul(X, W) + b)
 
cost = tf.reduce_mean(-tf.reduce_sum(Y * tf.log(hypothesis), axis=1))
train = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(cost)
 
# Test model
is_correct = tf.equal(tf.argmax(hypothesis, 1), tf.argmax(Y, 1))
# Calculate accuracy
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
 
# parameters
num_epochs = 15
batch_size = 100
num_iterations = int(len(labels_train) / batch_size)
 
train_dataset = train_dataset.repeat().batch(batch_size).prefetch(1)
train_iterator = train_dataset.make_one_shot_iterator()
next_batch_train = train_iterator.get_next()
 
with tf.Session() as sess:
    # Initialize TensorFlow variables
    sess.run(tf.global_variables_initializer())
    # Training cycle
    for epoch in range(num_epochs):
        avg_cost = 0
 
        for i in range(num_iterations):
            batch_xs, batch_ys = sess.run(next_batch_train)
            _, cost_val = sess.run([train, cost], feed_dict={X: batch_xs, Y: batch_ys})
            avg_cost += cost_val / num_iterations
 
        print("Epoch: {:04d}, Cost: {:.9f}".format(epoch + 1, avg_cost))
 
    print("Learning finished")
 
    # Test the model using test sets
    print(
        "Accuracy: ",
        accuracy.eval(
            session=sess, feed_dict={X: images_test, Y: labels_test}
        ),
    )
 
    # Get one and predict
    r = random.randint(0len(labels_test) - 1)
    print("Label: ", sess.run(tf.argmax(labels_test[r : r + 1], 1)))
    print(
        "Prediction: ",
        sess.run(tf.argmax(hypothesis, 1), feed_dict={X: images_test[r : r + 1]}),
    )
 
    plt.imshow(
        images_test[r : r + 1].reshape(2828),
        cmap="Greys",
        interpolation="nearest",
    )
    plt.show()
cs

참고 블로그 : https://hiseon.me/data-analytics/tensorflow/tensorflow-dataset/

Comments