title: Keras: How to compare K.sum(y_true) with 0 in custom loss?
body: <p>I want to define custom loss, but seems it fails to compare keras tensor <code>K.sum(y_true)</code> with single value <code>0</code>.</p>
  
  <pre><code>def custom_loss_keras(y_true, y_pred):
      if(K.sum(y_true) &gt; 0):
          loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
          return loss
      else:
          loss = 0.0
          return loss
  </code></pre>
  
  <p>I also tried <code>K.eval()</code> inside loss function to get numpy array and it failed.</p>
  
  <pre><code>def custom_loss_keras(y_true, y_pred):
      y_true_np = K.eval(y_true) 
      #if(K.sum(y_true) &gt; 0):
      if(np.sum(y_true_np) &gt; 0):
          loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
          return loss
      else:
          loss = 0.0
          return loss
  </code></pre>
  
  <p><strong>UPDATE:</strong></p>
  
  <pre><code>def custom_loss_keras(y_true, y_pred):
      if(K.greater(K.sum(y_true), 0)):
          loss = K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)
          return loss
      else:
          loss = 0.0
          return loss
  </code></pre>
  
  <p>It produces error: </p>
  
  <pre><code>TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
  </code></pre>
  
  <p>Also I have tried to combine suggested <code>tf.cond</code> with keras functions:</p>
  
  <pre><code>def custom_loss_keras(y_true, y_pred):
      loss = tf.cond(K.greater(K.sum(y_true),0), K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1), 0.0)
  
      return loss
  </code></pre>
  
  <p>It produces error:</p>
  
  <pre><code>     22 def custom_loss_keras(y_true, y_pred):
  ---&gt; 23     loss = tf.cond(K.greater(K.sum(y_true),0), K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1), 0.0)
       24 
       25     return loss
  
  ~/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/control_flow_ops.py in cond(pred, fn1, fn2, name)
     1718   with ops.name_scope(name, "cond", [pred]) as name:
     1719     if not callable(fn1):
  -&gt; 1720       raise TypeError("fn1 must be callable.")
     1721     if not callable(fn2):
     1722       raise TypeError("fn2 must be callable.")
  
  TypeError: fn1 must be callable.
  </code></pre>
  
  <p>Seems like I need to write it in pure tensorflow?</p>