出現該錯誤原因
因爲保存的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裏,以上就是在自定義一個損失函數從編譯模型階段到加載模型階段出現的所有的問題。