• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python munkres.make_cost_matrix函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中munkres.make_cost_matrix函数的典型用法代码示例。如果您正苦于以下问题:Python make_cost_matrix函数的具体用法?Python make_cost_matrix怎么用?Python make_cost_matrix使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: make_cost_matrix

 def make_cost_matrix(profit_matrix, inversion_function):
     """
     **DEPRECATED**
     Please use the module function ``make_cost_matrix()``.
     """
     import munkres
     return munkres.make_cost_matrix(profit_matrix, inversion_function)
开发者ID:swapnil96,项目名称:Online-Judge-Contest,代码行数:7,代码来源:clock.py


示例2: similar

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
开发者ID:sachin207,项目名称:academics,代码行数:26,代码来源:similarity_graph.py


示例3: calc_hungarian_alignment_score

    def calc_hungarian_alignment_score(self, s, t):
        """Calculate the alignment score between the two texts s and t
        using the implementation of the Hungarian alignment algorithm
        provided in https://pypi.python.org/pypi/munkres/."""
        s_toks = get_tokenized_lemmas(s)
        t_toks = get_tokenized_lemmas(t)
        #print("#### new ppdb calculation ####")
        #print(s_toks)
        #print(t_toks)
        df = pd.DataFrame(index=s_toks, columns=t_toks, data=0.)

        for c in s_toks:
            for a in t_toks:
                df.ix[c, a] = self.compute_paraphrase_score(c, a)

        matrix = df.values
        cost_matrix = make_cost_matrix(matrix, lambda cost: _max_ppdb_score - cost)

        indexes = _munk.compute(cost_matrix)
        total = 0.0
        for row, column in indexes:
            value = matrix[row][column]
            total += value
        #print(s + ' || ' + t + ' :' + str(indexes) + ' - ' + str(total / float(np.min(matrix.shape))))

        # original procedure returns indexes and score - i do not see any use for the indexes as a feature
        # return indexes, total / float(np.min(matrix.shape))
        return total / float(np.min(matrix.shape))
开发者ID:paris5020,项目名称:athene_system,代码行数:28,代码来源:hungarian_alignment.py


示例4: maximum_weight_bipartite

def maximum_weight_bipartite(matrix):
    cost_matrix = make_cost_matrix(matrix, lambda cost: 100000 - cost)

    m = Munkres()
    indices = m.compute(cost_matrix)

    return indices
开发者ID:kmwenja,项目名称:ftm,代码行数:7,代码来源:utils.py


示例5: get_suitability_score

    def get_suitability_score(customer_list, product_list):
        '''
        calculate the total maximum suitability score
        by using munkres algorithm and returns a detailed
        customer_product_enties & total suitability score
        '''
        suitability_scores = []
        customer_suitability_scores = []

        for customer in customer_list:
            for product in product_list:
                customer_suitability_scores.append(SuitabilityScore.calculate_suitability_score(customer,product))
            suitability_scores.append(customer_suitability_scores)
            customer_suitability_scores = []


        customer_product_entries = []
        cost_matrix = make_cost_matrix(suitability_scores, lambda cost: 1e10 - cost)
        munkres = Munkres()
        indexes = munkres.compute(cost_matrix)
        total_suitability_score = 0
        for customer_index, product_index  in indexes:
            suitability_score = suitability_scores[customer_index][product_index]
            total_suitability_score += suitability_score
            suitability_score_entry = SuitabilityScoreEntry(customer_list[customer_index],product_list[product_index],suitability_score)
            customer_product_entries.append(suitability_score_entry)
            #print(customer_index,product_index)

        return customer_product_entries,total_suitability_score
开发者ID:kabary,项目名称:python,代码行数:29,代码来源:suitabilityscore.py


示例6: filter_rects

def filter_rects(all_rects, threshold, input_rects=[], max_threshold=1.0, config=None):
    """Takes in all_rects and based on the threshold carries out the stitching process
    as described in the paper."""

    accepted_rects = input_rects

    for i in range(0, config["grid_height"], 1):
        for j in range(0, config["grid_width"], 1):
            relevant_rects = []
            current_rects = [r for r in all_rects[i][j] if r.confidence > threshold]

            for other in accepted_rects:
                for current in current_rects:
                    if other.overlaps(current):
                        relevant_rects.append(other)
                        break

            if len(relevant_rects) == 0 or len(current_rects) == 0:
                accepted_rects += current_rects
                continue

            matrix = []
            for c in current_rects:
                row = []
                for a in relevant_rects:
                    row.append(1000)
                    if a.overlaps(c):
                        row[-1] -=100
                    row[-1] += a.distance(c) / 1000.0
                matrix.append(row)

            m = Munkres()
            cost_matrix = make_cost_matrix(matrix, lambda x: x)
            indices = m.compute(matrix)

            bad = set()
            for row, column in indices:
                c = current_rects[row]
                a = relevant_rects[column]
                if c.confidence > max_threshold:
                    bad.add(row)
                    continue
                if c.overlaps(a):
                    if c.confidence > a.confidence and c.iou(a) > 0.7:
                        c.true_confidence = a.confidence
                        accepted_rects.remove(a)
                    else:
                        bad.add(row)

            for k in range(len(current_rects)):
                if k not in bad:
                    accepted_rects.append(current_rects[k])

    return accepted_rects
开发者ID:andriluka,项目名称:ReInspect,代码行数:54,代码来源:__init__.py


示例7: compute_agreements

def compute_agreements(similarity):
    import munkres
    import numpy as np

    m = munkres.Munkres()
    print("Computing mapping...")
    similarity = munkres.make_cost_matrix(similarity, lambda cost: 1 - cost)
    indexes = m.compute(similarity)

    agreement = np.sum([1 - similarity[r][c] for r, c in indexes]) / len(similarity)
    print("Agreement:", agreement)
    return agreement
开发者ID:dnola,项目名称:285J_Twitter,代码行数:12,代码来源:stability_evaluation.py


示例8: test_profit

def test_profit():
    profit_matrix = [[94, 66, 100, 18, 48],
                     [51, 63, 97, 79, 11],
                     [37, 53, 57, 78, 28],
                     [59, 43, 97, 88, 48],
                     [52, 19, 89, 60, 60]]
    import sys
    cost_matrix = munkres.make_cost_matrix(
        profit_matrix, lambda cost: sys.maxsize - cost
    )
    indices = m.compute(cost_matrix)
    profit = sum([profit_matrix[row][column] for row, column in indices])
    assert_equals(profit, 392)
开发者ID:bmc,项目名称:munkres,代码行数:13,代码来源:test_munkres.py


示例9: matching

def matching(male_distances):
    cost_matrix = munkres.make_cost_matrix(male_distances,
                                           lambda cost: 1.0 - cost)
    m = Munkres()
    indices = m.compute(cost_matrix)
    total = 0.0
    pairings = {}
    for row, column in indices:
        value = male_distances[row][column]
        total += value
        pairings[column] = [row]
    #print "Satish was here"
    print 'total profit=%f' % total
    return pairings
开发者ID:dw236,项目名称:plusone,代码行数:14,代码来源:util.py


示例10: do_hungarian_assignment

def do_hungarian_assignment(dict_a, dict_b, cost_func, yield_condt, cost_matrix_func=None):
    for ka  in dict_a.keys():
        if ka in dict_b:
            ia  = dict_a[ka]
            ib  = dict_b[ka]
            mat = [ [cost_func(a,b) for b in ib] for a in ia]
            #max similarity calculation
            c_mat = None
            if cost_matrix_func is not None:
                c_mat = make_cost_matrix(mat,cost_matrix_func)
            else:
                c_mat = mat
            indexes = MUNKR.compute(c_mat)
            for row, col in indexes:
                # yield only if condition satisfied
                if yield_condt(mat[row][col]):
                    #print '(%d, %d) -> %d' % (row, col, mat[row][col])
                    yield ia[row], ib[col]
开发者ID:Tskatom,项目名称:Finance,代码行数:18,代码来源:utils.py


示例11: make_match

def make_match(advertisers, persons, ctrfunc = funky_ctr):
    # make the ctr matrix
    ctr_matrix = make_ctr_matrix(advertisers, persons, ctrfunc)

    # convert it to a cost matrix by subtracting all values from a larger value
    cost_matrix = make_cost_matrix(ctr_matrix, lambda ctr: sys.maxsize - ctr)

    # compute the match
    match = Munkres().compute(cost_matrix)

    # elements in match are two-element lists, where the first is the
    # index into advertisers and second is index into persons

    # compute the total ctr by looking up the match elements in the ctr
    # matrix
    total_ctr = sum(map(lambda pair: ctr_matrix[pair[0]][pair[1]], match))

    return match, total_ctr
开发者ID:steve-goldman,项目名称:ad_matcher,代码行数:18,代码来源:ad_matcher.py


示例12: assignDuties

def assignDuties(dayA, dayB):
    if len(dayA) != len(dayB):
        print "Illegal!! number of duties should be equal every day"
        exit(1)
    matrix = createMatrix(len(dayA))
    ##Fill the matrix with the similarities
    for i in range(len(dayA)):
        for j in range(len(dayA)):
            matrix[i][j] = calcSimilarity(dayA[i], dayB[j])
    ##The following line is called to make sure we find the maximum sum and not the minimum
    ##Note that since all similarities are in [0,1] 2 is bigger than all.
    cost_matrix = make_cost_matrix(matrix, lambda cost: 2 - cost)
    m = Munkres()
    ##Indexes will contain the assignment
    indexes = m.compute(cost_matrix)
    res = []
    for row, column in indexes:
        res.append(("Driver "+str(row + 1) ,("Day 1 duty: "+str(row + 1),"Day 2 duty: "+str(column + 1))))
    return res
开发者ID:kalechstain,项目名称:Optibus,代码行数:19,代码来源:Optibus.py


示例13: get_best_matching

def get_best_matching(source_corpus, target_corpus, scores):
    stripper = LanguageStripper()
    err = 0

    m = munkres.Munkres()
    cost_matrix = munkres.make_cost_matrix(scores, lambda cost: 1 - cost)
    indexes = m.compute(cost_matrix)

    for row, column in indexes:
        s_url = source_corpus.keys()[row]
        t_url = target_corpus.keys()[column]
        success = stripper.strip(t_url) == stripper.strip(s_url)
        if not success:
            err += 1
        # sys.stdout.write("%f\t%s\t%s\t%s\n" %
        #                  (scores[row, column], success, s_url, t_url))

    n = min(len(source_corpus), len(target_corpus))
    sys.stderr.write("Correct: %d out of %d = %f%%\n" %
                     (n - err, n, (1. * n - err) / n))
开发者ID:christianbuck,项目名称:CorpusMining,代码行数:20,代码来源:matching.py


示例14: calc_hungarian_alignment_score

def calc_hungarian_alignment_score(s, t):
    """Calculate the alignment score between the two texts s and t
    using the implementation of the Hungarian alignment algorithm
    provided in https://pypi.python.org/pypi/munkres/."""
    s_toks = get_tokenized_lemmas(s)
    t_toks = get_tokenized_lemmas(t)

    df = pd.DataFrame(index=s_toks, columns=t_toks, data=0.)

    for c in s_toks:
        for a in t_toks:
            df.ix[c, a] = compute_paraphrase_score(c, a)

    matrix = df.values
    cost_matrix = make_cost_matrix(matrix, lambda cost: _max_ppdb_score - cost)

    indexes = _munk.compute(cost_matrix)
    total = 0.0
    for row, column in indexes:
        value = matrix[row][column]
        total += value
    return indexes, total / float(np.min(matrix.shape))
开发者ID:paris5020,项目名称:athene_system,代码行数:22,代码来源:run_calc_hungarian_alignment_score.py


示例15: hungarianAssignment

def hungarianAssignment(cases, controls, numberOfControlsPerCase):
    selectedControls = list()
    convFactor = 100000.00
    m = list()
    for control in controls:
        row = list()
        for _ in xrange(numberOfControlsPerCase):
            row += [(control.relatedTo.get(case) if (control.relatedTo.has_key(case)) else 0) for case in cases]
        m.append(row)
    cm = munkres.make_cost_matrix(m, lambda cost: convFactor - cost * convFactor)
    matrix = cm
    m = Munkres()
    indexes = m.compute(matrix)
    total = 0
    for row, column in indexes:
        value = matrix[row][column]
        total += value
        if value < convFactor:
            selectedControls.append(controls[row % len(controls)])
    print("\tassignment kic score: %f" % (float(len(indexes) * convFactor - total) / convFactor))
    print("\tall kic score: %f" % (kicScore(cases, selectedControls)))
    return [person.id for person in selectedControls]
开发者ID:rsippy,项目名称:PHlth903,代码行数:22,代码来源:casel.py


示例16: linkTemplates

    def linkTemplates(self, sentence):
        """ link group size and group templates using Hungarian matching algorithm """
        templates = sentence.templates
        qTemplateList = templates.getList(self.quantityType)
        mTemplateList = templates.getList(self.mentionType)

        nQuantities = len(qTemplateList)
        nMentions = len(mTemplateList)
        maxSize = max(nQuantities, nMentions)

        if nQuantities == 0 or nMentions == 0:
            return

        probMatrix = []
        for qIdx in range(maxSize):
            probMatrix.append([])
            for mIdx in range(maxSize):
                probMatrix[qIdx].append(0)

        for fv in templates.featureVectors:
            probMatrix[fv.valueId][fv.mentionId] = fv.prob * 1000

        costMatrix = munkres.make_cost_matrix(probMatrix, lambda cost: 1000 - cost)
        m = munkres.Munkres()
        #    print probMatrix
        #    print costMatrix
        indices = m.compute(costMatrix)
        for qIdx, mIdx in indices:
            if qIdx < nQuantities and mIdx < nMentions:
                prob = probMatrix[qIdx][mIdx]
                if prob >= 500:
                    # this quantity and mention should be associated
                    prob = float(prob) / 1000
                    qTemplate = qTemplateList[qIdx]
                    mTemplate = mTemplateList[mIdx]
                    self.linkQuantityAndMention(qTemplate, mTemplate, prob)
开发者ID:rlsummerscales,项目名称:acres,代码行数:36,代码来源:groupsizegroupassociator.py


示例17: costify

def costify(similarity_matrix):
    """Transform a similarity matrix into a cost matrix."""
    return munkres.make_cost_matrix(similarity_matrix, lambda s: 1 - s)
开发者ID:query,项目名称:mt-submissions,代码行数:3,代码来源:meant.py


示例18: cost_matrix

def cost_matrix(contingency_table):
    """Hungarian method assumes the goal of minimum cost, while our goal with a
    contigency table is maximum cost. To deal with this, the table is inverted in
    an additive sense.
    """
    return make_cost_matrix(contingency_table, lambda cost: sys.maxsize - cost)
开发者ID:koadman,项目名称:proxigenomics,代码行数:6,代码来源:f1score.py


示例19: linkTemplatesHungarian

    def linkTemplatesHungarian(self, sentence):
        """ link group size and group templates using Hungarian matching algorithm """
        #    print 'linking all templates'
        templates = sentence.templates
        costValueList = templates.getList('cost_value')
        outcomeList = templates.getList('outcome')
        groupList = templates.getList('group')

        nCostValues = len(costValueList)
        nGroupOutcomePairs = len(outcomeList)*len(groupList)

        if nGroupOutcomePairs == 0 or nCostValues == 0:
            return

        maxSize = max(nCostValues, nGroupOutcomePairs)

        # build list of group-outcome pairs
        goPairs = []
        for group in groupList:
            for outcome in outcomeList:
                goPairs.append((group, outcome))

        # initialize cost matrix for matching cost values with group,outcome pairs
        probMatrix = []
        probMultiplier = 100000

        for cvIdx in range(maxSize):
            probMatrix.append([])
            for goIdx in range(maxSize):
                if cvIdx < nCostValues and goIdx < nGroupOutcomePairs:
                    cv = costValueList[cvIdx]
                    (group, outcome) = goPairs[goIdx]

                    outcomeFV = cv.getMatchFeatures(outcome)
                    groupFV = cv.getMatchFeatures(group)
                    groupProb = groupFV.prob
                    outcomeProb = outcomeFV.prob
                    prob = round(groupProb * outcomeProb * probMultiplier)
                else:
                    # no association can be made
                    # this possible match involves either a dummy cost value or a dummy (group,outcome) pair
                    prob = 0

                probMatrix[cvIdx].append(prob)

        costMatrix = munkres.make_cost_matrix(probMatrix, lambda cost: probMultiplier - cost)
        m = munkres.Munkres()
        #    print probMatrix
        #    print costMatrix
        indices = m.compute(costMatrix)
        # threshold is (1/2)^4
        # threshold = 0.0625 * probMultiplier
        threshold = 0.0001 * probMultiplier
        #    threshold = 0.25 * probMultiplier

        for cvIdx, goIdx in indices:
            if cvIdx < nCostValues and goIdx < nGroupOutcomePairs:
                prob = probMatrix[cvIdx][goIdx]
                if prob > threshold:
                    # this quantity and mention should be associated
                    prob = float(prob) / probMultiplier
                    om = costValueList[cvIdx]
                    (group, outcome) = goPairs[goIdx]
                    self.linkOutcomeMeasurementAssociations(om, group, outcome, prob)
开发者ID:rlsummerscales,项目名称:acres,代码行数:64,代码来源:costeffectivenessassociator.py


示例20:

gmm_model = sklmix.GMM(n_components=3, covariance_type='full')
gmm_model.fit(iris[['PW', 'PL', 'SW']])
yhat = gmm_model.predict(iris[['PW', 'PL', 'SW']])
crosstab = pd.crosstab(iris['Type'], yhat, rownames=['true'], colnames=['predicted'])
print crosstab

# <headingcell level=4>

# Align the confusion matrix with a non-standard package

# <codecell>

import munkres
import sys
m = munkres.Munkres()
cost = munkres.make_cost_matrix(crosstab.values.tolist(), lambda x : sys.maxint - x)
align = m.compute(cost)
print align, '\n'

permute = [x[1] for x in align]
new_label = np.argsort(permute)
yhat_new = new_label[yhat]
print pd.crosstab(iris['Type'], yhat_new, rownames=['true'], colnames=['predicted'])

# <headingcell level=4>

# Bridging the gap with Rpy2

# <codecell>

from rpy2.robjects import r
开发者ID:joseramoncajide,项目名称:public_talks,代码行数:31,代码来源:statBytes-python.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python munkres.Munkres类代码示例发布时间:2022-05-27
下一篇:
Python munkilib.FoundationPlist类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap