Python munkres.Munkres() Examples
The following are 21
code examples of munkres.Munkres().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
munkres
, or try the search function
.
Example #1
Source File: cluster.py From acai with Apache License 2.0 | 7 votes |
def error(cluster, target_cluster, k): """ Compute error between cluster and target cluster :param cluster: proposed cluster :param target_cluster: target cluster :return: error """ n = np.shape(target_cluster)[0] M = np.zeros((k, k)) for i in range(k): for j in range(k): M[i][j] = np.sum(np.logical_and(cluster == i, target_cluster == j)) m = Munkres() indexes = m.compute(-M) corresp = [] for i in range(k): corresp.append(indexes[i][1]) pred_corresp = [corresp[int(predicted)] for predicted in cluster] acc = np.sum(pred_corresp == target_cluster) / float(len(target_cluster)) return acc
Example #2
Source File: utils.py From video-to-pose3D with MIT License | 6 votes |
def best_matching_hungarian(all_cors, all_pids_info, all_pids_fff, track_vid_next_fid, weights, weights_fff, num, mag): box1_num = len(all_pids_info) box2_num = track_vid_next_fid['num_boxes'] cost_matrix = np.zeros((box1_num, box2_num)) # print(f"Outer for loop :{box1_num}", end=' ') pool = Pool() results = [] for pid1 in range(box1_num): result = pool.apply_async(cal_one_matching, args=(all_cors, all_pids_fff, all_pids_info, cost_matrix, mag, num, pid1, track_vid_next_fid, weights, weights_fff)) results.append(result) pool.close() pool.join() # print() for i, result in enumerate(results): cost_matrix[i] = result.get() m = Munkres() indexes = m.compute((-np.array(cost_matrix)).tolist()) return indexes, cost_matrix
Example #3
Source File: util.py From SpectralNet with MIT License | 6 votes |
def get_y_preds(cluster_assignments, y_true, n_clusters): ''' Computes the predicted labels, where label assignments now correspond to the actual labels in y_true (as estimated by Munkres) cluster_assignments: array of labels, outputted by kmeans y_true: true labels n_clusters: number of clusters in the dataset returns: a tuple containing the accuracy and confusion matrix, in that order ''' confusion_matrix = sklearn.metrics.confusion_matrix(y_true, cluster_assignments, labels=None) # compute accuracy based on optimal 1:1 assignment of clusters to labels cost_matrix = calculate_cost_matrix(confusion_matrix, n_clusters) indices = Munkres().compute(cost_matrix) kmeans_to_true_cluster_labels = get_cluster_labels_from_indices(indices) y_pred = kmeans_to_true_cluster_labels[cluster_assignments] return y_pred, confusion_matrix
Example #4
Source File: metric.py From MvDSCN with MIT License | 6 votes |
def best_map(L1, L2): #L1 should be the groundtruth labels and L2 should be the clustering labels we got Label1 = np.unique(L1) nClass1 = len(Label1) Label2 = np.unique(L2) nClass2 = len(Label2) nClass = np.maximum(nClass1,nClass2) G = np.zeros((nClass,nClass)) for i in range(nClass1): ind_cla1 = L1 == Label1[i] ind_cla1 = ind_cla1.astype(float) for j in range(nClass2): ind_cla2 = L2 == Label2[j] ind_cla2 = ind_cla2.astype(float) G[i,j] = np.sum(ind_cla2 * ind_cla1) m = Munkres() index = m.compute(-G.T) index = np.array(index) c = index[:,1] newL2 = np.zeros(L2.shape) for i in range(nClass2): newL2[L2 == Label2[i]] = Label1[c[i]] return newL2
Example #5
Source File: util.py From Deep-Spectral-Clustering-using-Dual-Autoencoder-Network with MIT License | 6 votes |
def get_y_preds(cluster_assignments, y_true, n_clusters): ''' Computes the predicted labels, where label assignments now correspond to the actual labels in y_true (as estimated by Munkres) cluster_assignments: array of labels, outputted by kmeans y_true: true labels n_clusters: number of clusters in the dataset returns: a tuple containing the accuracy and confusion matrix, in that order ''' confusion_matrix = sklearn.metrics.confusion_matrix(y_true, cluster_assignments, labels=None) # compute accuracy based on optimal 1:1 assignment of clusters to labels cost_matrix = calculate_cost_matrix(confusion_matrix, n_clusters) indices = Munkres().compute(cost_matrix) kmeans_to_true_cluster_labels = get_cluster_labels_from_indices(indices) y_pred = kmeans_to_true_cluster_labels[cluster_assignments] return y_pred, confusion_matrix
Example #6
Source File: util.py From pose-ae-demo with BSD 2-Clause "Simplified" License | 5 votes |
def py_max_match(scores): m = Munkres() tmp = m.compute(-scores) tmp = np.array(tmp).astype(np.int32) return tmp
Example #7
Source File: subspace.py From biclustlib with GNU General Public License v3.0 | 5 votes |
def _calculate_dmax(predicted_biclustering, reference_biclustering): pred_sets = _bic2sets(predicted_biclustering) true_sets = _bic2sets(reference_biclustering) cost_matrix = [[sys.maxsize - len(b.intersection(g)) for g in true_sets] for b in pred_sets] indices = Munkres().compute(cost_matrix) return sum(sys.maxsize - cost_matrix[i][j] for i, j in indices)
Example #8
Source File: calc.py From px2graph with BSD 3-Clause "New" or "Revised" License | 5 votes |
def py_max_match(scores): # Backup if you have trouble getting munkres-tensorflow compiled (much slower) from munkres import Munkres m = Munkres() tmp = m.compute(-scores) return np.array(tmp).astype(np.int32)
Example #9
Source File: util.py From SpectralNet with MIT License | 5 votes |
def get_accuracy(cluster_assignments, y_true, n_clusters): ''' Computes the accuracy based on the provided kmeans cluster assignments and true labels, using the Munkres algorithm cluster_assignments: array of labels, outputted by kmeans y_true: true labels n_clusters: number of clusters in the dataset returns: a tuple containing the accuracy and confusion matrix, in that order ''' y_pred, confusion_matrix = get_y_preds(cluster_assignments, y_true, n_clusters) # calculate the accuracy return np.mean(y_pred == y_true), confusion_matrix
Example #10
Source File: people_counting.py From Smart-City-Sample with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self): # Array of Gallery Objects - {embeddings(numpy array), timestamp} self.identities = [] self.reid_threshold = 0.7 self.matcher = Munkres() self.timestamp = 0
Example #11
Source File: tcga.py From pytorch-meta with MIT License | 5 votes |
def _assign_samples(tcga_metadataset): import pandas as pd import munkres blacklist = [] sample_to_task_assignment = {} for cancer in get_cancers(): filename = tcga_metadataset.get_processed_filename(cancer) dataframe = pd.read_csv(filename, sep='\t', index_col=0, header=0) dataframe = dataframe.drop(blacklist, errors='ignore') permutation = dataframe.index[torch.randperm(len(dataframe.index))] dataframe = dataframe.reindex(permutation) labels = dataframe.notna() labels = labels.applymap(lambda x: 1. if x else munkres.DISALLOWED) all_disallowed = labels.apply(lambda x: True if all(x == munkres.DISALLOWED) else False, axis=1) labels = labels.drop(labels[all_disallowed].index) matrix = labels.values shape = matrix.shape # The +5 allows for some slack in the assignment # which is necessary for the used implementation to converge on BRCA repeats = np.int(np.ceil(shape[0] / shape[1])) + 5 expanded_matrix = np.tile(matrix, (1, repeats)) indices = munkres.Munkres().compute(expanded_matrix) mapped_indices = [(a, b % shape[1]) for a, b in indices] for index, mapped_index in mapped_indices: sample_to_task_assignment.setdefault((dataframe.columns[mapped_index], cancer), []).append( dataframe.index[index]) blacklist.extend(dataframe.index.tolist()) return sample_to_task_assignment
Example #12
Source File: util.py From Deep-Spectral-Clustering-using-Dual-Autoencoder-Network with MIT License | 5 votes |
def get_accuracy(cluster_assignments, y_true, n_clusters): ''' Computes the accuracy based on the provided kmeans cluster assignments and true labels, using the Munkres algorithm cluster_assignments: array of labels, outputted by kmeans y_true: true labels n_clusters: number of clusters in the dataset returns: a tuple containing the accuracy and confusion matrix, in that order ''' y_pred, confusion_matrix = get_y_preds(cluster_assignments, y_true, n_clusters) # calculate the accuracy return np.mean(y_pred == y_true), confusion_matrix
Example #13
Source File: align_wordlists.py From panphon with MIT License | 5 votes |
def main(wordlist1, wordlist2, dist_funcs): with open(wordlist1, 'rb') as file_a, open(wordlist2, 'rb') as file_b: reader_a = csv.reader(file_a, encoding='utf-8') reader_b = csv.reader(file_b, encoding='utf-8') print('Reading word lists...') words = zip([(w, g) for (g, w) in reader_a], [(w, g) for (g, w) in reader_b]) words_a, words_b = zip(*[(a, b) for (a, b) in words if a and b]) print('Constructing cost matrix...') matrix = construct_cost_matrix(words_a, words_b, dist_funcs) m = munkres.Munkres() print('Computing matrix using Hungarian Algorithm...') indices = m.compute(matrix) print(score(indices)) print('Done.')
Example #14
Source File: noun_iou.py From show-control-and-tell with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, pre_comp_file): self.pre_comp_file = pre_comp_file self.munkres = munkres.Munkres() with open(self.pre_comp_file, 'rb') as fp: self.vectors = pkl.load(fp)
Example #15
Source File: group.py From HigherHRNet-Human-Pose-Estimation with MIT License | 5 votes |
def py_max_match(scores): m = Munkres() tmp = m.compute(scores) tmp = np.array(tmp).astype(np.int32) return tmp
Example #16
Source File: pose_flow.py From detectron2-pipeline with MIT License | 5 votes |
def best_matching_hungarian(all_cors, all_pids_info, all_pids_fff, track_vid_next_fid, weights, weights_fff, num, mag): box1_num = len(all_pids_info) box2_num = len(track_vid_next_fid[1]) cost_matrix = np.zeros((box1_num, box2_num)) for pid1 in range(box1_num): box1_pos = all_pids_info[pid1]['box_pos'] box1_region_ids = find_region_cors_last(box1_pos, all_cors) box1_score = all_pids_info[pid1]['box_score'] box1_pose = all_pids_info[pid1]['keypoints_pos'] box1_fff = all_pids_fff[pid1] for pid2 in range(box2_num): box2_pos = track_vid_next_fid[1][pid2]['box_pos'] box2_region_ids = find_region_cors_next(box2_pos, all_cors) box2_score = track_vid_next_fid[1][pid2]['box_score'] box2_pose = track_vid_next_fid[1][pid2]['keypoints_pos'] inter = box1_region_ids & box2_region_ids union = box1_region_ids | box2_region_ids dm_iou = len(inter) / (len(union) + 0.00001) box_iou = cal_bbox_iou(box1_pos, box2_pos) pose_iou_dm = cal_pose_iou_dm(all_cors, box1_pose, box2_pose, num, mag) pose_iou = cal_pose_iou(box1_pose, box2_pose, num, mag) if box1_fff: grade = cal_grade([dm_iou, box_iou, pose_iou_dm, pose_iou, box1_score, box2_score], weights) else: grade = cal_grade([dm_iou, box_iou, pose_iou_dm, pose_iou, box1_score, box2_score], weights_fff) cost_matrix[pid1, pid2] = grade m = Munkres() indexes = m.compute((-np.array(cost_matrix)).tolist()) return indexes, cost_matrix
Example #17
Source File: test_benchmark_solvers.py From py-lapsolver with MIT License | 5 votes |
def load_solver_munkres(): from munkres import Munkres, DISALLOWED def run(costs): m = Munkres() idx = np.array(m.compute(costs), dtype=int) return costs[idx[:,0], idx[:,1]].sum() return run
Example #18
Source File: group.py From pose-ae-train with BSD 3-Clause "New" or "Revised" License | 5 votes |
def py_max_match(scores): m = Munkres() tmp = m.compute(-scores) tmp = np.array(tmp).astype(np.int32) return tmp
Example #19
Source File: pymot.py From 3d-vehicle-tracking with BSD 3-Clause "New" or "Revised" License | 4 votes |
def __init__(self, groundtruth, hypotheses, overlap_threshold): """Constructor """ self.overlap_threshold_ = overlap_threshold """Bounding box overlap threshold""" self.munkres_inf_ = sys.maxsize """Not quite infinite number for Munkres algorithm""" self.sync_delta_ = 0.001 """Maximum offset considered for a match of hypothesis and ground truth""" self.groundtruth_ = groundtruth """Groundtruth. See groundtruth.json for a sample file""" if self.groundtruth_["class"] != "video": raise Exception("Ground truth is not of class \"video\"") self.hypotheses_ = hypotheses """Hypotheses. See hypotheses.json for a sample file""" if self.hypotheses_["class"] != "video": raise Exception("Hypotheses is not of class \"video\"") self.convertIDsToString() self.resetStatistics() # Set class and type for hypos and ground truths for f in self.hypotheses_["frames"]: for h in f["hypotheses"]: h["type"] = "hypothesis" h["class"] = "unevaluated" for f in self.groundtruth_["frames"]: for g in f["annotations"]: g["type"] = "groundtruth" g["class"] = "unevaluated" # List of dicts, containing ground truths and hypotheses for visual # debugging self.visualDebugFrames_ = []
Example #20
Source File: predeval.py From proficiency-metric with Apache License 2.0 | 4 votes |
def compute_assignment (self): # https://pypi.python.org/pypi/munkres import munkres taxonomy = list(self.check_taxonomy()) costs = [] actual_entropy = [] for ac in taxonomy: an = self.actual.get(ac,0) ae = util.bin_entropy(self.observations,an) actual_entropy.append(ae) if ae == 0: costs.append([0 for _pc in taxonomy]) else: # negative MI because munkres minimizes costs costs.append([- util.bin_mutual_info( self.observations,self.predicted.get(pc,0), an,self.tp.get((ac,pc),0)) for pc in taxonomy]) m = munkres.Munkres() indexes = m.compute(costs) mutual_information = 0 reassigned = [] for row, col in indexes: mutual_information += - costs[row][col] if row != col: ac = taxonomy[row] pc = taxonomy[col] c = -100*costs[row][col] if c > 0: c /= actual_entropy[row] reassigned.append((c,ac,self.actual.get(ac,0), pc,self.predicted.get(pc,0))) if len(reassigned) > 0: reassigned.sort(key=operator.itemgetter(0),reverse=True) self.logger.warn("Reassigned %d categories%s",len(reassigned),"".join( ["\n Proficiency=%.2f%%: Actual [%s](%d) = Predicted [%s](%d)" % (p,ac,an,pc,pn) for (p,ac,an,pc,pn) in reassigned if (p >= 10 and an >= 5 and pn >= 5)])) actual_entropy = sum(actual_entropy) return (taxonomy,indexes, 0 if actual_entropy == 0 else mutual_information / actual_entropy)
Example #21
Source File: utils.py From simple-HRNet with GNU General Public License v3.0 | 4 votes |
def find_person_id_associations(boxes, pts, prev_boxes, prev_pts, prev_person_ids, next_person_id=0, pose_alpha=0.5, similarity_threshold=0.5, smoothing_alpha=0.): """ Find associations between previous and current skeletons and apply temporal smoothing. It requires previous and current bounding boxes, skeletons, and previous person_ids. Args: boxes (:class:`np.ndarray`): current person bounding boxes pts (:class:`np.ndarray`): current human joints prev_boxes (:class:`np.ndarray`): previous person bounding boxes prev_pts (:class:`np.ndarray`): previous human joints prev_person_ids (:class:`np.ndarray`): previous person ids next_person_id (int): the id that will be assigned to the next novel detected person Default: 0 pose_alpha (float): parameter to weight between bounding box similarity and pose (oks) similarity. pose_alpha * pose_similarity + (1 - pose_alpha) * bbox_similarity Default: 0.5 similarity_threshold (float): lower similarity threshold to have a correct match between previous and current detections. Default: 0.5 smoothing_alpha (float): linear temporal smoothing filter. Set 0 to disable, 1 to keep the previous detection. Default: 0.1 Returns: (:class:`np.ndarray`, :class:`np.ndarray`, :class:`np.ndarray`): A list with (boxes, pts, person_ids) where boxes and pts are temporally smoothed. """ bbox_similarity_matrix, pose_similarity_matrix = compute_similarity_matrices(boxes, prev_boxes, pts, prev_pts) similarity_matrix = pose_similarity_matrix * pose_alpha + bbox_similarity_matrix * (1 - pose_alpha) m = munkres.Munkres() assignments = np.asarray(m.compute((1 - similarity_matrix).tolist())) # Munkres require a cost => 1 - similarity person_ids = np.ones(len(pts), dtype=np.int32) * -1 for assignment in assignments: if similarity_matrix[assignment[0], assignment[1]] > similarity_threshold: person_ids[assignment[0]] = prev_person_ids[assignment[1]] if smoothing_alpha: boxes[assignment[0]] = (1 - smoothing_alpha) * boxes[assignment[0]] + smoothing_alpha * prev_boxes[assignment[1]] pts[assignment[0]] = (1 - smoothing_alpha) * pts[assignment[0]] + smoothing_alpha * prev_pts[assignment[1]] person_ids[person_ids == -1] = np.arange(next_person_id, next_person_id + np.sum(person_ids == -1)) return boxes, pts, person_ids # #