





import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
# 1. 데이터셋 로드 및 분할
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
print("Train Images:", train_images.shape)
print("Train Labels:", train_labels.shape)
print("Test Images:", test_images.shape)
print("Test Labels:", test_labels.shape)
# 클래스 이름 정의
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# 2. 일부 이미지 시각화
plt.figure(figsize=(15,15))
plt.subplots_adjust(hspace=1)
for idx in range(20):
plt.subplot(5, 5, idx+1)
plt.imshow(train_images[idx])
plt.title(class_names[train_labels[idx]])
plt.show()
# 3. 한 이미지 보기 (컬러바 포함)
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()
# 4. 이미지 전처리 (정규화)
train_images = train_images / 255.0
test_images = test_images / 255.0
# 5. 정규화된 이미지 확인
plt.figure(figsize=(10,8))
for i in range(20):
plt.subplot(4,5,i+1)
plt.xticks([])
plt.yticks([])
plt.grid(False)
plt.imshow(train_images[i], cmap=plt.cm.binary)
plt.xlabel(class_names[train_labels[i]])
plt.show()
# 6. 모델 구성
model = keras.Sequential([
keras.layers.Flatten(input_shape=(28,28)), # 28x28 입력을 784 벡터로 변환
keras.layers.Dense(128, activation='relu'), # 은닉층
keras.layers.Dense(10, activation='softmax') # 출력층
])
model.summary()
# 7. 모델 컴파일
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
# 8. 모델 학습
model.fit(train_images, train_labels, epochs=20)
# 9. 예측 수행
predictions = model.predict(test_images)
# 10. 예측 결과 확인 (첫 번째 테스트 이미지)
print("예측 확률:", predictions[0])
print("예측 클래스:", np.argmax(predictions[0]))
print("실제 정답:", test_labels[0])
# 11. 시각화 함수 정의
def plot_image(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
plt.imshow(img, cmap=plt.cm.binary)
predicted_label = np.argmax(predictions_array)
color = 'blue' if predicted_label == true_label else 'red'
plt.xlabel(f"{class_names[predicted_label]} {100*np.max(predictions_array):2.0f}% "
f"({class_names[true_label]})", color=color)
def plot_value_array(i, predictions_array, true_label):
predictions_array, true_label = predictions_array[i], true_label[i]
plt.grid(False)
plt.xticks([])
plt.yticks([])
bar_plot = plt.bar(range(10), predictions_array, color="#777777")
plt.ylim([0, 1])
predicted_label = np.argmax(predictions_array)
bar_plot[predicted_label].set_color('red')
bar_plot[true_label].set_color('blue')
# 12. 여러 예측 결과 시각화
num_rows = 5
num_cols = 3
num_images = num_rows * num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
plt.subplot(num_rows, 2*num_cols, 2*i+1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(num_rows, 2*num_cols, 2*i+2)
plot_value_array(i, predictions, test_labels)
plt.show()
# 13. 정확도 평가
predicted_labels = tf.argmax(predictions, axis=-1).numpy()
acc = accuracy_score(predicted_labels, test_labels)
print(f"Accuracy score: {acc:.4f}")


