■ 학습 모델을 저장하는 방법을 보여준다.
▶ 예제 코드 (PY)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
import keras.datasets.mnist as mnist import keras.layers as layers import keras.models as models import keras.utils.np_utils as np_utils import numpy as np np.random.seed(3) # 데이터를 로드한다. (trainInputNDArray, trainCorrectOutputNDArray), (testInputNDArray, testCorrectOutputNDArray) = mnist.load_data() # 훈련 데이터에서 검증 데이터와 훈련 데이터를 나눈다. validationInputNDArray = trainInputNDArray[50000:] validationCorrectOutputNDArray = trainCorrectOutputNDArray[50000:] trainInputNDArray = trainInputNDArray[:50000] trainCorrectOutputNDArray = trainCorrectOutputNDArray[:50000] # 데이터셋 전처리 trainInputNDArray = trainInputNDArray.reshape(50000, 784).astype("float32") / 255.0 validationInputNDArray = validationInputNDArray.reshape(10000, 784).astype("float32") / 255.0 testInputNDArray = testInputNDArray.reshape(10000, 784).astype("float32") / 255.0 # 훈련/검증 데이터를 랜덤하게 섞는다. randomTrainIndexNDArray = np.random.choice(50000, 700) trainInputNDArray = trainInputNDArray[randomTrainIndexNDArray] trainCorrectOutputNDArray = trainCorrectOutputNDArray[randomTrainIndexNDArray] randomValidationIndexNDArray = np.random.choice(10000, 300) validationInputNDArray = validationInputNDArray[randomValidationIndexNDArray] validationCorrectOutputNDArray = validationCorrectOutputNDArray[randomValidationIndexNDArray] # 정답 데이터를 인코딩 한다. trainCorrectOutputNDArray = np_utils.to_categorical(trainCorrectOutputNDArray) validationCorrectOutputNDArray = np_utils.to_categorical(validationCorrectOutputNDArray) testCorrectOutputNDArray = np_utils.to_categorical(testCorrectOutputNDArray) # 모델을 정의한다. model = models.Sequential() model.add(layers.Dense(units = 64, input_dim = 784, activation = "relu")) model.add(layers.Dense(units = 10, activation = "softmax")) model.compile(loss = "categorical_crossentropy", optimizer = "sgd", metrics = ["accuracy"]) # 모델을 학습시킨다. model.fit(trainInputNDArray, trainCorrectOutputNDArray, epochs = 1000, batch_size = 100, validation_data = (validationInputNDArray, validationCorrectOutputNDArray)) # 학습 과정을 조회한다. evaluateList = model.evaluate(testInputNDArray, testCorrectOutputNDArray, batch_size = 32) print("") print("loss : " + str(evaluateList[0])) print("accuracy : " + str(evaluateList[1])) # 모델을 저장한다. model.save("model.data") |