当前位置: 首页>>代码示例>>Python>>正文


Python optimize.linear_sum_assignment方法代码示例

本文整理汇总了Python中scipy.optimize.linear_sum_assignment方法的典型用法代码示例。如果您正苦于以下问题:Python optimize.linear_sum_assignment方法的具体用法?Python optimize.linear_sum_assignment怎么用?Python optimize.linear_sum_assignment使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在scipy.optimize的用法示例。


在下文中一共展示了optimize.linear_sum_assignment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _sanitize_dists

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def _sanitize_dists(self, dists):
        """Replace invalid distances."""
        
        dists = np.copy(dists)
        
        # Note there is an issue in scipy.optimize.linear_sum_assignment where
        # it runs forever if an entire row/column is infinite or nan. We therefore
        # make a copy of the distance matrix and compute a safe value that indicates
        # 'cannot assign'. Also note + 1 is necessary in below inv-dist computation
        # to make invdist bigger than max dist in case max dist is zero.
        
        valid_dists = dists[np.isfinite(dists)]
        INVDIST = 2 * valid_dists.max() + 1 if valid_dists.shape[0] > 0 else 1.
        dists[~np.isfinite(dists)] = INVDIST  

        return dists, INVDIST 
开发者ID:facebookresearch,项目名称:PoseWarper,代码行数:18,代码来源:mot.py

示例2: unsupervised_clustering_accuracy

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def unsupervised_clustering_accuracy(
    y: Union[np.ndarray, torch.Tensor], y_pred: Union[np.ndarray, torch.Tensor]
) -> tuple:
    """Unsupervised Clustering Accuracy
    """
    assert len(y_pred) == len(y)
    u = np.unique(np.concatenate((y, y_pred)))
    n_clusters = len(u)
    mapping = dict(zip(u, range(n_clusters)))
    reward_matrix = np.zeros((n_clusters, n_clusters), dtype=np.int64)
    for y_pred_, y_ in zip(y_pred, y):
        if y_ in mapping:
            reward_matrix[mapping[y_pred_], mapping[y_]] += 1
    cost_matrix = reward_matrix.max() - reward_matrix
    row_assign, col_assign = linear_sum_assignment(cost_matrix)

    # Construct optimal assignments matrix
    row_assign = row_assign.reshape((-1, 1))  # (n,) to (n, 1) reshape
    col_assign = col_assign.reshape((-1, 1))  # (n,) to (n, 1) reshape
    assignments = np.concatenate((row_assign, col_assign), axis=1)

    optimal_reward = reward_matrix[row_assign, col_assign].sum() * 1.0
    return optimal_reward / y_pred.size, assignments 
开发者ID:YosefLab,项目名称:scVI,代码行数:25,代码来源:posterior_utils.py

示例3: test_linear_sum_assignment_input_validation

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def test_linear_sum_assignment_input_validation():
    assert_raises(ValueError, linear_sum_assignment, [1, 2, 3])

    C = [[1, 2, 3], [4, 5, 6]]
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.asarray(C)))
    assert_array_equal(linear_sum_assignment(C),
                       linear_sum_assignment(np.matrix(C)))

    I = np.identity(3)
    assert_array_equal(linear_sum_assignment(I.astype(np.bool)),
                       linear_sum_assignment(I))
    assert_raises(ValueError, linear_sum_assignment, I.astype(str))

    I[0][0] = np.nan
    assert_raises(ValueError, linear_sum_assignment, I)

    I = np.identity(3)
    I[1][1] = np.inf
    assert_raises(ValueError, linear_sum_assignment, I) 
开发者ID:Relph1119,项目名称:GraphicDesignPatternByPython,代码行数:22,代码来源:test_hungarian.py

示例4: _assign_posterior

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def _assign_posterior(self):
        """assign posterior to prior based on Hungarian algorithm

        Returns
        -------
        TFA
            Returns the instance itself.
        """

        prior_centers = self.get_centers(self.local_prior)
        posterior_centers = self.get_centers(self.local_posterior_)
        posterior_widths = self.get_widths(self.local_posterior_)
        # linear assignment on centers
        cost = distance.cdist(prior_centers, posterior_centers, 'euclidean')
        _, col_ind = linear_sum_assignment(cost)
        # reorder centers/widths based on cost assignment
        self.set_centers(self.local_posterior_, posterior_centers[col_ind])
        self.set_widths(self.local_posterior_, posterior_widths[col_ind])
        return self 
开发者ID:brainiak,项目名称:brainiak,代码行数:21,代码来源:tfa.py

示例5: cluster_accuracy

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def cluster_accuracy(y_true, y_predicted, cluster_number: Optional[int] = None):
    """
    Calculate clustering accuracy after using the linear_sum_assignment function in SciPy to
    determine reassignments.

    :param y_true: list of true cluster numbers, an integer array 0-indexed
    :param y_predicted: list  of predicted cluster numbers, an integer array 0-indexed
    :param cluster_number: number of clusters, if None then calculated from input
    :return: reassignment dictionary, clustering accuracy
    """
    if cluster_number is None:
        cluster_number = (
            max(y_predicted.max(), y_true.max()) + 1
        )  # assume labels are 0-indexed
    count_matrix = np.zeros((cluster_number, cluster_number), dtype=np.int64)
    for i in range(y_predicted.size):
        count_matrix[y_predicted[i], y_true[i]] += 1

    row_ind, col_ind = linear_sum_assignment(count_matrix.max() - count_matrix)
    reassignment = dict(zip(row_ind, col_ind))
    accuracy = count_matrix[row_ind, col_ind].sum() / y_predicted.size
    return reassignment, accuracy 
开发者ID:vlukiyanov,项目名称:pt-sdae,代码行数:24,代码来源:utils.py

示例6: bipartite_match

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def bipartite_match(pred, gt, n_classes=None, presence=None):
  """Does maximum biprartite matching between `pred` and `gt`."""

  if n_classes is not None:
    n_gt_labels, n_pred_labels = n_classes, n_classes
  else:
    n_gt_labels = np.unique(gt).shape[0]
    n_pred_labels = np.unique(pred).shape[0]

  cost_matrix = np.zeros([n_gt_labels, n_pred_labels], dtype=np.int32)
  for label in range(n_gt_labels):
    label_idx = (gt == label)
    for new_label in range(n_pred_labels):
      errors = np.equal(pred[label_idx], new_label).astype(np.float32)
      if presence is not None:
        errors *= presence[label_idx]

      num_errors = errors.sum()
      cost_matrix[label, new_label] = -num_errors

  row_idx, col_idx = linear_sum_assignment(cost_matrix)
  num_correct = -cost_matrix[row_idx, col_idx].sum()
  acc = float(num_correct) / gt.shape[0]
  return AttrDict(assingment=(row_idx, col_idx), acc=acc,
                  num_correct=num_correct) 
开发者ID:akosiorek,项目名称:stacked_capsule_autoencoders,代码行数:27,代码来源:eval.py

示例7: Hungarian

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def Hungarian(A):
    _, col_ind = linear_sum_assignment(A)
    # Cost can be found as A[row_ind, col_ind].sum()
    return col_ind 
开发者ID:abhinav4192,项目名称:sparse-subspace-clustering-python,代码行数:6,代码来源:Hungarian.py

示例8: linear_assignment

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def linear_assignment(cost_matrix):
  try:
    import lap
    _, x, y = lap.lapjv(cost_matrix, extend_cost=True)
    return np.array([[y[i],i] for i in x if i >= 0]) #
  except ImportError:
    from scipy.optimize import linear_sum_assignment
    x, y = linear_sum_assignment(cost_matrix)
    return np.array(list(zip(x, y))) 
开发者ID:abewley,项目名称:sort,代码行数:11,代码来源:sort.py

示例9: _assign_unique_in_plate

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def _assign_unique_in_plate(self, plate):
        preds = np.array(list(map(itemgetter(1), plate)))
        preds = np.vectorize(lambda x: x if x != -np.inf else -1e10)(preds)
        _, indices = linear_sum_assignment(-preds)
        return [(k, v.item()) for (k, _), v in zip(plate, indices)] 
开发者ID:maciej-sypetkowski,项目名称:kaggle-rcic-1st,代码行数:7,代码来源:make_submission.py

示例10: compute_mean_IoU

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def compute_mean_IoU(S_mask, IoU):
    n_data = IoU.shape[0]
    n_seg_ids = IoU.shape[1]
    K = IoU.shape[2]

    sum_mean_IoU = 0.

    for k in range(n_data):
        assert(K >= np.sum(S_mask[k]))
        sum_IoU = 0.
        count = 0

        row_ind, col_ind = linear_sum_assignment(-IoU[k])
        assert(len(row_ind) == min(n_seg_ids, K))
        assert(len(col_ind) == min(n_seg_ids, K))
        for (i, j) in zip(row_ind, col_ind):

            # NOTE:
            # Ignore when the label does not exist in the shape.
            if not S_mask[k,i]:
                assert(IoU[k,i,j] == 0.)
                continue

            sum_IoU += IoU[k,i,j]
            count += 1

        sum_mean_IoU += sum_IoU / float(count)

    mean_IoU = sum_mean_IoU / float(n_data)
    return mean_IoU 
开发者ID:mhsung,项目名称:deep-functional-dictionaries,代码行数:32,代码来源:evaluate.py

示例11: clustering_accuracy

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def clustering_accuracy(gtlabels, labels):
    cost_matrix = []
    categories = np.unique(gtlabels)
    nr = np.amax(labels) + 1
    for i in np.arange(len(categories)):
        cost_matrix.append(np.bincount(labels[gtlabels == categories[i]], minlength=nr))
    cost_matrix = np.asarray(cost_matrix).T
    row_ind, col_ind = linear_sum_assignment(np.max(cost_matrix) - cost_matrix)

    return float(cost_matrix[row_ind, col_ind].sum()) / len(gtlabels) 
开发者ID:shahsohil,项目名称:DCC,代码行数:12,代码来源:DCCComputation.py

示例12: matching_upd_j

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def matching_upd_j(weights_j, global_weights, sigma_inv_j, global_sigmas, prior_mean_norm, prior_inv_sigma,
                   popularity_counts, gamma, J):

    L = global_weights.shape[0]

    full_cost = compute_cost(global_weights, weights_j, global_sigmas, sigma_inv_j, prior_mean_norm, prior_inv_sigma,
                             popularity_counts, gamma, J)

    row_ind, col_ind = linear_sum_assignment(-full_cost)

    assignment_j = []

    new_L = L

    for l, i in zip(row_ind, col_ind):
        if i < L:
            popularity_counts[i] += 1
            assignment_j.append(i)
            global_weights[i] += weights_j[l]
            global_sigmas[i] += sigma_inv_j
        else:  # new neuron
            popularity_counts += [1]
            assignment_j.append(new_L)
            new_L += 1
            global_weights = np.vstack((global_weights, prior_mean_norm + weights_j[l]))
            global_sigmas = np.vstack((global_sigmas, prior_inv_sigma + sigma_inv_j))

    return global_weights, global_sigmas, popularity_counts, assignment_j 
开发者ID:IBM,项目名称:probabilistic-federated-neural-matching,代码行数:30,代码来源:pfnm.py

示例13: _get_linear_assignment_results

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def _get_linear_assignment_results(self, dist_matrix, query_ids, gallery_ids):
        # get matched id
        row_ind, col_ind = linear_sum_assignment(dist_matrix)
        match_ids = [None] * len(query_ids)
        for i in range(row_ind.shape[0]):
            match_ids[row_ind[i]] = gallery_ids[col_ind[i]]
        # get matched scores
        match_distances = [1.] * len(query_ids)
        for i in range(row_ind.shape[0]):
            match_distances[row_ind[i]] = dist_matrix[row_ind[i], col_ind[i]]
        match_similarity = [1 - dist for dist in match_distances]
        for i in range(len(match_similarity)):
            if match_similarity[i] >= 2:
                match_ids[i] = None
                match_similarity[i] = 0.

        duplicate_ids = [item for item, count in collections.Counter(match_ids).items() if count > 1]
        for dup_id in duplicate_ids:
            indexes = list(np.where(np.array(match_ids) == dup_id)[0])
            duplicate_patch_scores = np.array(match_similarity)[indexes]
            max_score_index = list(duplicate_patch_scores).index(max(list(duplicate_patch_scores)))
            del indexes[max_score_index]
            for index in indexes:
                match_ids[index] = None
                match_similarity[index] = 0.

        return np.array(match_ids), np.array(match_similarity) 
开发者ID:tensorboy,项目名称:centerpose,代码行数:29,代码来源:head_pose_base.py

示例14: soft_to_hard_permutation

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def soft_to_hard_permutation(inputs):
  """Returns permutation matrices by solving a matching problem.

  Solves linear sum assignment to convert doubly-stochastic matrices to
  permutation matrices. It uses scipy.optimize.linear_sum_assignment to solve
  the optimization problem max_P sum_i,j M_i,j P_i,j with P a permutation
  matrix. Notice the negative sign; the reason, the original function solves a
  minimization problem.

  Code is adapted from Mena et al. [1].

  [1] Gonzalo Mena, David Belanger, Scott Linderman, Jasper Snoek.
  Learning latent permutations with Gumbel-Sinkhorn networks. International
  Conference on Learning Representations, 2018.

  Args:
    inputs: A `Tensor` with shape `[:, vocab_size, vocab_size]` that is
      doubly-stochastic in its last two dimensions.

  Returns:
    outputs: A hard permutation `Tensor` with the same shape as `inputs` (in
      other words the last two dimensions are doubly-stochastic and each element
      is 0 or 1).
  """

  def hungarian(x):
    if x.ndim == 2:
      x = np.reshape(x, [1, x.shape[0], x.shape[1]])
    sol = np.zeros((x.shape[0], x.shape[1]), dtype=np.int32)
    for i in range(x.shape[0]):
      sol[i, :] = linear_sum_assignment(-x[i, :])[1].astype(np.int32)
    return sol

  vocab_size = inputs.shape[-1]
  # Note: tf.py_func isn't currently supported on headless GPUs.
  # TODO(vafa): Fix tf.py_func headless GPU bug.
  permutation_lists = tf.py_func(hungarian, [inputs], tf.int32)
  hard = tf.one_hot(permutation_lists, depth=vocab_size)
  outputs = tf.stop_gradient(hard - inputs) + inputs
  return outputs 
开发者ID:yyht,项目名称:BERT,代码行数:42,代码来源:reversible_layers.py

示例15: hungarian_matching

# 需要导入模块: from scipy import optimize [as 别名]
# 或者: from scipy.optimize import linear_sum_assignment [as 别名]
def hungarian_matching(pred_loc, target_loc):
    # pred_loc = pred_loc.data.cpu().numpy()
    # target_loc = target_loc.data.cpu().numpy()

    cost_matrix = cdist(target_loc, pred_loc)
    row_ind, col_ind = linear_sum_assignment(cost_matrix)
    return col_ind 
开发者ID:anshulpaigwar,项目名称:Attentional-PointNet,代码行数:9,代码来源:modules.py


注:本文中的scipy.optimize.linear_sum_assignment方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。