title: Iterate over tensor in a custom loss function
body: <p>I need to use this loss function for a CNN the list_distance and list_residual are output tensors from hidden layers which are important to compute the loss, but when i execute the code it gives me back this error </p>
  
  <p>TypeError: Tensor objects are only iterable when eager execution is enabled. To iterate over this tensor use tf.map_fn.</p>
  
  <p>Is there another way to iterate over tensors without the use of the costruct
  x in X or convert it in a numpy array or using the backend function of keras?</p>
  
  <pre class="lang-py prettyprint-override"><code>
  def DBL(y_true, y_pred, list_distances, list_residual, l=0.65):
      prob_dist = []
      Li = []
  
      # mean of the images power spectrum
      S = np.sum([np.power(np.abs(fp.fft2(residual)), 2)
                  for residual in list_residual], axis=0) / K.shape(list_residual)[0]
      # log-ratio between the geometric and arithmetic of S
      R = np.log10((scistats.gmean(S) / np.mean(S)))
  
      for c_i, dis_i in enumerate(list_distances):
          prob_dist.append([
              np.exp(-dis_i) / sum([np.exp(-dis_j) if c_j != c_i else 0 for c_j, dis_j in enumerate(list_distances)])
          ])
      for count, _ in enumerate(prob_dist):
          Li.append(
              -1 * np.log10(sum([p_j for c_j, p_j in enumerate(prob_dist[count])
                                 if y_pred[count] == 1 and count != c_j])))
  
      L0 = np.sum(Li)
  
      return L0 - l * R
  
  </code></pre>