title: keras: Smooth L1 loss
body: <p>Try to customize loss function(smooth L1 loss) in keras like below</p>
  
  <blockquote>
    <p>ValueError: Shape must be rank 0 but is rank 5 for 'cond/Switch' (op: 'Switch') with input shapes: [?,24,24,24,?], [?,24,24,24,?].</p>
  </blockquote>
  
  <pre><code>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
  </code></pre>