DL 모델 저장후 다시 불러오기(keras, tensorflow)

<개념>/Deep learning|2021. 8. 14. 12:05
반응형

 

케라스 sequential 로 만든 모델 저장하는법 & 불러오는법

코드 참조 : https://tykimos.github.io/2017/06/10/Model_Save_Load/

참조 :https://mylifemystudy.tistory.com/69

https://ssongnote.tistory.com/12

 

  • 케라스에서 모델 구성하는법
# 0. 사용할 패키지 불러오기
from keras.utils import np_utils
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
from numpy import argmax

# 1. 데이터셋 생성하기

# 훈련셋과 시험셋 불러오기
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# 데이터셋 전처리
x_train = x_train.reshape(60000, 784).astype('float32') / 255.0
x_test = x_test.reshape(10000, 784).astype('float32') / 255.0

# 원핫인코딩 (one-hot encoding) 처리
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)

# 훈련셋과 검증셋 분리
x_val = x_train[:42000] # 훈련셋의 30%를 검증셋으로 사용
x_train = x_train[42000:]
y_val = y_train[:42000] # 훈련셋의 30%를 검증셋으로 사용
y_train = y_train[42000:]

# 2. 모델 구성하기
model = Sequential()
model.add(Dense(units=64, input_dim=28*28, activation='relu'))
model.add(Dense(units=10, activation='softmax'))

# 3. 모델 학습과정 설정하기
model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# 4. 모델 학습시키기
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_data=(x_val, y_val))

# 5. 모델 평가하기
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=32)
print('')
print('loss_and_metrics : ' + str(loss_and_metrics))

# 6. 모델 사용하기
xhat_idx = np.random.choice(x_test.shape[0], 5)
xhat = x_test[xhat_idx]
yhat = model.predict_classes(xhat)

for i in range(5):
    print('True : ' + str(argmax(y_test[xhat_idx[i]])) + ', Predict : ' + str(yhat[i]))
위 코드 관련된 내용

** reshape 관련참조 https://supermemi.tistory.com/12

** utils.to_categorical

** model.compile → optimizer,loss,metrics 지정해줌.

** loss 함수 참조 https://hororolol.tistory.com/375

** train (val , train ) / test 이렇게 나눠짐

** predict vs predict_class

  • predict 의 경우

[[0.22520512],[0.9520419 ],[0.9672848 ],[0.02690617]]

  • predict_classes 의 경우

[[0],[1],[1],[0]]

** argmax

 

Q. 저장한 모델은 어떻게 다시 불러오고 불러온 모델을 어떤식으로 활용하는지
  • 모델을 저장한다. 무엇을 저장하는건지

모델은 1. 모델 아키텍쳐 (모델이 어떤레이어로 쌓여있는지= 즉 모델구성) 2. 모델가중치(처음에는 임의의값으로 초기화되어있지만, 훈련셋으로 학습하면서 갱신됨) 로 이루어짐. 모델을 저장한다는 의미는 이 두개를 저장한다는 말.

  • 위코드를 실행하고나면 ~~.h5 파일이 생김. 여기에 들어있는 정보들은

(1) 모델구성정보 (2) 가중치 (3) 손실함수등등 학습설정(model.compile해준거) (4) 재학습을 할수있도록 마지막 학습상태 들로 구성되어있다.

→ 만약에 (1) 모델구성정보와 (2) 가중치를 따로 각각 저장하고 불러오는 케이스일경우, 모델을 불러온다음, model.compile을 설정해주어야한다.

 

 

Python sklearn 로 만든 모델 저장하는법

참조: https://cocook.tistory.com/46

https://www.python2.net/questions-889925.htm

Tensorflow 만든 모델 저장,불러오는법

TENSORFLOW

model.save()를 호출하면 다음과 같은 파일들이 저장된다.

  • model's architecture/config
  • model's weight values
  • model's compilation information (if compile() was called)
  • optimizer and its state

model.save('my_custom_model')시 저장되는 디렉토리는 다음과 같다.

my_custom_model 
└ assets (dir) 
└ variables (dir) 
└ saved_model.pb (file)

불러올때는 아래처럼 불러오면 된다

model_dnn = load_model('my_custom_model')

 

 

람다에서 불러올때 h5로 불러오면 에러가 나고, pb 형태로만 인식이 되나보다. 변환해주면 됨

**KERAS (.H5)→ Tensorflow (.pb) 형식

https://coredump064.tistory.com/80 참조 (h5→pb)

 

본인이 변환해서 저장한 saved_dnn_model 형태는 파일형태로 다음과 같았다.

saved_dnn_model
ㄴkeras_metadata.pb
ㄴsaved_model.pb
ㄴvariables
ㄴassets

 

 

Uploaded by Notion2Tistory v1.1.0

반응형

댓글()