本文整理汇总了Python中munkres.Munkres方法的典型用法代码示例。如果您正苦于以下问题:Python munkres.Munkres方法的具体用法?Python munkres.Munkres怎么用?Python munkres.Munkres使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类munkres
的用法示例。
在下文中一共展示了munkres.Munkres方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: error
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例2: get_y_preds
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例3: best_map
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例4: best_matching_hungarian
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例5: py_max_match
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
def py_max_match(scores):
m = Munkres()
tmp = m.compute(-scores)
tmp = np.array(tmp).astype(np.int32)
return tmp
示例6: load_solver_munkres
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例7: best_matching_hungarian
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例8: py_max_match
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
def py_max_match(scores):
m = Munkres()
tmp = m.compute(scores)
tmp = np.array(tmp).astype(np.int32)
return tmp
示例9: __init__
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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)
示例10: main
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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.')
示例11: get_accuracy
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例12: _assign_samples
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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
示例13: __init__
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
def __init__(self):
# Array of Gallery Objects - {embeddings(numpy array), timestamp}
self.identities = []
self.reid_threshold = 0.7
self.matcher = Munkres()
self.timestamp = 0
示例14: py_max_match
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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)
示例15: _calculate_dmax
# 需要导入模块: import munkres [as 别名]
# 或者: from munkres import Munkres [as 别名]
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)