# Path: tf_slim/losses/metric_learning.py
#   HAS_SKLEARN = True
#   HAS_SKLEARN = False
# def pairwise_distance(feature, squared=False):
# def contrastive_loss(labels, embeddings_anchor, embeddings_positive,
#                      margin=1.0):
# def masked_maximum(data, mask, dim=1):
# def masked_minimum(data, mask, dim=1):
# def triplet_semihard_loss(labels, embeddings, margin=1.0):
# def npairs_loss(labels, embeddings_anchor, embeddings_positive,
#                 reg_lambda=0.002, print_losses=False):
# def _build_multilabel_adjacency(sparse_labels):
# def npairs_loss_multilabel(sparse_labels, embeddings_anchor,
#                            embeddings_positive, reg_lambda=0.002,
#                            print_losses=False):
# def lifted_struct_loss(labels, embeddings, margin=1.0):
# def update_1d_tensor(y, index, value):
# def get_cluster_assignment(pairwise_distances, centroid_ids):
# def compute_facility_energy(pairwise_distances, centroid_ids):
# def compute_clustering_score(labels, predictions, margin_type):
# def _compute_nmi_score(labels, predictions):
# def _compute_ami_score(labels, predictions):
# def _compute_ari_score(labels, predictions):
# def _compute_vmeasure_score(labels, predictions):
# def _compute_zeroone_score(labels, predictions):
# def _find_loss_augmented_facility_idx(pairwise_distances, labels, chosen_ids,
#                                       candidate_ids, margin_multiplier,
#                                       margin_type):
#   def func_cond(iteration, nmi_scores):
#   def func_body(iteration, nmi_scores):
# def compute_augmented_facility_locations(pairwise_distances, labels, all_ids,
#                                          margin_multiplier, margin_type):
#   def func_cond_augmented(iteration, chosen_ids):
#   def func_body_augmented(iteration, chosen_ids):
# def update_medoid_per_cluster(pairwise_distances, pairwise_distances_subset,
#                               labels, chosen_ids, cluster_member_ids,
#                               cluster_idx, margin_multiplier, margin_type):
#   def func_cond(iteration, scores_margin):
#   def func_body(iteration, scores_margin):
# def update_all_medoids(pairwise_distances, predictions, labels, chosen_ids,
#                        margin_multiplier, margin_type):
#   def func_cond_augmented_pam(iteration, chosen_ids):
#   def func_body_augmented_pam(iteration, chosen_ids):
# def compute_augmented_facility_locations_pam(pairwise_distances,
#                                              labels,
#                                              margin_multiplier,
#                                              margin_type,
#                                              chosen_ids,
#                                              pam_max_iter=5):
# def compute_gt_cluster_score(pairwise_distances, labels):
#   def func_cond(iteration, gt_cluster_score):
#   def func_body(iteration, gt_cluster_score):
# def cluster_loss(labels,
#                  embeddings,
#                  margin_multiplier,
#                  enable_pam_finetuning=True,
#                  margin_type='nmi',
#                  print_losses=False):


import numpy as np
import tensorflow.compat.v1 as tf
from tf_slim.losses import metric_learning
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.platform import test
  from sklearn import datasets
  from sklearn import metrics
    upper_tri_pdists **= 2.
  num_data = feature.shape[0]
  pairwise_distances = np.zeros((num_data, num_data))
  pairwise_distances[np.triu_indices(num_data, 1)] = upper_tri_pdists
  # Make symmetrical.
  pairwise_distances = pairwise_distances + pairwise_distances.T - np.diag(
      pairwise_distances.diagonal())
  return pairwise_distances


class ContrastiveLossTest(test.TestCase):

  def testContrastive(self):
    with self.cached_session():
      num_data = 10
      feat_dim = 6
      margin = 1.0

      embeddings_anchor = np.random.rand(num_data, feat_dim).astype(np.float32)
      embeddings_positive = np.random.rand(num_data, feat_dim).astype(
          np.float32)
      labels = np.random.randint(0, 2, size=(num_data,)).astype(np.float32)

      # Compute the loss in NP
      dist = np.sqrt(
          np.sum(np.square(embeddings_anchor - embeddings_positive), axis=1))
      loss_np = np.mean(
          labels * np.square(dist) +
          (1.0 - labels) * np.square(np.maximum(margin - dist, 0.0)))
      # Compute the loss with TF

# Path: tf_slim/losses/metric_learning.py
#   HAS_SKLEARN = True
#   HAS_SKLEARN = False
# def pairwise_distance(feature, squared=False):
# def contrastive_loss(labels, embeddings_anchor, embeddings_positive,
#                      margin=1.0):
# def masked_maximum(data, mask, dim=1):
# def masked_minimum(data, mask, dim=1):
# def triplet_semihard_loss(labels, embeddings, margin=1.0):
# def npairs_loss(labels, embeddings_anchor, embeddings_positive,
#                 reg_lambda=0.002, print_losses=False):
# def _build_multilabel_adjacency(sparse_labels):
# def npairs_loss_multilabel(sparse_labels, embeddings_anchor,
#                            embeddings_positive, reg_lambda=0.002,
#                            print_losses=False):
# def lifted_struct_loss(labels, embeddings, margin=1.0):
# def update_1d_tensor(y, index, value):
# def get_cluster_assignment(pairwise_distances, centroid_ids):
# def compute_facility_energy(pairwise_distances, centroid_ids):
# def compute_clustering_score(labels, predictions, margin_type):
# def _compute_nmi_score(labels, predictions):
# def _compute_ami_score(labels, predictions):
# def _compute_ari_score(labels, predictions):
# def _compute_vmeasure_score(labels, predictions):
# def _compute_zeroone_score(labels, predictions):
# def _find_loss_augmented_facility_idx(pairwise_distances, labels, chosen_ids,
#                                       candidate_ids, margin_multiplier,
#                                       margin_type):
#   def func_cond(iteration, nmi_scores):
#   def func_body(iteration, nmi_scores):
# def compute_augmented_facility_locations(pairwise_distances, labels, all_ids,
#                                          margin_multiplier, margin_type):
#   def func_cond_augmented(iteration, chosen_ids):
#   def func_body_augmented(iteration, chosen_ids):
# def update_medoid_per_cluster(pairwise_distances, pairwise_distances_subset,
#                               labels, chosen_ids, cluster_member_ids,
#                               cluster_idx, margin_multiplier, margin_type):
#   def func_cond(iteration, scores_margin):
#   def func_body(iteration, scores_margin):
# def update_all_medoids(pairwise_distances, predictions, labels, chosen_ids,
#                        margin_multiplier, margin_type):
#   def func_cond_augmented_pam(iteration, chosen_ids):
#   def func_body_augmented_pam(iteration, chosen_ids):
# def compute_augmented_facility_locations_pam(pairwise_distances,
#                                              labels,
#                                              margin_multiplier,
#                                              margin_type,
#                                              chosen_ids,
#                                              pam_max_iter=5):
# def compute_gt_cluster_score(pairwise_distances, labels):
#   def func_cond(iteration, gt_cluster_score):
#   def func_body(iteration, gt_cluster_score):
# def cluster_loss(labels,
#                  embeddings,
#                  margin_multiplier,
#                  enable_pam_finetuning=True,
#                  margin_type='nmi',
#                  print_losses=False):


# Path: tf_slim/losses/metric_learning_test.py
import numpy as np
import tensorflow.compat.v1 as tf
from tf_slim.losses import metric_learning
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.platform import test
  from sklearn import datasets
  from sklearn import metrics

    upper_tri_pdists **= 2.
  num_data = feature.shape[0]
  pairwise_distances = np.zeros((num_data, num_data))
  pairwise_distances[np.triu_indices(num_data, 1)] = upper_tri_pdists
  # Make symmetrical.
  pairwise_distances = pairwise_distances + pairwise_distances.T - np.diag(
      pairwise_distances.diagonal())
  return pairwise_distances


class ContrastiveLossTest(test.TestCase):

  def testContrastive(self):
    with self.cached_session():
      num_data = 10
      feat_dim = 6
      margin = 1.0

      embeddings_anchor = np.random.rand(num_data, feat_dim).astype(np.float32)
      embeddings_positive = np.random.rand(num_data, feat_dim).astype(
          np.float32)
      labels = np.random.randint(0, 2, size=(num_data,)).astype(np.float32)

      # Compute the loss in NP
      dist = np.sqrt(
          np.sum(np.square(embeddings_anchor - embeddings_positive), axis=1))
      loss_np = np.mean(
          labels * np.square(dist) +
          (1.0 - labels) * np.square(np.maximum(margin - dist, 0.0)))
      # Compute the loss with TF

      loss_tf = metric_learning.contrastive_loss(