필요 모듈 설정

import tensorflow as tf
import keras
import numpy as np
from matplotlib import pyplot as plt
from keras.datasets import mnist
from keras import models, layers
from keras.utils import to_categorical

mnist 데이터 불러오기

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

mnist 데이터 확인하기

print(train_images.shape)
print(train_labels)
print(test_images.shape)
print(test_labels)

예측 확인용 체크 이미지 저장 하기

check_image = test_images[24]

Keras 모델 만들기

model = models.Sequential()
model.add(layers.Dense(512, activation='relu', input_shape=(28*28, )))
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(128, activation='relu'))
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))

만든 모델 구조 확인하기

from keras.utils import plot_model
plot_model(model, show_shapes=True)

모델 컴파일 하기

model.compile(optimizer = 'rmsprop',
              loss = 'categorical_crossentropy',
              metrics = ['accuracy'])

이미지 모양 바꿔주기

train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32')/255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

모델 학습하기

model.fit(train_images, train_labels, epochs=5, batch_size=128)

모델 Cost 및 loss 값 확인하기

test_loss, test_acc = model.evaluate(test_images, test_labels)
print(test_loss, test_acc)

예측 확인용 체크 이미지 확인하기

plt.imshow(check_image, cmap = plt.cm.binary)

예측 확인용 체크 이미지 모델에 넣고 예측하기

checking_img = check_image.reshape((1, 28*28))
output = model.predict(checking_img)
print(np.argmax(output))

 

반응형

+ Recent posts