现在深度学习逐渐应用到各行各业,针对各个行业的具体不同问题,需要设计较为合理的损失函数。
- MSE
之前接触的最多的应该是最小二乘优化方法,最小二乘损失函数为 平均均方误差MSE(Mean Squared Error),
keres中MSE损失为:
from keras import backend as K
def mean_squared_error(y_true, y_pred):
return K.mean(K.square(y_pred - y_true), axis=-1)
但是使用MSE之前有一个前提,就是去除了较明显的异常值后,效果才会较好。因为,异常值会产生较大的损失,因此求损失函数最优值(最小值)时,结果会偏向靠近异常值。
- MAE
MAE(Mean Absolute Error )由于其绝对值运算较为麻烦,应用没有最小二乘多。但是其异常值对结果的影响程度没有MSE严重。
keras里面的MAE损失函数为:
from keras import backend as K
def mean_absolute_error(y_true, y_pred):
return K.mean(K.abs(y_pred - y_true), axis=-1)
更多的时候,我们希望将这两结合起来使用.
3. MSE和MAE结合
def myloss(y_true,y_pred,MAE_loss_weight=0.6,MSE_loss_weight=0.6):
'''
自定义损失函数
'''
from keras import backend as K
MAE_loss=K.mean(K.abs(y_pred-y_true),axis=-1)
MSE_loss=K.mean(K.square(y_pred-y_true),axis=-1)
total_loss=MAE_loss*MAE_loss_weight+MSE_loss*MSE_loss_weight
return total_loss
调用如下:
model=Model()
model.compile(loss=myloss)
其他的自定义损失函数过程基本差不多!