Tensorflow 모델을 저장하고로드하면 Keras 오류가 발생합니다.

Aug 20 2020

작업중인 프로젝트의 경우 밀도가 높은 피처 레이어와 3 개의 밀도 레이어로 구성된 간단한 모델을 TensorFlow에서 만들었습니다.

def build_model(arguments):
    model = tf.keras.Sequential([
        tf.keras.layers.DenseFeatures(arguments),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dense(128, activation='relu'),
        tf.keras.layers.Dense(5, activation='sigmoid')
    ])
    
    return model

매개 변수에 대해 더 자세히 설명 할 수는 arguments없지만 위의 모델 함수는 완벽하게 작동 .h5하며 아래 코드를 사용하여 완벽하게 파일을 훈련하고 저장할 수 있습니다.

    # Create a path for the saving location of the model
    model_dir = log_dir + "\model.h5"

    # Save the model
    model.save(model_dir)

그러나 .h5파일 에서 모델을 다시로드하려고하면

model = tf.keras.models.load_model(model_path)

다음과 같은 오류 메시지가 나타납니다.

  File "sampleModel.py", line 342, in <module>
    model = tf.keras.models.load_model(model_path)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\saving\save.py", line 1
82, in load_model
    return hdf5_format.load_model_from_hdf5(filepath, custom_objects, c
ompile)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\saving\hdf5_format.py",
 line 178, in load_model_from_hdf5
    custom_objects=custom_objects)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\saving\model_config.py"
, line 55, in model_from_config
    return deserialize(config, custom_objects=custom_objects)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\layers\serialization.py
", line 175, in deserialize
    printable_module_name='layer')
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\utils\generic_utils.py"
, line 358, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\engine\sequential.py",
line 487, in from_config
    custom_objects=custom_objects)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\layers\serialization.py
", line 175, in deserialize
    printable_module_name='layer')
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\utils\generic_utils.py"
, line 358, in deserialize_keras_object
    list(custom_objects.items())))
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\keras\feature_column\base_fea
ture_layer.py", line 141, in from_config
    config['feature_columns'], custom_objects=custom_objects)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\feature_column\serialization.
py", line 186, in deserialize_feature_columns
    for c in configs
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\feature_column\serialization.
py", line 186, in <listcomp>
    for c in configs
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\feature_column\serialization.
py", line 138, in deserialize_feature_column
    columns_by_name=columns_by_name)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\feature_column\feature_column
_v2.py", line 2622, in from_config
    config['normalizer_fn'], custom_objects=custom_objects)
  File "C:\WINDOWS\system32\config\systemprofile\AppData\Roaming\Python
\Python37\site-packages\tensorflow\python\feature_column\serialization.
py", line 273, in _deserialize_keras_object
    obj = module_objects.get(object_name)
AttributeError: 'NoneType' object has no attribute 'get'

주위를 둘러 보면 함수 의 custom_objects태그 와 관련이 있다고 생각 load_model하지만 구현 방법을 100 % 확신하지 못합니다.

답변

John Aug 21 2020 at 20:55

이 링크 시도 https://github.com/keras-team/keras/issues/11418

사용하여 문제를 해결하는 것 같은 ethanfowler의 답변이 있습니다. custom_objects

AaronJones Sep 05 2020 at 01:54

좀 더 둘러보고 Github 문제를 파헤친 후 문제를 해결했다고 생각합니다. 특정 상황에서는 가중치 만 저장하는 것이 아니라 전체 모델을 저장할 필요가 없었습니다. 내 구성을 위해 Tensorflow 2.3.0 및 Keras 2.4.3을 사용하고 있습니다.

짧은 답변:

최소 한 시대에 모델을 맞춘 다음 가중치를로드합니다.

긴 답변 :

가중치를 저장하려면 그 위에 모델 파일 경로가 추가 된 다음 함수를 사용합니다.

# Create a path for the saving location of the model
model_dir = dir_path + '/model.h5'

# Save the model
model.save_weights(model_dir)

먼저 위의 질문에서 모델을 만들고 모델 개체에 저장합니다.

model = build_model(arguments)

손실 함수와 최적화 프로그램을 추가 한 다음 모델을 컴파일하여 가중치를로드하기 전에 모든 관련 기능이 있는지 확인합니다.

loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    
#Declare and set the parametors of the optimizer
optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, decay=0.001)
    
#Compile the model
model.compile(loss=loss_object, optimizer=optimizer, metrics=['accuracy'])

나는 여기이 줄에서 내 대답을 찾았 지만 맨 아래에는 가중치를로드하기 전에 1 epoch 동안 모델을 맞추라고 말합니다.

history = model.fit(test_data, batch_size=1, epochs=1)

그 후에 아래 함수를 사용하여 가중치를 잘로드 할 수 있습니다.

model.load_weights(model_path)