title: Custom Loss Function in R Keras
body: <p>I want to calculate weighted mean squared error, where weights is one vector in the data. I wrote a custom code based on the suggestions available on stack overflow. </p>
  
  <p>The function is provided below: </p>
  
  <pre><code>weighted_mse &lt;- function(y_true, y_pred,weights){
    # convert tensors to R objects
    K        &lt;- backend()
    y_true   &lt;- K$eval(y_true)
    y_pred   &lt;- K$eval(y_pred)
    weights  &lt;- K$eval(weights)
  
    # calculate the metric
    loss &lt;- sum(weights*((y_true - y_pred)^2)) 
  
    # convert to tensor
    return(K$constant(loss))
    }
  </code></pre>
  
  <p>However, I am not sure how to pass the custom function to the compiler. It would be great if someone can help me. Thank you. </p>
  
  <pre><code>model      &lt;- model %&gt;% compile(
                  loss = 'mse', 
                  optimizer = 'rmsprop',
                  metrics = 'mse')
  </code></pre>
  
  <p>Regards</p>