-
keras-1 mnist딥러닝/keras 2023. 5. 23. 16:47
1. python
import keras keras.__version__ 2.12.0
케라스를 불러온다.
from keras.datasets import mnist (train_images,train_labels),(test_images,test_labels) = mnist.load_data() train_images.shape (60000, 28, 28) test_images.shape (10000, 28, 28)
케라스에 내장된 손글씨 데이터인 mnist를 불러온다.
import matplotlib.pyplot as plt digit = train_images[4] plt.imshow(digit, cmap=plt.cm.binary)
숫자[4]를 그릴 수 있다.
from keras import models from keras import layers network = models.Sequential() network.add(layers.Dense(512,activation='relu',input_shape=(28*28,))) network.add(layers.Dense(10,activation='softmax')) network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
sequential()을 사용하여 레이어를 붙여줄 수 있다. 28*28픽셀의 렐루를 가진 한 개의 신경망과 다중 분류를 위한 소프트 맥스를 가진 한 개의 신경망을 만든다. 손실함수와 옵티마이저, 메트릭을 지정한다.
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)
라벨 값이 원핫 인코딩 형태를 가지기 위하여 categorical으로 바꿔준다.
network.fit(train_images, train_labels, epochs=5, batch_size=128) Epoch 1/5 469/469 [==============================] - 8s 14ms/step - loss: 0.2643 - accuracy: 0.9236 Epoch 2/5 469/469 [==============================] - 6s 13ms/step - loss: 0.1067 - accuracy: 0.9683 Epoch 3/5 469/469 [==============================] - 6s 14ms/step - loss: 0.0707 - accuracy: 0.9790 Epoch 4/5 469/469 [==============================] - 6s 13ms/step - loss: 0.0511 - accuracy: 0.9850 Epoch 5/5 469/469 [==============================] - 6s 12ms/step - loss: 0.0388 - accuracy: 0.9885
fit으로 학습한다.
test_loss, test_acc = network.evaluate(test_images, test_labels) print('test acc:', test_acc) 313/313 [==============================] - 3s 8ms/step - loss: 0.0637 - accuracy: 0.9803 test acc: 0.9803000092506409
테스트를 하면 잘 작동한다.
'딥러닝 > keras' 카테고리의 다른 글
keras-6 cnn (0) 2023.05.29 keras-5 boston (0) 2023.05.29 keras-3 reuter (0) 2023.05.29 keras-2 imdb (0) 2023.05.23