title: Keras with Theano backend: custom loss function
body: <p>I'm trying to create a custom loss function in Keras for a one-layer LSTM regression problem that calculates the mean squared error between only the nonzero values in the label/truth vector, and the corresponding values in the predicted vector. I have tried doing the following</p>
  
  <pre><code>import theano.tensor as T
  import keras.backend as K
  
  def custom_loss_func(y_true, y_pred):
  
      #make the prediction vector zero where the label vector is zero
      y_pred = T.where(T.eq(y_true,0), 0, y_pred) 
  
      #get nonzero values
      nonzero_vals = T.flatnonzero(y_pred)
  
      #return mean squared error on only the nonzero values
      return K.sum(K.square(y_pred-y_true)) / K.shape(nonzero_vals)[0]
  </code></pre>
  
  <p>which yields the error </p>
  
  <blockquote>
    <p>"theano.gof.fg.MissingInputError: Input 0 of the graph (indices start
    from 0), used to compute Elemwise{neq,no_inplace}(/masking_1_input,
    InplaceDimShuffle{x,x,x}.0), was not provided and not given a value.
    Use the Theano flag exception_verbosity='high', for more information
    on this error."</p>
  </blockquote>
  
  <p>This does not appear to work and I think it is due to the "shape" factor of the nonzero vector. I can't seem to gather from the Theano documentation how to fit the shape value into an expression. Any help appreciated, thank you!</p>