Keras自定义Loss函数
生活随笔
收集整理的這篇文章主要介紹了
Keras自定义Loss函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Keras作為一個深度學習庫,非常適合新手。在做神經網絡時,它自帶了許多常用的目標函數,優化方法等等,基本能滿足新手學習時的一些需求。具體包含目標函數和優化方法。但它也支持用戶自定義目標函數,下邊介紹一種最簡單的自定義目標函數的方法。
要實現自定義目標函數,自然想到先看下Keras中的目標函數是怎么定義的。查下源碼發現在Keras/objectives.py中,Keras定義了一系列的目標函數。
def mean_squared_error(y_true, y_pred):return K.mean(K.square(y_pred - y_true), axis=-1)def mean_absolute_error(y_true, y_pred):return K.mean(K.abs(y_pred - y_true), axis=-1)def mean_absolute_percentage_error(y_true, y_pred):diff = K.abs((y_true - y_pred) / K.clip(K.abs(y_true), K.epsilon(), np.inf))return 100. * K.mean(diff, axis=-1)def mean_squared_logarithmic_error(y_true, y_pred):first_log = K.log(K.clip(y_pred, K.epsilon(), np.inf) + 1.)second_log = K.log(K.clip(y_true, K.epsilon(), np.inf) + 1.)return K.mean(K.square(first_log - second_log), axis=-1)def squared_hinge(y_true, y_pred):return K.mean(K.square(K.maximum(1. - y_true * y_pred, 0.)), axis=-1)def hinge(y_true, y_pred):return K.mean(K.maximum(1. - y_true * y_pred, 0.), axis=-1)def categorical_crossentropy(y_true, y_pred):'''Expects a binary class matrix instead of a vector of scalar classes.'''return K.categorical_crossentropy(y_pred, y_true)def sparse_categorical_crossentropy(y_true, y_pred):'''expects an array of integer classes.Note: labels shape must have the same number of dimensions as output shape.If you get a shape error, add a length-1 dimension to labels.'''return K.sparse_categorical_crossentropy(y_pred, y_true)def binary_crossentropy(y_true, y_pred):return K.mean(K.binary_crossentropy(y_pred, y_true), axis=-1)def kullback_leibler_divergence(y_true, y_pred):y_true = K.clip(y_true, K.epsilon(), 1)y_pred = K.clip(y_pred, K.epsilon(), 1)return K.sum(y_true * K.log(y_true / y_pred), axis=-1)def poisson(y_true, y_pred):return K.mean(y_pred - y_true * K.log(y_pred + K.epsilon()), axis=-1)def cosine_proximity(y_true, y_pred):y_true = K.l2_normalize(y_true, axis=-1)y_pred = K.l2_normalize(y_pred, axis=-1)return -K.mean(y_true * y_pred, axis=-1)看到源碼后,事情就簡單多了,我們只要仿照這源碼的定義形式,來定義自己的loss就可以了。例如舉個最簡單的例子,我們定義一個loss為預測值與真實值的差,則可寫為:
def my_koss(y_true,y_pred):return K.mean((y_pred-y_true),axis = -1)然后,將這段代碼放到你的模型中編譯,例如
def my_loss(y_true,y_pred):return K.mean((y_pred-y_true),axis = -1) model.compile(loss=my_loss, optimizer='SGD', metrics=['accuracy'])有一點需要注意,Keras作為一個高級封裝庫,它的底層可以支持theano或者tensorflow,在使用上邊代碼時,首先要導入這一句
from keras import backend as K- ?
這樣你自定義的loss函數就可以起作用了
總結
以上是生活随笔為你收集整理的Keras自定义Loss函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: purdue university so
- 下一篇: Nginx - 配置