[TensorFlow 2.0] Evaluating & Prediction

Load Packages

1
2
3
4
import tensorflow as tf
from tensorflow.keras import layers

from tensorflow.keras import datasets

Build Model

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
input_shape = (28, 28, 1)
num_classes = 10
learning_rate = 0.001

inputs = layers.Input(input_shape, dtype=tf.float64)
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')
1
2
3
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

데이터셋 불러오기

1
2
3
4
5
6
7
(train_x, train_y), (test_x, test_y) = datasets.mnist.load_data()

train_x = train_x[..., tf.newaxis]
test_x = test_x[..., tf.newaxis]

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

Training

1
2
3
4
5
6
7
8
9
10
num_epochs = 1
batch_size = 64

hist = model.fit(train_x, train_y,
batch_size=batch_size,
shuffle=True)

# 결과
Train on 60000 samples
60000/60000 [==============================] - 6s 94us/sample - loss: 0.0798 - accuracy: 0.9755
1
2
3
4
hist.history

# 결과
{'loss': [0.07980264157739779], 'accuracy': [0.9755]}

Evaluating

학습한 모델을 확인합니다.

1
2
3
4
model.evaluate(test_x, test_y, batch_size=batch_size)

# 결과
[0.03286817007374484, 0.9888]

결과 확인

Input으로 들어갈 이미지 데이터를 확인한다.

1
2
3
4
5
6
7
8
9
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

test_image = text_x[0, :, :, 0]
test_image.shape

# 결과
(28, 28)
1
2
3
plt.title(test_y[0])
plt.imshow(test_image, 'gray')
plt.show()

모델에 Input Data로 확인 할 이미지 데이터를 넣는다.

1
2
3
4
5
6
7
# 이미지를 보기위해 shape를 바꿨었는데 다시 reshape로 차원을 변경합니다.
pred = model.predict(test_image.reshape(1, 28, 28, 1))

# 결과
array([[2.4227038e-09, 2.3278629e-08, 5.8909092e-07, 1.0298673e-07,
9.4029007e-10, 6.1998517e-11, 1.4364351e-12, 9.9999928e-01,
4.7319365e-10, 4.7449920e-08]], dtype=float32)
1
2
3
4
5
# 배열에서 가장 높은 값의 인덱스를 찾을 때 np.argmax를 사용한다.
np.argmax(pred)

# 결과
7

Test Batch

Batch Test Dataset 모델에 넣는다.

1
2
3
4
5
test_batch = test_x[:32]
test_batch.shape

# 결과
(32, 28, 28, 1)
1
2
3
4
5
preds = model.predict(test_batch)
preds.shape

# 결과
(32, 10)
1
2
3
4
5
6
7
8
9
# -1을 넣으면 하나의 값이 아니라 앞의 32개의 결과를 보여줍니다.
np.argmax(preds, -1)

# 결과
array([7, 2, 1, 0, 4, 1, 4, 9, 5, 9, 0, 6, 9, 0, 1, 5, 9, 7, 5, 4, 9, 6,
6, 5, 4, 0, 7, 4, 0, 1, 3, 1], dtype=int64)

plt.imshow(test_batch[5, :, :, 0], 'gray')
plt.show()

Share