首页 > 解决方案 > ValueError:未知初始化程序:HeNormal

问题描述

我正在构建一个基于 cnn 的情绪检测模型。我在 google colab 上训练了我的模型,并尝试将这些权重加载到我本地的 jupyter 机器中。这样做时,我收到以下错误堆栈:

ValueError                                Traceback (most recent call last)
<ipython-input-9-95fbe8e6b6b2> in <module>
     21 
     22 path = ""
---> 23 model = load_model(path)
     24 
     25 fcc_path = "Tools/haarcascade_frontalface_alt.xml"

<ipython-input-9-95fbe8e6b6b2> in load_model(path)
      9         json_file.close()
     10 
---> 11         model = model_from_json(loaded_model_json)
     12         model.load_weights(path + "model.h5")
     13         print("Loaded model from disk")

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\saving\model_config.py in model_from_json(json_string, custom_objects)
     94   config = json.loads(json_string)
     95   from tensorflow.python.keras.layers import deserialize  # pylint: disable=g-import-not-at-top
---> 96   return deserialize(config, custom_objects=custom_objects)

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\layers\serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    189             custom_objects=dict(
    190                 list(_GLOBAL_CUSTOM_OBJECTS.items()) +
--> 191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
    193         return cls.from_config(cls_config)

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\sequential.py in from_config(cls, config, custom_objects)
    367     for layer_config in layer_configs:
    368       layer = layer_module.deserialize(layer_config,
--> 369                                        custom_objects=custom_objects)
    370       model.add(layer)
    371     if not model.inputs and build_input_shape:

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\layers\serialization.py in deserialize(config, custom_objects)
    100       module_objects=globs,
    101       custom_objects=custom_objects,
--> 102       printable_module_name='layer')

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    191                 list(custom_objects.items())))
    192       with CustomObjectScope(custom_objects):
--> 193         return cls.from_config(cls_config)
    194     else:
    195       # Then `cls` may be a function returning a class.

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py in from_config(cls, config)
    592         A layer instance.
    593     """
--> 594     return cls(**config)
    595 
    596   def compute_output_shape(self, input_shape):

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\layers\convolutional.py in __init__(self, filters, kernel_size, strides, padding, data_format, dilation_rate, activation, use_bias, kernel_initializer, bias_initializer, kernel_regularizer, bias_regularizer, activity_regularizer, kernel_constraint, bias_constraint, **kwargs)
    489         activation=activations.get(activation),
    490         use_bias=use_bias,
--> 491         kernel_initializer=initializers.get(kernel_initializer),
    492         bias_initializer=initializers.get(bias_initializer),
    493         kernel_regularizer=regularizers.get(kernel_regularizer),

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\initializers.py in get(identifier)
    192     return None
    193   if isinstance(identifier, dict):
--> 194     return deserialize(identifier)
    195   elif isinstance(identifier, six.string_types):
    196     identifier = str(identifier)

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\initializers.py in deserialize(config, custom_objects)
    184       module_objects=module_objects,
    185       custom_objects=custom_objects,
--> 186       printable_module_name='initializer')
    187 
    188 

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    178     config = identifier
    179     (cls, cls_config) = class_and_config_for_serialized_keras_object(
--> 180         config, module_objects, custom_objects, printable_module_name)
    181 
    182     if hasattr(cls, 'from_config'):

~\Anaconda3\lib\site-packages\tensorflow_core\python\keras\utils\generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    163     cls = module_objects.get(class_name)
    164     if cls is None:
--> 165       raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    166   return (cls, config['config'])
    167 

ValueError: Unknown initializer: HeNormal

我的代码部分是:

from tensorflow.keras.models import model_from_json
import numpy as np
import cv2

def load_model(path):

    json_file = open(path + 'model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    
    model = model_from_json(loaded_model_json)
    model.load_weights(path + "model.h5")
    print("Loaded model from disk")
    return model
    
def predict_emotion(gray, x, y, w, h):
    face = np.expand_dims(np.expand_dims(np.resize(gray[y:y+w, x:x+h]/255.0, (48, 48)),-1), 0)
    prediction = model.predict([face])

    return(int(np.argmax(prediction)), round(max(prediction[0])*100, 2))
    
path = ""
model = load_model(path)

希望你能找到我的问题的解决方案,在过去的几天里卡在这里。提前致谢。

标签: python-3.xtensorflowkerasdeep-learningconv-neural-network

解决方案


您的推理环境中的 tensorflow/keras 版本似乎与您用来训练模型的版本不同。他们在较新的版本中将 he_normal 更改为 HeNormal。

尝试以下操作,它应该让 tensorflow 引用正确的对象:

HeNormal = tf.keras.initializers.he_normal()
load_model= keras.models.load_model(your_model_path, custom_objects={'HeNormal': HeNormal},compile=False)

推荐阅读