code test

์ˆ˜์ • ๋ชฉ๋ก



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()