我刚开始学习 tensorflow
,我想编写自己的损失函数。是否有相关的教程?例如,铰链损失或平方和损失(虽然这已经在tf中了)?
我可以直接在Python中完成吗,还是必须编写cpp代码?
我刚开始学习 tensorflow
,我想编写自己的损失函数。是否有相关的教程?例如,铰链损失或平方和损失(虽然这已经在tf中了)?
我可以直接在Python中完成吗,还是必须编写cpp代码?
我们需要编写损失函数。例如,我们可以使用基本的均方误差作为预测y和目标y_的损失函数:
loss_mse = 1/n(Sum((y-y_)^2))
张量的基本函数包括 tf.add(x,y)
、tf.sub(x,y)
、tf.square(x)
、tf.reduce_sum(x)
以及等等。
然后,我们可以在TensorFlow中定义我们的损失函数,如下:
cost = tf.reduce_mean(tf.square(tf.sub(y,y_)))
除了其他答案之外,如果损失函数可以表示为现有函数的组合,则可以在Python中编写损失函数。
例如,请查看sigmoid_cross_entropy_with_logits
的实现链接,该函数使用基本变换实现。
计算当前模型与提供数据之间差值的平方和
squared_deltas = tf.square(linear_model - y)
loss = tf.reduce_sum(squared_deltas)
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
您可以看到,这并不难:您只需要将函数编码为张量格式并使用它们的基本函数。
例如,以下是如何实现F-beta得分(F1得分的一般方法)。 其公式为:
我们唯一需要做的就是找到如何计算布尔值或0/1值的真正阳性、假阳性和假阴性。如果您有0/1值的向量,可以按照以下方式计算每个值:TP = tf.count_nonzero(actual, predicted)
FP = tf.count_nonzero((actual - 1) * predicted)
FN = tf.count_nonzero((predicted - 1) * actual)
denom = (1 + b**2) * TP + b**2 TN + FP
Fb = (1 + b**2) * TP / denom
TP = tf.count_nonzero(actual * predicted)
denom = (1 + b**2) * TP + b**2 FN + FP
def focal_loss(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
custom_loss=kb.square((pt_1-pt_0)/10)
return custom_loss
model.compile(loss=focal_loss,
optimizer='adam',
metrics=['accuracy'])
我使用Kullbak-Leibler距离实现了自定义损失函数,其中p=常数。我将其应用于自编码器中。
rho = 0.05
class loss_with_KLD(losses.Loss):
def __init__(self, rho):
super(loss_with_KLD, self).__init__()
self.rho = rho
self.kl = losses.KLDivergence()
self.mse = losses.MeanSquaredError(reduction=tf.keras.losses.Reduction.SUM)
def call(self, y_true, y_pred):
mse = self.mse(y_true, y_pred)
kl = self.kl(self.rho, y_pred)
return mse + kl
也许对任何人都有帮助。