keras自定義損失函數(shù)并且模型加載的寫法介紹
keras自定義函數(shù)時候,正常在模型里自己寫好自定義的函數(shù),然后在模型編譯的那行代碼里寫上接口即可。如下所示,focal_loss和fbeta_score是我們自己定義的兩個函數(shù),在model.compile加入它們,metrics里‘a(chǎn)ccuracy'是keras自帶的度量函數(shù)。
def focal_loss(): ... return xx def fbeta_score(): ... return yy model.compile(optimizer=Adam(lr=0.0001), loss=[focal_loss],metrics=['accuracy',fbeta_score] )
訓(xùn)練好之后,模型加載也需要再額外加一行,通過load_model里的custom_objects將我們定義的兩個函數(shù)以字典的形式加入就能正常加載模型啦。
weight_path = './weights.h5'
model = load_model(weight_path,custom_objects={'focal_loss': focal_loss,'fbeta_score':fbeta_score})
補充知識:keras如何使用自定義的loss及評價函數(shù)進行訓(xùn)練及預(yù)測
1.有時候訓(xùn)練模型,現(xiàn)有的損失及評估函數(shù)并不足以科學(xué)的訓(xùn)練評估模型,這時候就需要自定義一些損失評估函數(shù),比如focal loss損失函數(shù)及dice評價函數(shù) for unet的訓(xùn)練。
2.在訓(xùn)練建模中導(dǎo)入自定義loss及評估函數(shù)。
#模型編譯時加入自定義loss及評估函數(shù)
model.compile(optimizer = Adam(lr=1e-4), loss=[binary_focal_loss()],
metrics=['accuracy',dice_coef])
#自定義loss及評估函數(shù)
def binary_focal_loss(gamma=2, alpha=0.25):
"""
Binary form of focal loss.
適用于二分類問題的focal loss
focal_loss(p_t) = -alpha_t * (1 - p_t)**gamma * log(p_t)
where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.
References:
https://arxiv.org/pdf/1708.02002.pdf
Usage:
model.compile(loss=[binary_focal_loss(alpha=.25, gamma=2)], metrics=["accuracy"], optimizer=adam)
"""
alpha = tf.constant(alpha, dtype=tf.float32)
gamma = tf.constant(gamma, dtype=tf.float32)
def binary_focal_loss_fixed(y_true, y_pred):
"""
y_true shape need be (None,1)
y_pred need be compute after sigmoid
"""
y_true = tf.cast(y_true, tf.float32)
alpha_t = y_true * alpha + (K.ones_like(y_true) - y_true) * (1 - alpha)
p_t = y_true * y_pred + (K.ones_like(y_true) - y_true) * (K.ones_like(y_true) - y_pred) + K.epsilon()
focal_loss = - alpha_t * K.pow((K.ones_like(y_true) - p_t), gamma) * K.log(p_t)
return K.mean(focal_loss)
return binary_focal_loss_fixed
#'''
#smooth 參數(shù)防止分母為0
def dice_coef(y_true, y_pred, smooth=1):
intersection = K.sum(y_true * y_pred, axis=[1,2,3])
union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])
return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)
注意在模型保存時,記錄的loss函數(shù)名稱:你猜是哪個
a:binary_focal_loss()
b:binary_focal_loss_fixed
3.模型預(yù)測時,也要加載自定義loss及評估函數(shù),不然會報錯。
該告訴上面的答案了,保存在模型中l(wèi)oss的名稱為:binary_focal_loss_fixed,在模型預(yù)測時,定義custom_objects字典,key一定要與保存在模型中的名稱一致,不然會找不到loss function。所以自定義函數(shù)時,盡量避免使用我這種函數(shù)嵌套的方式,免得帶來一些意想不到的煩惱。
model = load_model('./unet_' + label + '_20.h5',custom_objects={'binary_focal_loss_fixed': binary_focal_loss(),'dice_coef': dice_coef})
以上這篇keras自定義損失函數(shù)并且模型加載的寫法介紹就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python實現(xiàn)斐波那契數(shù)列的示例代碼
斐波那契數(shù)列是一種經(jīng)典的數(shù)學(xué)問題,在計算機科學(xué)和編程中經(jīng)常被用來演示算法和遞歸的概念,本文將詳細(xì)介紹斐波那契數(shù)列的定義、計算方法以及如何在Python中實現(xiàn)它,需要的可以參考下2024-01-01
Python中DataFrame判斷兩列數(shù)據(jù)是否相等的方法
本文主要介紹了DataFrame判斷兩列數(shù)據(jù)是否相等的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
在Python IDLE 下調(diào)用anaconda中的庫教程
這篇文章主要介紹了在Python IDLE 下調(diào)用anaconda中的庫教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python中利用Future對象異步返回結(jié)果示例代碼
future是一種對象,表示異步執(zhí)行的操作。下面這篇文章主要給大家介紹了關(guān)于python中利用Future對象異步返回結(jié)果的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來一起看看吧。2017-09-09
python中numpy基礎(chǔ)學(xué)習(xí)及進行數(shù)組和矢量計算
這篇文章主要給大家介紹了python中numpy基礎(chǔ)知識,以及進行數(shù)組和矢量計算的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-02-02
Python 創(chuàng)建子進程模塊subprocess詳解
這篇文章主要介紹了Python 創(chuàng)建子進程模塊subprocess詳解,本文詳細(xì)講解了subprocess模塊的方法、參數(shù)、使用實例等,需要的朋友可以參考下2015-04-04

