title: How to write a custom loss function in Keras/Tensorflow that uses loops/iterations with reference numpy code
body: <p>I saw this question: <a href="https://stackoverflow.com/questions/51100508/implementing-custom-loss-function-in-keras-with-condition">Implementing custom loss function in keras with condition</a> And I need to do the same thing but with code that seems to need loops.</p>
  
  <p>I have a custom <code>numpy</code> function which calculates the mean Euclid distance from the mean vector. I wrote this based on the paper <a href="https://arxiv.org/pdf/1801.05365.pdf" rel="nofollow noreferrer">https://arxiv.org/pdf/1801.05365.pdf</a>:</p>
  
  <p><a href="https://i.stack.imgur.com/VKXMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VKXMG.png" alt="Equation Picture"></a></p>
  
  <pre><code>import numpy as np
  
  def mean_euclid_distance_from_mean_vector(n_vectors):
  
      dists = []
  
      for (i, v) in enumerate(n_vectors):
          n_vectors_rest = n_vectors[np.arange(len(n_vectors)) != i]
  
          print("rest of vectors: ")
          print(n_vectors_rest)
  
          # calculate mean vector
          mean_rest = n_vectors_rest.mean(axis=0)
  
          print("mean rest vector")
          print(mean_rest)
  
          dist = v - mean_rest
  
          print("dist vector")
          print(dist)
          dists.append(dist)
  
      # dists is now a matrix of distance vectors (distance from the mean vector)
      dists = np.array(dists)
  
      print("distance vector matrix")
      print(dists)
  
      # here we matmult each vector
      # sum them up
      # and divide by the total number of elements
      result = np.sum([np.matmul(d, d) for d in dists]) / dists.size
  
      return result
  
  
  features = np.array([
      [1,2,3,4],
      [4,3,2,1]
  ])
  
  c = mean_euclid_distance_from_mean_vector(features)
  
  print(c)
  </code></pre>
  
  <p>I need this function however to work inside <code>tensorflow</code> with Keras. So a custom lambda <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda" rel="nofollow noreferrer">https://www.tensorflow.org/api_docs/python/tf/keras/layers/Lambda</a></p>
  
  <p>However, I'm not sure how to implement the above in Keras/Tensorflow since it has loops, and the way the paper talked about calculating the <code>m_i</code> seems to require loops like the way I implemented the above.</p>
  
  <p>For reference, the PyTorch version of this code is here: <a href="https://github.com/PramuPerera/DeepOneClass" rel="nofollow noreferrer">https://github.com/PramuPerera/DeepOneClass</a></p>