공유자료 HOME > 자료실 > 공유자료
 
[PYTHON] MNIST 이미지 판정하는 CNN 파이선
관리자 19-10-23 11:19 144

from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()


print(train_images.shape)  # (60000, 28, 28)
print(test_images.shape)   # (10000, 28, 28)


print(len(train_labels))  # 60000
print(len(test_labels))  # 10000


train_labels    # array([5, 0, 4, ..., 5, 6, 8], dtype=uint8)
test_labels    # array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)


from keras import models
from keras import layers
network = models.Sequential()                               # 모델 초기화


# 은닉층 설정. Data shape가 28*28이므로 이에 맞추어 input_shape를 넣는다
network.add(layers.Dense(512, activation='relu', input_shape=(28*28,)))


# 출력층 설정. 10개 각각에 대한 확률정보 출력. Softmax 층은 확률 점수를 출력한다
network.add(layers.Dense(10, activation='softmax'))

network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
print(train_images[0,])


## reshape하기
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


## 판별을 하려면 종속변수가 명목변수가 되어야 함
from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)


## 학습하기
network.fit(train_images, train_labels, epochs=5, batch_size=128)


## 학습된 모델을 가지고 예측하기
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)