첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
유용한 소스 코드가 있으면 icodebroker@naver.com으로 보내주시면 감사합니다.
블로그 자료는 자유롭게 사용하세요.

728x90
반응형

■ 학습 모델 저장하기

------------------------------------------------------------------------------------------------------------------------

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")

------------------------------------------------------------------------------------------------------------------------

728x90
반응형
Posted by 사용자 icodebroker

댓글을 달아 주세요