import tensorflow as tf
from tensorflow import keras
import warnings
warnings.filterwarnings('ignore')
# Helper libraries
# numpy와 matplotlib을 사용한다.
import numpy as np
import matplotlib.pyplot as plt
# jupyter notebook에서 matplotlib을 사용하기 위한 매직커맨드
%matplotlib inline
print("사용되는 tensorflow의 버전:",tf.__version__)
사용되는 tensorflow의 버전: 2.9.1
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
신버전 사용시 발생하는 오류 제어
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
train_labels
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
train_images.shape
(60000, 28, 28)
test_images.shape
(10000, 28, 28)
# matplotlib을 통해 그림을 그린다.
plt.figure()
# train_images의 첫번째 요소를 그린다.
plt.imshow(train_images[0])
plt.colorbar()
# 점자선을 False로 둠으로써 없앤다.
plt.gca().grid(False)
train_images = train_images / 255.0
test_images = test_images / 255.0
# matplotlib을 통해 그림을 그린다.
plt.figure()
# train_images의 첫번째 요소를 그린다.
plt.imshow(train_images[0])
plt.colorbar()
# 점자선을 False로 둠으로써 없앤다.
plt.gca().grid(False)
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(10, activation=tf.nn.softmax)
])
model.compile(optimizer=tf.train.AdamOptimizer(),
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
Train on 60000 samples
Epoch 1/5
60000/60000 [==============================] - 2s 40us/sample - loss: 0.5039 - acc: 0.8234
Epoch 2/5
60000/60000 [==============================] - 3s 43us/sample - loss: 0.3801 - acc: 0.8628
Epoch 3/5
60000/60000 [==============================] - 2s 39us/sample - loss: 0.3401 - acc: 0.8767
Epoch 4/5
60000/60000 [==============================] - 2s 40us/sample - loss: 0.3163 - acc: 0.8842
Epoch 5/5
60000/60000 [==============================] - 2s 41us/sample - loss: 0.2975 - acc: 0.8910
<keras.callbacks.History at 0x1f8446a3b20>
test_loss, test_acc = model.evaluate(test_images, test_labels)
print('Test accuracy:', test_acc)
Test accuracy: 0.8663
predictions = model.predict(test_images)
predictions[0]
array([1.6646754e-06, 4.6912991e-08, 1.9488364e-06, 2.4025017e-08,
6.5531931e-06, 5.9902354e-04, 1.7164682e-06, 1.0812764e-02,
2.1776802e-06, 9.8857415e-01], dtype=float32)
np.argmax(predictions[0])
9
test_labels[0]
9
plt.figure(figsize=(10,10))
for i in range(25):
plt.subplot(5,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid('off')
plt.imshow(test_images[i], cmap=plt.cm.binary)
# predictions에서 가장 큰 값을 predicted_label 로 가져온다.
predicted_label = np.argmax(predictions[i])
true_label = test_labels[i]
# 이때 실제 test_label과 일치하면 초록색 글씨로,
if predicted_label == true_label:
color = 'green'
# 일치하지 않으면 빨간색 글씨로 출력한다.
else:
color = 'red'
plt.xlabel("{} ({})".format(class_names[predicted_label],
class_names[true_label]),
color=color)