keras调用load_model时报错ValueError: Unknown Layer:LayerName, ValueError: Unknown metric function:recall

出现该错误原因

因为保存的model中包含了自定义的层(Custom Layer),导致加载模型的时候无法解析该Layer。
参考can not load_model() if my model contains my own Layer

解决方法

在load_model函数中添加custom_objects参数,该参数接受一个字典,键值为自定义的层:

model = load_model(model_path, custom_objects={'AttLayer': AttLayer})  # 假设自定义的层的名字为AttLayer

若添加该语句后不报错则解决问题。
若出现新的Error:init() got an unexpected keyword argument ‘name’
If you use custom args for your model, then implement get_config() method. It would help you save all necessary arguments with your model.
解决该Error,可以参照keras-team的写法,在自定义的层中添加get_config函数,该函数定义形如:

def get_config(self):    
    config = {
        'attention_dim': self.attention_dim    
    }    
    base_config = super(AttLayer, self).get_config()    
    return dict(list(base_config.items()) + list(config.items()))

其中,config中定义的属性是自定义层中__init__函数的参数,__init__函数如下:

def __init__(self, attention_dim, **kwargs):    
    self.init = initializers.get('normal')    
    self.supports_masking = True    
    self.attention_dim = attention_dim    
    super(AttLayer, self).__init__()

注意:
1、__init__函数中需添加**kwargs参数

2、只需要将__init__函数的参数写入config属性中,__init__函数体中的内容不必加进去,get_config函数其他部分也无需改动,否则会报错

原文:https://blog.csdn.net/larry233/article/details/88569797

keras 自定义评估函数和损失函数loss训练模型后加载模型出现ValueError: Unknown metric function:precision,recall

有时候训练模型,现有的评估函数并不足以科学的评估模型的好坏,这时候就需要自定义一些评估函数,比如样本分布不均衡是准确率accuracy评估无法判定一个模型的好坏,这时候需要引入精确度和召回率作为评估标准,不幸的是keras没有这些评估函数。以下是参考别的文章摘取的两个自定义评估函数

召回率:

def recall(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
    recall = true_positives / (possible_positives + K.epsilon())
    return recall

精确度:

def precision(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

自定义了评估函数,一般在编译模型阶段加入即可:

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy', precision, recall])

自定义了损失函数focal_loss一般也在编译阶段加入:

 model.compile(optimizer=Adam(lr=0.0001), loss=[focal_loss], metrics=['accuracy',fbeta_score] )

其他的没有特别要注意的点,直接按照原来的思路训练一版模型出来就好了,关键的地方在于加载模型这里,自定义的函数需要特殊的加载方式,不然会出现加载没有自定义函数的问题:ValueError: Unknown loss function:focal_loss

解决方案:

model_name = 'test_calssification_model.h5'
model_dfcw = load_model(model_name,
                        custom_objects={'precision: precision,'recall':recall,'fbeta_score':fbeta_score, 'focal_loss':focal_loss})

注意点:将自定义的损失函数和评估函数都加入到custom_objects里,以上就是在自定义一个损失函数从编译模型阶段到加载模型阶段出现的所有的问题。

原文:https://blog.csdn.net/aojue1109/article/details/88058965

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章