[keras] model save & load 하는 방법


모델 저장하기

Weights + Model Architecture 각각 저장하는 방법

# Save the weights
model.save_weights("mnist_weights.h5")

# Save the model architecture as json
with open("mnist_architecture.json", "w") as fp:
  fp.write(model.to_json(indent="\t"))

model.save_weights(filepath)

Notes

모델의 가중치 값을 HDF5 파일 형식으로 저장합니다.


model.to_json()

Notes

model architecture만 json 형태로 저장합니다.
가중치는 저장하지 않습니다.
json에서 indent="\t"가 궁금하신 분은
https://daewoonginfo.blogspot.com/2019/04/python-json.html
참조해주시기 바랍니다.



Weights + Model Architecture + Optimizer State 한번에 저장하는 방법

# Creates a single HDF5 file
model.save("mnist_model.h5")

model.save(filepath)

Notes

모델의 Weights, Architecture, Optimizer State를 모두 포함하는 HDF5 파일 형식으로 저장합니다.



모델 불러오기

Weights + Model Architecture 각각 불러오는 방법

from keras.models import model_from_json

# Reconfigure model in json file
with open("mnist_architecture.json", "r") as fp:
  model = model_from_json(fp.read())

# Load weights to new model
model.load_weights("mnist_weights.h5")

model_from_json(model.to_json file)

Notes

json 파일을 읽어와 새로운 model Architecture을 만듭니다.
가중치값은 존재하지 않습니다.


model.load_weights(filepath)

Notes

HDF5 파일(save_weights에서 생성)에서 모델의 가중치를 불러옵니다.
model architecture은 기본적으로 변경되지 않으며
by_name=True라면 다른 model architecture 중 이름이 동일한 layer에만 가중치를 불러옵니다.



Weights + Model Architecture + Optimizer State 한번에 불러오는 방법

from keras.models import load_model

model = load_model("mnist_model.h5")

model.load_model(filepath)

Notes

HDF5 파일(model.save에서 생성)에서 모델의 정보(weights, architecture, optimizer)를 불러옵니다.
compile되지 않은 모델을 저장했다면 optimizer 정보는 존재하지 않습니다.
이럴 경우에는 모델을 load하여 compile 과정을 거쳐야합니다.


참고문헌



댓글

이 블로그의 인기 게시물

[opencv-python] 이미지 크기조절(resize) 하는 법

[python] selenium close와 quit 차이점

[python]파이썬: csv reader header skip (첫번째 행 무시하기, 안읽기)