yua*_*hou 4 deep-learning keras loss-function
尝试在 keras 中自定义损失函数(平滑 L1 损失),如下所示
ValueError: Shape must be rank 0 but is rank 5 for 'cond/Switch' (op: 'Switch') with input shape: [?,24,24,24,?], [?,24,24,24,? ]。
from keras import backend as K
import numpy as np
def smooth_L1_loss(y_true, y_pred):
THRESHOLD = K.variable(1.0)
mae = K.abs(y_true-y_pred)
flag = K.greater(mae, THRESHOLD)
loss = K.mean(K.switch(flag, (mae - 0.5), K.pow(mae, 2)), axis=-1)
return loss
Run Code Online (Sandbox Code Playgroud)
小智 9
我知道我参加聚会晚了两年,但是如果您使用 tensorflow 作为 keras 后端,您可以使用 tensorflow 的Huber 损失(本质上是相同的),如下所示:
import tensorflow as tf
def smooth_L1_loss(y_true, y_pred):
return tf.losses.huber_loss(y_true, y_pred)
Run Code Online (Sandbox Code Playgroud)
这是使用 keras.backend 的平滑 L1 损失的实现:
HUBER_DELTA = 0.5
def smoothL1(y_true, y_pred):
x = K.abs(y_true - y_pred)
x = K.switch(x < HUBER_DELTA, 0.5 * x ** 2, HUBER_DELTA * (x - 0.5 * HUBER_DELTA))
return K.sum(x)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11197 次 |
最近记录: |