# Keras에서 MNIST 데이터 세트를 가져옴.
import tensorflow as tf
from keras.datasets import mnist
(x_Train, y_Train), (x_Test, y_Test) = mnist.load_data()

# 데이터 준비하기
print((x_Train.shape, y_Train.shape, x_Test.shape, y_Test.shape))

# 데이터 확인하기
import matplotlib.pyplot as plt
plt.imshow(x_Train[0], cmap='Greys')
plt.show()

# 컴퓨터에서는 이미지를 픽셀 단위로 인식
for row in x_Train[0]:
    for pixel in row:
        print('%4d' %pixel, end='')
    print()

# 데이터 정규화
x_Train = x_Train.reshape(-1, 28*28) / 255.0
x_Test = x_Test.reshape(-1, 28*28) / 255.0

# 딥러닝 모델 구축
model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(120, activation = 'relu', input_shape=(28*28,)),
    tf.keras.layers.Dense(10, activation = 'softmax')
])

# 딥러닝 학습 환경 구성하기
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 딥러닝 모델 학습
model.fit(x_Train, y_Train, epochs=5, batch_size=32, validation_split=0.2)

# 모델 평가
loss, accuracy = model.evaluate(x_Test, y_Test)
print('Test loss:', loss)
print('Test accuracy:', accuracy)

# 모델 저장
model.save('my_model.h5')
print("모델이 저장되었습니다.")