import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt
# MNIST ๋ฐ์ดํฐ์
๋ก๋
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
# ๋ฐ์ดํฐ ์ ์ฒ๋ฆฌ
train_images = train_images.reshape((60000, 28 * 28)).astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28)).astype('float32') / 255
# ๋ชจ๋ธ ์์ฑ
model = models.Sequential([
layers.Dense(128, activation='relu', input_shape=(28 * 28,)),
layers.Dropout(0.2),
layers.Dense(10, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# ๋ชจ๋ธ ํ๋ จ
model.fit(train_images, train_labels, epochs=5)
# ๋ชจ๋ธ ํ๊ฐ
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest Accuracy: {test_acc * 100:.2f} %')
# ์์ธก ์ํ
predictions = model.predict(test_images)
predicted_labels = [tf.argmax(p).numpy() for p in predictions]
# ์ด๋ฏธ์ง ํ์
plt.figure(figsize=(9, 9))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(test_images[i].reshape(28, 28), cmap=plt.cm.binary) # ์ด๋ฏธ์ง๋ฅผ 2D๋ก ๋ณํ
plt.xlabel(f"Real: {test_labels[i]} - Pred: {predicted_labels[i]}")
plt.show()