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