[tensorflow2.x 기초 - 6] MNIST data로 Evaluation & Prediction을 구현기본

2020. 9. 1. 17:10DL in Python/Tensorflow2.x 기초

 

 

 

 

 

TensorFlow: Evaluating & Prediction

In [1]:
import tensorflow as tf
from tensorflow.keras import layers

from tensorflow.keras import datasets 
 

Build Model

In [2]:
input_shape = (28, 28, 1)
num_classes = 10

learning_rate = 0.001
In [3]:
inputs = layers.Input(input_shape)
net = layers.Conv2D(32, (3, 3), padding='SAME')(inputs)
net = layers.Activation('relu')(net)
net = layers.Conv2D(32, (3, 3), padding='SAME')(net)
net = layers.Activation('relu')(net)
net = layers.MaxPooling2D(pool_size=(2, 2))(net)
net = layers.Dropout(0.5)(net)

net = layers.Conv2D(64, (3, 3), padding='SAME')(net)
net = layers.Activation('relu')(net)
net = layers.Conv2D(64, (3, 3), padding='SAME')(net)
net = layers.Activation('relu')(net)
net = layers.MaxPooling2D(pool_size=(2, 2))(net)
net = layers.Dropout(0.5)(net)

net = layers.Flatten()(net)
net = layers.Dense(512)(net)
net = layers.Activation('relu')(net)
net = layers.Dropout(0.5)(net)
net = layers.Dense(num_classes)(net)
net = layers.Activation('softmax')(net)

model = tf.keras.Model(inputs=inputs, outputs=net, name='Basic_CNN')
In [4]:
# Model is the full model w/o custom layers
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate),
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
 

Preprocess

 

데이터셋 불러오기

In [5]:
(train_x, train_y), (test_x, test_y) = datasets.mnist.load_data()
In [6]:
train_x = train_x[..., tf.newaxis]
test_x = test_x[..., tf.newaxis]

train_x = train_x / 255.
test_x = test_x / 255.
 

Training

In [7]:
num_epochs = 1
batch_size = 64
In [8]:
hist = model.fit(train_x, train_y, 
                 batch_size=batch_size, 
                 shuffle=True)
 
938/938 [==============================] - 132s 141ms/step - loss: 0.2164 - accuracy: 0.9312
In [25]:
hist.history
Out[25]:
{'loss': [0.21658981240888436], 'accuracy': [0.931]}
 

Evaluating

  • 학습한 모델 확인
In [9]:
model.evaluate(test_x, test_y, batch_size = batch_size)
 
157/157 [==============================] - 5s 31ms/step - loss: 0.0444 - accuracy: 0.9860
Out[9]:
[0.044350724667310715, 0.9860000014305115]
 

결과 확인

 

Input으로 들어갈 이미지 데이터 확인

In [10]:
import matplotlib.pyplot as plt

import numpy as np

%matplotlib inline
In [11]:
test_image = test_x[0,:,:,0]
test_image.shape
Out[11]:
(28, 28)
In [12]:
plt.title(test_y[0])
plt.imshow(test_image,'gray')
plt.show()
 
 
  • 모델에 Input Data로 확인 할 이미지 데이터 넣기
In [13]:
pred = model.predict(test_image.reshape(1,28,28,1))
In [14]:
pred.shape
Out[14]:
(1, 10)
In [16]:
pred  # softmax를 거친 각 레이블별 확률
      # 가장 높은 값을 가진 레이블이 예측된 정답
Out[16]:
array([[7.9267153e-09, 1.5796324e-07, 5.4426841e-06, 2.7217495e-05,
        1.0247860e-08, 4.9534464e-08, 3.9703126e-11, 9.9994802e-01,
        1.8639984e-08, 1.9035480e-05]], dtype=float32)
 
  • np.argmax
In [17]:
np.argmax(pred)
Out[17]:
7
 

Test Batch

 

Batch로 Test Dataset 넣기

In [18]:
test_batch = test_x[:32]
test_batch.shape
Out[18]:
(32, 28, 28, 1)
 

Batch Test Dataset 모델에 넣기

In [20]:
preds = model.predict(test_batch)
preds.shape
Out[20]:
(32, 10)
 
  • 결과 확인
In [23]:
np.argmax(preds).shape
np.argmax(preds,-1).shape
np.argmax(preds,-1)
Out[23]:
array([7, 2, 1, 0, 4, 1, 4, 9, 5, 9, 0, 6, 9, 0, 1, 5, 9, 7, 3, 4, 9, 6,
       6, 5, 4, 0, 7, 4, 0, 1, 3, 1], dtype=int64)
In [25]:
plt.imshow(test_batch[1,:,:,0],'gray')
plt.show()
 
In [ ]: