class_docstr: Class to build constraints from labeled data.
  
  See more in the :ref:`User Guide <supervised_version>`.
  
  Parameters
  ----------
  partial_labels : `numpy.ndarray` of ints, shape=(n_samples,)
    Array of labels, with -1 indicating unknown label.
  
  Attributes
  ----------
  partial_labels : `numpy.ndarray` of ints, shape=(n_samples,)
    Array of labels, with -1 indicating unknown label.
class_docstr_tok: ["Class","to","build","constraints","from","labeled","data",".","See","more","in","the",":","ref",":","`","User","Guide","<","supervised_version",">","`",".","Parameters","--","--","--","--","--","partial_labels",":","`","numpy.ndarray","`","of","ints",",","shape=","(","n_samples",",",")","Array","of","labels",",","with","-1","indicating","unknown","label",".","Attributes","--","--","--","--","--","partial_labels",":","`","numpy.ndarray","`","of","ints",",","shape=","(","n_samples",",",")","Array","of","labels",",","with","-1","indicating","unknown","label","."]
docstr: Generates triplets from labeled data.
  
  For every point (X_a) the triplets (X_a, X_b, X_c) are constructed from all
  the combinations of taking one of its `k_genuine`-nearest neighbors of the
  same class (X_b) and taking one of its `k_impostor`-nearest neighbors of
  other classes (X_c).
  
  In the case a class doesn't have enough points in the same class (other
  classes) to yield `k_genuine` (`k_impostor`) neighbors a warning will be
  raised and the maximum value of genuine (impostor) neighbors will be used
  for that class.
  
  Parameters
  ----------
  X : (n x d) matrix
    Input data, where each row corresponds to a single instance.
  
  k_genuine : int
    Number of neighbors of the same class to be taken into account.
  
  k_impostor : int
    Number of neighbors of different classes to be taken into account.
  
  Returns
  -------
  triplets : array-like, shape=(n_constraints, 3)
    2D array of triplets of indicators.
docstr_tok: ["Generates","triplets","from","labeled","data",".","For","every","point","(","X_a",")","the","triplets","(","X_a",",","X_b",",","X_c",")","are","constructed","from","all","the","combinations","of","taking","one","of","its","`","k_genuine","`","-nearest","neighbors","of","the","same","class","(","X_b",")","and","taking","one","of","its","`","k_impostor","`","-nearest","neighbors","of","other","classes","(","X_c",")",".","In","the","case","a","class","does","n't","have","enough","points","in","the","same","class","(","other","classes",")","to","yield","`","k_genuine","`","(","`","k_impostor","`",")","neighbors","a","warning","will","be","raised","and","the","maximum","value","of","genuine","(","impostor",")","neighbors","will","be","used","for","that","class",".","Parameters","--","--","--","--","--","X",":","(","n","x","d",")","matrix","Input","data",",","where","each","row","corresponds","to","a","single","instance",".","k_genuine",":","int","Number","of","neighbors","of","the","same","class","to","be","taken","into","account",".","k_impostor",":","int","Number","of","neighbors","of","different","classes","to","be","taken","into","account",".","Returns","--","--","--","-","triplets",":","array-like",",","shape=","(","n_constraints",",","3",")","2D","array","of","triplets","of","indicators","."]
code: def generate_knntriplets(self, X, k_genuine, k_impostor):
      """
      Generates triplets from labeled data.
  
      For every point (X_a) the triplets (X_a, X_b, X_c) are constructed from all
      the combinations of taking one of its `k_genuine`-nearest neighbors of the
      same class (X_b) and taking one of its `k_impostor`-nearest neighbors of
      other classes (X_c).
  
      In the case a class doesn't have enough points in the same class (other
      classes) to yield `k_genuine` (`k_impostor`) neighbors a warning will be
      raised and the maximum value of genuine (impostor) neighbors will be used
      for that class.
  
      Parameters
      ----------
      X : (n x d) matrix
        Input data, where each row corresponds to a single instance.
  
      k_genuine : int
        Number of neighbors of the same class to be taken into account.
  
      k_impostor : int
        Number of neighbors of different classes to be taken into account.
  
      Returns
      -------
      triplets : array-like, shape=(n_constraints, 3)
        2D array of triplets of indicators.
      """
      # Ignore unlabeled samples
      known_labels_mask = self.partial_labels >= 0
      known_labels = self.partial_labels[known_labels_mask]
      X = X[known_labels_mask]
  
      labels, labels_count = np.unique(known_labels, return_counts=True)
      len_input = known_labels.shape[0]
  
      # Handle the case where there are too few elements to yield k_genuine or
      # k_impostor neighbors for every class.
  
      k_genuine_vec = np.full_like(labels, k_genuine)
      k_impostor_vec = np.full_like(labels, k_impostor)
  
      for i, count in enumerate(labels_count):
          if k_genuine + 1 > count:
              k_genuine_vec[i] = count - 1
              warnings.warn(
                  "The class {} has {} elements, which is not sufficient "
                  "to generate {} genuine neighbors as specified by "
                  "k_genuine. Will generate {} genuine neighbors instead."
                  "\n".format(
                      labels[i], count, k_genuine + 1, k_genuine_vec[i]
                  )
              )
          if k_impostor > len_input - count:
              k_impostor_vec[i] = len_input - count
              warnings.warn(
                  "The class {} has {} elements of other classes, which is"
                  " not sufficient to generate {} impostor neighbors as "
                  "specified by k_impostor. Will generate {} impostor "
                  "neighbors instead.\n".format(
                      labels[i],
                      k_impostor_vec[i],
                      k_impostor,
                      k_impostor_vec[i],
                  )
              )
  
      # The total number of possible triplets combinations per label comes from
      # taking one of the k_genuine_vec[i] genuine neighbors and one of the
      # k_impostor_vec[i] impostor neighbors for the labels_count[i] elements
      comb_per_label = labels_count * k_genuine_vec * k_impostor_vec
  
      # Get start and finish for later triplet assigning
      # append zero at the begining for start and get cumulative sum
      start_finish_indices = np.hstack((0, comb_per_label)).cumsum()
  
      # Total number of triplets is the sum of all possible combinations per
      # label
      num_triplets = start_finish_indices[-1]
      triplets = np.empty((num_triplets, 3), dtype=np.intp)
  
      neigh = NearestNeighbors()
  
      for i, label in enumerate(labels):
          # generate mask for current label
          gen_mask = known_labels == label
          gen_indx = np.where(gen_mask)
  
          # get k_genuine genuine neighbors
          neigh.fit(X=X[gen_indx])
          # Take elements of gen_indx according to the yielded k-neighbors
          gen_relative_indx = neigh.kneighbors(
              n_neighbors=k_genuine_vec[i], return_distance=False
          )
          gen_neigh = np.take(gen_indx, gen_relative_indx)
  
          # generate mask for impostors of current label
          imp_indx = np.where(~gen_mask)
  
          # get k_impostor impostor neighbors
          neigh.fit(X=X[imp_indx])
          # Take elements of imp_indx according to the yielded k-neighbors
          imp_relative_indx = neigh.kneighbors(
              n_neighbors=k_impostor_vec[i],
              X=X[gen_mask],
              return_distance=False,
          )
          imp_neigh = np.take(imp_indx, imp_relative_indx)
  
          # length = len_label*k_genuine*k_impostor
          start, finish = start_finish_indices[i : i + 2]
  
          triplets[start:finish, :] = comb(
              gen_indx,
              gen_neigh,
              imp_neigh,
              k_genuine_vec[i],
              k_impostor_vec[i],
          )
  
      return triplets
  
file_path: metric-learn/metric_learn/constraints.py
imports: import numpy
  import warnings
  from sklearn.utils import check_random_state
  from sklearn.neighbors import NearestNeighbors
label_desc: Use image node_id 3 for calling the Constraints obj's underlying member method code with example usage: obj.generate_knntriplets(X, k_genuine, k_impostor) and returns: triplets