本文整理汇总了Python中munkres.Munkres.compute方法的典型用法代码示例。如果您正苦于以下问题:Python Munkres.compute方法的具体用法?Python Munkres.compute怎么用?Python Munkres.compute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类munkres.Munkres
的用法示例。
在下文中一共展示了Munkres.compute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Objmatch
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def Objmatch(objy,objx,ref,refc,L,W,im,length):
global D_limit_s
dmtx = np.zeros((L,W))
cmtx = np.zeros((L,W))
Wd = 0.5 #weight of distance
Wc = 1-Wd #weight of color
for i in range(L):
dmtx[i,:] =((objy - ref[i][0])**2+(objx - ref[i][1])**2).T
cmtx[i,:] = Color_Dif(im,objx,objy,refc[i],length[i])
dmtx = dmtx/diag # normalize the distance by divid diag
dmtx[dmtx>D_limit_s] = 10**6
cmtx = cmtx*Wc + dmtx*Wd
tmp = copy.deepcopy(cmtx)
m = Munkres()
if L<=W:
indexes = m.compute(cmtx)
else: # len(ori) > # live_blobs
indexes = m.compute(cmtx.T)
indexes = [(s[1],s[0]) for s in indexes]
D_idx = []
if vid_idx>=0:
for i in range(len(indexes))[::-1]:
if tmp[indexes[i][0],indexes[i][1]]>10**5:
D_idx.append(i)
indexes.pop(i)
return indexes,D_idx
示例2: match_parameters
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def match_parameters(p, q, method="munkres", discard_misses=False):
"""
Match two sets of parameters.
TODO: finish greedy
"""
logger.info("Matching with method %s" % method)
assert p.shape[1] == q.shape[1], (
"Shapes do not match (%s vs %s)" % (p.shape, q.shape)
)
match_size = min(p.shape[0], q.shape[0])
corrs = np.corrcoef(p, q)[match_size:, :match_size]
corrs[np.isnan(corrs)] = 0
if method == "munkres":
m = Munkres()
cl = 1 - np.abs(corrs)
if (cl.shape[0] > cl.shape[1]):
indices = m.compute(cl.T)
else:
indices = m.compute(cl)
indices = [(i[1], i[0]) for i in indices]
elif method == "greedy":
q_idx = []
raise NotImplementedError("Greedy not supported yet.")
for c in range(q.shape[0]):
idx = corrs[c, :].argmax()
q_idx.append(idx)
corrs[:,idx] = 0
else:
raise NotImplementedError("%s matching not supported" % method)
return indices
示例3: fixColouringAndCompare
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def fixColouringAndCompare(atk, btk):
"""
15 April 2013
input: atk, btk are clustering results
output: btk['pattern'] and btk['centroids'][1] fixed
returning the distanceSquaredMatrix and the indices
"""
k = len(atk["centroids"][0])
# k = a.k
aClusters = [-999] * k # initialising a length-k list for convenience
bClusters = [-999] * k
for i in range(k):
# x-coord, y-coord, weight of the i-th cluster in a
aClusters[i] = {
"x": atk["centroids"][0][i][0],
"y": atk["centroids"][0][i][1],
"weight": len([v for v in atk["centroids"][1] if v == i]),
}
# doing the same for b
bClusters[i] = {
"x": btk["centroids"][0][i][0],
"y": btk["centroids"][0][i][1],
"weight": len([v for v in btk["centroids"][1] if v == i]),
}
distanceSquaredMatrix = np.ones((k, k)) * (-999.0)
for i in range(k):
for j in range(k):
dist2 = (aClusters[i]["x"] - bClusters[j]["x"]) ** 2 + (aClusters[i]["y"] - bClusters[j]["y"]) ** 2
# print i,j, dist2 #debug
distanceSquaredMatrix[i, j] = dist2
from munkres import Munkres
m = Munkres()
indices = m.compute(distanceSquaredMatrix.copy()) # munkres would alter the entries
# indicies2=dict([(v[1], v[0]) for v in indices])
indices2 = m.compute(distanceSquaredMatrix.copy().T) # munkres would alter the entries
indices2Dict = dict(indices2)
# print indices2 #debug
# print indices2Dict
bData = btk["data"]
bCentroids = btk["centroids"]
for i in range(len(bCentroids[1])):
newColour = indices2Dict[bCentroids[1][i]]
btk["centroids"][1][i] = newColour
btk["pattern"].matrix[bData[i][1], bData[i][0]] = newColour
abCompare = {
"distanceSquared": distanceSquaredMatrix,
"indices": indices,
"aClusters": aClusters,
"bClusters": bClusters,
}
return abCompare
示例4: __init__
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def __init__(self, G1, G2, nattr='weight', eattr='weight', lamb = 0.5):
G1, G2 = sorted([G1, G2], key=lambda x: len(x))
csim = gs.tacsim_combined_in_C(G1, G2, node_attribute=nattr, edge_attribute=eattr, lamb=lamb)
self.csim = csim / np.sqrt(((csim * csim).sum())) # to ensure valid structural distance
self.g1 = G1
self.g2 = G2
m = Munkres()
cdist = (1 - self.csim).tolist()
self.matching = m.compute(cdist)
nmap = {}
def _gen_nnid(node):
if node not in nmap:
nmap[node] = len(nmap)
return nmap[node]
self.mesos = nx.DiGraph()
for (e1_idx, e2_idx) in self.matching:
e1 = G1.edges()[e1_idx]
e2 = G2.edges()[e2_idx]
ns = _gen_nnid(e1[0])
nt = _gen_nnid(e1[1])
self.mesos.add_edge(ns, nt)
self.mesos.edge[ns][nt][eattr] = 0.5 * (G1.edge[e1[0]][e1[1]][eattr] + G2.edge[e2[0]][e2[1]][eattr])
self.mesos.node[ns][nattr] = 0.5 * (G1.node[e1[0]][nattr] + G2.node[e2[0]][nattr])
self.mesos.node[nt][nattr] = 0.5 * (G1.node[e1[1]][nattr] + G2.node[e2[1]][nattr])
示例5: HungarianMapper
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
class HungarianMapper(BaseMapper):
def __init__(self, cost=None):
super(HungarianMapper, self).__init__(cost=cost)
self._munkres = Munkres()
def __call__(self, A, B):
# Cooccurrence matrix
matrix = self.cost(A, B)
# Shape and labels
nRows, nCols = matrix.shape
rows = matrix.get_rows()
cols = matrix.get_columns()
# Cost matrix
N = max(nCols, nRows)
C = np.zeros((N, N))
C[:nCols, :nRows] = (np.max(matrix.df.values) - matrix.df.values).T
mapping = {}
for b, a in self._munkres.compute(C):
if (b < nCols) and (a < nRows):
if matrix[rows[a], cols[b]] > 0:
mapping[rows[a]] = cols[b]
return mapping
示例6: getFileSim
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def getFileSim(fileA,fileB,alpha,beta): #to find the similarity of two files
File1=open(dirname+'/'+fileA, "r")
File2=open(dirname+'/'+fileB, "r")
content1=File1.readlines()
flag=0
content2=File2.readlines()
if len(content1) > len(content2):
flag=1
content1,content2 = content2,content1
sim=[]
for sen_A in content1:
temp = []
sen_A = sen_A.lower()
for sen_B in content2:
sen_B = sen_B.lower()
temp.append(senSim(sen_A,sen_B,alpha))
sim.append(temp)
for i in range(len(sim)) #to make it a maximum cost problem
for j in range(len(sim[i])):
sim[i][j] = 1.0-sim[i][j]
m=Munkres()
result_matrix=m.compute(sim) #implementing hungarian
maxSimMatrix = []
for row,column in result_matrix:
if sim[row][column]!=1.0:
if flag==1:
row,column=column,row
maxSimMatrix.append([row,column]) #storing which lines are matched
FileSim=float(len(maxSimMatrix))/(len(content1))
if FileSim<beta:
FileSim = 0
return (FileSim, maxSimMatrix)
示例7: match
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def match(self, model_manager):
individuals = model_manager.individuals
groups = model_manager.groups
pref_matrix = []
individual_count = len(individuals)
row_index = -1
individuals_by_row = {}
groups_by_col = {}
for individual_id, individual in individuals.iteritems():
row_index += 1
individuals_by_row[str(row_index)] = individual
pref_matrix_row = []
col_index = -1
for group_id, group in groups.iteritems():
group_pref_value = individual.get_group_pref_value(group.id)
# we use group slots to control the max number of individuals per group. one individual per slot
# each slot represents a potential membership within a group within the preference matrix.
# the len(pref_matrix_group_slots[grounp.id]) == min(group.max_size, len(individuals))
group_slot_size = min(group.max_size, individual_count)
for s in range(group_slot_size):
# multiply value by negative 1 because munkres finds
# the assignment with minimum net value,
# and we want to find the assignment with
# maximum net value
pref_matrix_row.append(group_pref_value * -1)
col_index += 1
groups_by_col[str(col_index)] = group
pref_matrix.append(pref_matrix_row)
munkres = Munkres()
optimal_match_indexes = munkres.compute(pref_matrix)
assignments = [(individuals_by_row[str(row)], groups_by_col[str(col)]) for row, col in optimal_match_indexes]
return assignments
示例8: main
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def main(tutors, players):
scores = []
#create cross-scores
for tutor in tutors:
# create the score array for each tutor to every player
scores.append([ getModFLF(tutor, player)*getBaseFLF(tutor,player) for player in players ])
# print the matrix
#pretty_print(scores)
# find max
maxscore = max(max(row) for row in scores)
# turn the matrix into a min-problem
for row in scores:
for idx,col in enumerate(row):
row[idx] = maxscore-col
# using munkres (copy of tutorial)
m = Munkres()
indexes = m.compute(scores)
# pretty_print(scores)
total = 0
print "[[Tutor ::: Player]]"
for row, col in indexes:
total += scores[row][col]
print '{0} ::: {1}'.format(tutors[row],players[col])
print 'total FLF: {0}'.format(maxscore*len(tutors)-total)
示例9: similar
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def similar(list_current,list_called):
global P,total
# comparing the length of two files to compare smaller length to bigger
if len(list_current)<len(list_called):
# calling comparison function to compare both files line by line for similarity
similarity = comparison(list_current,list_called)
# storing the lenght of smaller
P = len(list_current)
point=[[0 for x in range(len(list_called))] for y in range(len(list_current))]
else:
# calling comparison function to compare both files line by line for similarity
similarity = comparison(list_called,list_current)
P = len(list_called)
point=[[0 for x in range(len(list_current))] for y in range(len(list_called))]
# calling functions of munkres to form maximum weighted bipartite matching graph
graph_matrix = make_cost_matrix(similarity, lambda cost: 1.0 - cost)
m = Munkres()
indexes =m.compute(graph_matrix)
total = 0
for row, column in indexes:
# forming list of points(lines) of similarity between two files
value = similarity[row][column]
if value>0.0:
total += 1
point[row][column]=1
return point
示例10: accuracy
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def accuracy(labels_true, labels_pred):
labels_true, labels_pred = check_clusterings(labels_true, labels_pred)
n_samples = labels_true.shape[0]
classes = np.unique(labels_true)
clusters = np.unique(labels_pred)
# Special limit cases: no clustering since the data is not split;
# or trivial clustering where each document is assigned a unique cluster.
# These are perfect matches hence return 1.0.
if (classes.shape[0] == clusters.shape[0] == 1
or classes.shape[0] == clusters.shape[0] == 0
or classes.shape[0] == clusters.shape[0] == len(labels_true)):
return 1.0
# print "accuracy testing..."
contingency = contingency_matrix(labels_true, labels_pred) #Type: <type 'numpy.ndarray'>:rows are clusters, cols are classes
contingency = -contingency
#print contingency
contingency = contingency.tolist()
m = Munkres() # Best mapping by using Kuhn-Munkres algorithm
map_pairs = m.compute(contingency) #best match to find the minimum cost
sum_value = 0
for key,value in map_pairs:
sum_value = sum_value + contingency[key][value]
return float(-sum_value)/n_samples
示例11: p345
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def p345():
A = [[ 7, 53, 183, 439, 863, 497, 383, 563, 79, 973, 287, 63, 343, 169, 583],
[627, 343, 773, 959, 943, 767, 473, 103, 699, 303, 957, 703, 583, 639, 913],
[447, 283, 463, 29, 23, 487, 463, 993, 119, 883, 327, 493, 423, 159, 743],
[217, 623, 3, 399, 853, 407, 103, 983, 89, 463, 290, 516, 212, 462, 350],
[960, 376, 682, 962, 300, 780, 486, 502, 912, 800, 250, 346, 172, 812, 350],
[870, 456, 192, 162, 593, 473, 915, 45, 989, 873, 823, 965, 425, 329, 803],
[973, 965, 905, 919, 133, 673, 665, 235, 509, 613, 673, 815, 165, 992, 326],
[322, 148, 972, 962, 286, 255, 941, 541, 265, 323, 925, 281, 601, 95, 973],
[445, 721, 11, 525, 473, 65, 511, 164, 138, 672, 18, 428, 154, 448, 848],
[414, 456, 310, 312, 798, 104, 566, 520, 302, 248, 694, 976, 430, 392, 198],
[184, 829, 373, 181, 631, 101, 969, 613, 840, 740, 778, 458, 284, 760, 390],
[821, 461, 843, 513, 17, 901, 711, 993, 293, 157, 274, 94, 192, 156, 574],
[ 34, 124, 4, 878, 450, 476, 712, 914, 838, 669, 875, 299, 823, 329, 699],
[815, 559, 813, 459, 522, 788, 168, 586, 966, 232, 308, 833, 251, 631, 107],
[813, 883, 451, 509, 615, 77, 281, 613, 459, 205, 380, 274, 302, 35, 805]]
for r in range(len(A)):
for c in range(len(A[0])):
A[r][c] *= -1
from munkres import Munkres, print_matrix
m = Munkres()
indexes = m.compute(A)
total = 0
for row, column in indexes:
value = A[row][column]
total += value
return -total
示例12: hun
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def hun(costMatrix):
# Check first, if costmatrix is not empty
if costMatrix.shape==(0,0):
return []
# Create squared temporary matrix
tmpMatrix = numpy.copy(costMatrix)
tmpMatrix = makeSquareWithNegValues(tmpMatrix)
sqCostMatrix = numpy.copy(tmpMatrix)
sqCostMatrix[tmpMatrix==-1]=10e10
# Solve ASP on the temporary matrix
m=Munkres()
i=m.compute(sqCostMatrix)
# Create resultin matrix that contains ones at matching
# objects and remove all excluded matches
binMatrix = numpy.zeros( tmpMatrix.shape,dtype=bool )
for x,y in i:
if tmpMatrix[x,y]==-1:
continue
binMatrix[x,y]=True
return binMatrix
示例13: eval_result
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def eval_result(labels, result_gen, cache_file):
if path.exists(cache_file):
print "Loading cached result..."
with open(cache_file, "rb") as inf:
lbl_clst = pickle.load(inf)
print "Done."
else:
lbl_clst = result_gen()
print "Saving result to cache..."
with open(cache_file, "wb") as outf:
pickle.dump(lbl_clst, outf)
print "Done."
all_langs = ["da", "de", "el", "en", "es", "fi", "fr", "it", "nl", "pt", "sv"]
print "Constructing cost matrix..."
nObj = len(labels)
nLang = len(all_langs)
G = [[0 for j in range(nLang)] for i in range(nLang)]
for i in range(nLang):
for j in range(nLang):
G[i][j] = -sum([(lbl_clst[k] == i and labels[k] == all_langs[j]) for k in range(nObj)])
print "Finding best mapping..."
m = Munkres()
idx = m.compute(G)
print "Calculating accuracy..."
total = 0
for row, col in idx:
total += G[row][col]
accuracy = -total / float(nObj)
print "Accuracy = %.4f" % accuracy
示例14: align
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def align(sen1, sen2):
"""finds the best mapping of words from one sentence to the other"""
#find lengths
sen1 = list(map(preprocess_word, sen1.split()))
sen2 = list(map(preprocess_word, sen2.split()))
lengthDif = len(sen1) - len(sen2)
if lengthDif > 0:
shorter = sen2
longer = sen1
else:
shorter = sen1
longer = sen2
lengthDif = abs(lengthDif)
shorter += ["emptyWord"] * lengthDif
#create matrix
matrix = np.zeros((len(longer), len(longer)))
for i in range(len(longer)):
for j in range(len(longer) - lengthDif):
matrix[i,j] = distance.levenshtein(longer[i], shorter[j])
print(matrix)
#compare with munkres
m = Munkres()
indexes = m.compute(matrix)
print("mapping is:",[(shorter[i], longer[j]) for (i,j) in indexes])
示例15: maximum_weight_bipartite
# 需要导入模块: from munkres import Munkres [as 别名]
# 或者: from munkres.Munkres import compute [as 别名]
def maximum_weight_bipartite(matrix):
cost_matrix = make_cost_matrix(matrix, lambda cost: 100000 - cost)
m = Munkres()
indices = m.compute(cost_matrix)
return indices