def compute_distance_matrix_loo()

in tensorflow_hub/tools/module_search/utils.py [0:0]


def compute_distance_matrix_loo(x, measure="squared_l2"):
  """Calculates the distance matrix for leave-one-out strategy.

  Args:
    x: Matrix (NxD) where each row represents a sample
    measure: Distance measure (not necessarly metric) to use

  Raises:
    NotImplementedError: When the measure is not implemented

  Returns:
    Matrix (NxN) where elemnt i,j is the distance between x_i and x_j.
    The diagonal is set to infinity
  """

  if tf.test.is_gpu_available():
    x = tf.convert_to_tensor(x, tf.float64)
  else:
    if x.dtype != np.float32:
      x = np.float32(x)

  if measure == "squared_l2":
    if tf.test.is_gpu_available():
      x_xt = tf.matmul(x, tf.transpose(x)).numpy()
    else:
      x_xt = np.matmul(x, np.transpose(x))
    diag = np.diag(x_xt)
    d = np.copy(x_xt)

    for i in range(np.shape(d)[0]):
      d[i, :] = np.multiply(d[i, :], -2)
      d[i, :] = np.add(d[i, :], x_xt[i, i])
      d[i, :] = np.add(d[i, :], diag)
      d[i, i] = float("inf")

  elif measure == "cosine":
    if tf.test.is_gpu_available():
      d = tf.matmul(x, tf.transpose(x)).numpy()
    else:
      d = np.matmul(x, np.transpose(x))
    diag_sqrt = np.sqrt(np.diag(d))
    outer = np.outer(diag_sqrt, diag_sqrt)
    d = np.ones(np.shape(d)) - np.divide(d, outer)
    np.fill_diagonal(d, float("inf"))

  else:
    raise NotImplementedError("Method '{}' is not implemented".format(measure))

  return d