我是靠谱客的博主 复杂烤鸡,这篇文章主要介绍keras自定义loss function的简单方法,现在分享给大家,希望可以做个参考。

首先看一下Keras中我们常用到的目标函数(如mse,mae等)是如何定义的

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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) 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 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)

所以仿照以上的方法,可以自己定义特定任务的目标函数。比如:定义预测值与真实值的差

复制代码
1
2
3
4
from keras import backend as K def new_loss(y_true,y_pred): return K.mean((y_pred-y_true),axis = -1)

然后,应用你自己定义的目标函数进行编译

复制代码
1
2
3
4
5
6
from keras import backend as K def my_loss(y_true,y_pred): return K.mean((y_pred-y_true),axis = -1) model.compile(optimizer=optimizers.RMSprop(lr),loss=my_loss, metrics=['accuracy'])

最后

以上就是复杂烤鸡最近收集整理的关于keras自定义loss function的简单方法的全部内容,更多相关keras自定义loss内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(67)

评论列表共有 0 条评论

立即
投稿
返回
顶部