因为程序需要,需要新定义使用Tensorflow2.Kares时的损失函数,因此在这里简单记录下。首先声明环境与引入:Tensorflow2,import tensorflow as tf,import tensorflow.keras.backend as K。
1. 自定义均方损失函数
均方误差MSE的定义就比较简单,就是 1 N ∗ ∑ i = 0 N − 1 ( Y _ t r u e i − Y _ p r e d i ) 2 \frac{1}{N}*\sum_{i=0}^{N-1}\left (Y\_true_{i}-Y\_pred_{i}\right )^{2} N1∗∑i=0N−1(Y_truei−Y_predi)2,Y_pred是预测序列或者说预测值,Y_true是真实序列或者说真实值。给出代码:
def custom_mean_squared_error(y_true, y_pred):
return tf.math.reduce_mean(tf.square(y_true - y_pred))
2. 自定义交叉熵损失函数
交叉熵损失函数用来评估判别器(神经网络)分类情况,假设问题为2分类,判别器(神经网络)的输出维度为2,类似于这种形式[p1,p2],p1 + p2 = 1,而实际标签(c1,c2)为[0,1]或[1,0]。则,交叉熵为:
C
a
t
e
g
o
r
i
c
a
l
C
r
o
s
s
e
n
t
r
o
p
y
=
−
∑
i
=
1
2
c
i
∗
l
o
g
(
p
i
)
CategoricalCrossentropy=-\sum_{i=1}^{2}c_{i}*log(p_{i})
CategoricalCrossentropy=−∑i=12ci∗log(pi)
所以,代码为:
def custom_Bi_CategoricalCrossentropy(y_true, y_pred):
t_loss = (-1)*(y_true * K.log(y_pred))
return K.mean(t_loss)
结果验证无错: