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


Python Factor.setProbability方法代码示例

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


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

示例1: inferenceByLikelihoodWeightingSampling

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def inferenceByLikelihoodWeightingSampling(bayesNet, queryVariables, evidenceDict, numSamples):
        """
        Question 6: Inference by likelihood weighted sampling

        This function should perform a probabilistic inference query that
        returns the factor:

        P(queryVariables | evidenceDict)

        It should perform inference by performing likelihood weighting
        sampling.  It should sample numSamples times.

        In order for the autograder's solution to match yours, 
        your outer loop needs to iterate over the number of samples, 
        with the inner loop sampling from each variable's factor.
        Use the ordering of variables provided by BayesNet.linearizeVariables in 
        your inner loop so that the order of samples matches the autograder's.
        There are typically many linearization orders of a directed acyclic 
        graph (DAG), however we just use a particular one.

        The sum of the probabilities should sum to one (so that it is a true 
        conditional probability, conditioned on the evidence).

        bayesNet:       The Bayes Net on which we are making a query.
        queryVariables: A list of the variables which are unconditioned in
                        the inference query.
        evidenceDict:   An assignment dict {variable : value} for the
                        variables which are presented as evidence
                        (conditioned) in the inference query. 
        numSamples:     The number of samples that should be taken.


        Useful functions:
        sampleFromFactor
        normalize
        BayesNet.getCPT
        BayesNet.linearizeVariables
        """

        sampleFromFactor = sampleFromFactorRandomSource(randomSource)

        "*** YOUR CODE HERE ***"
        unconditioned = evidenceDict.keys()
        new_domain = bayesNet.getReducedVariableDomains(evidenceDict)
        new_factor = Factor(queryVariables, unconditioned, new_domain)
        for x in range(0, numSamples):
            assignment_dict = {}
            sample = [1]
            linearized_var = bayesNet.linearizeVariables()
            for var in linearized_var:
                var_cpt = bayesNet.getCPT(var)
                if var in unconditioned:
                    assignment_dict[var] = evidenceDict[var]
                    sample.append(var_cpt.getProbability(assignment_dict))
                else:
                    assignment_dict[var] = sampleFromFactor(var_cpt, assignment_dict)[var]
            prob = reduce(lambda x, y: x*y, sample)
            new_factor.setProbability(assignment_dict, new_factor.getProbability(assignment_dict) + prob)
        new_factor = normalize(new_factor)
        return new_factor
开发者ID:philigobears,项目名称:PacMan,代码行数:62,代码来源:inference.py

示例2: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 2: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        unconditioned = factor.unconditionedVariables()
        unconditioned.remove(eliminationVariable)
        newFactor = Factor(unconditioned, factor.conditionedVariables(),factor.variableDomainsDict())

        tempProbTable = dict()
        allAssignments = factor.getAllPossibleAssignmentDicts()
        for assignment in allAssignments:
            prunedAssignment = {key:value for key,value in assignment.items() if key != eliminationVariable}
            prunedAssignment = frozenset(prunedAssignment.items())
            if prunedAssignment not in tempProbTable:
                tempProbTable[prunedAssignment] = 0
            tempProbTable[prunedAssignment] += factor.getProbability(assignment)
        for assignment in tempProbTable:
            defrozenAssignment = dict(assignment)
            newFactor.setProbability(defrozenAssignment,tempProbTable[assignment])
        return newFactor
开发者ID:KentZiqi,项目名称:bayes,代码行数:61,代码来源:factorOperations.py

示例3: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 4: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        "*** YOUR CODE HERE ***"
        unCondVar = factor.unconditionedVariables()
        unCondVar.remove(eliminationVariable)
        condVar = factor.conditionedVariables()
        varDomainsDict = factor.variableDomainsDict()
        result = Factor(unCondVar, condVar, varDomainsDict)
        
        for assignmentDict in result.getAllPossibleAssignmentDicts():
            prob = 0
            for eliminationValue in varDomainsDict[eliminationVariable]:
                assignmentDictCopy = assignmentDict
                assignmentDictCopy[eliminationVariable] = eliminationValue
                prob += factor.getProbability(assignmentDictCopy)
            result.setProbability(assignmentDict, prob)

        return result
开发者ID:JunTan,项目名称:DVC,代码行数:61,代码来源:factorOperations.py

示例4: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 4: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        "*** YOUR CODE HERE ***"
        # Note: "reduced" indicates its the unconditioned variables minus the elimVar, and "full" means its all the starting unconditioned variables
        reducedUnconditionedVariables = factor.unconditionedVariables()
        reducedUnconditionedVariables.remove(eliminationVariable)
        reducedFactor = Factor(reducedUnconditionedVariables, factor.conditionedVariables(), factor.variableDomainsDict())

        for reducedAssignment in reducedFactor.getAllPossibleAssignmentDicts():
            prob = 0
            for elimVarVal in factor.variableDomainsDict()[eliminationVariable]:
                fullAssignment = reducedAssignment
                fullAssignment[eliminationVariable] = elimVarVal

                prob = prob + factor.getProbability(fullAssignment)
            reducedFactor.setProbability(reducedAssignment, prob)

        return reducedFactor
开发者ID:yttfwang,项目名称:cs188-proj4,代码行数:61,代码来源:factorOperations.py

示例5: normalize

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
def normalize(factor):
    """
    Question 5: Your normalize implementation 

    Input factor is a single factor.

    The set of conditioned variables for the normalized factor consists 
    of the input factor's conditioned variables as well as any of the 
    input factor's unconditioned variables with exactly one entry in their 
    domain.  Since there is only one entry in that variable's domain, we 
    can either assume it was assigned as evidence to have only one variable 
    in its domain, or it only had one entry in its domain to begin with.
    This blurs the distinction between evidence assignments and variables 
    with single value domains, but that is alright since we have to assign 
    variables that only have one value in their domain to that single value.

    Return a new factor where the sum of the all the probabilities in the table is 1.
    This should be a new factor, not a modification of this factor in place.

    If the sum of probabilities in the input factor is 0,
    you should return None.

    This is intended to be used at the end of a probabilistic inference query.
    Because of this, all variables that have more than one element in their 
    domain are assumed to be unconditioned.
    There are more general implementations of normalize, but we will only 
    implement this version.

    Useful functions:
    Factor.getAllPossibleAssignmentDicts
    Factor.getProbability
    Factor.setProbability
    Factor.unconditionedVariables
    Factor.conditionedVariables
    Factor.variableDomainsDict
    """

    # typecheck portion
    variableDomainsDict = factor.variableDomainsDict()
    for conditionedVariable in factor.conditionedVariables():
        if len(variableDomainsDict[conditionedVariable]) > 1:
            print "Factor failed normalize typecheck: ", factor
            raise ValueError, ("The factor to be normalized must have only one " + \
                            "assignment of the \n" + "conditional variables, " + \
                            "so that total probability will sum to 1\n" + 
                            str(factor))

    unconditioned_variables = set(filter(lambda var: len(factor.variableDomainsDict()[var]) != 1, factor.unconditionedVariables()))
    conditioned_variables = set(factor.conditionedVariables()).union(filter(lambda var: len(factor.variableDomainsDict()[var]) == 1, 
        factor.unconditionedVariables()))

    normalized = Factor(unconditioned_variables, conditioned_variables, factor.variableDomainsDict())

    total_prob = sum([factor.getProbability(ass) for ass in factor.getAllPossibleAssignmentDicts()])

    for ass in normalized.getAllPossibleAssignmentDicts():
        normalized.setProbability(ass, factor.getProbability(ass) / total_prob)

    return normalized
开发者ID:j3nnahuang,项目名称:python,代码行数:61,代码来源:factorOperations.py

示例6: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
def joinFactors(factors):
    """
    Question 3: Your join implementation 

    Input factors is a list of factors.  
    
    You should calculate the set of unconditioned variables and conditioned 
    variables for the join of those factors.

    Return a new factor that has those variables and whose probability entries 
    are product of the corresponding rows of the input factors.

    You may assume that the variableDomainsDict for all the input 
    factors are the same, since they come from the same BayesNet.

    joinFactors will only allow unconditionedVariables to appear in 
    one input factor (so their join is well defined).

    Hint: Factor methods that take an assignmentDict as input 
    (such as getProbability and setProbability) can handle 
    assignmentDicts that assign more variables than are in that factor.

    Useful functions:
    Factor.getAllPossibleAssignmentDicts
    Factor.getProbability
    Factor.setProbability
    Factor.unconditionedVariables
    Factor.conditionedVariables
    Factor.variableDomainsDict
    """

    # typecheck portion
    setsOfUnconditioned = [set(factor.unconditionedVariables()) for factor in factors]
    setsOfConditioned = [set(factor.conditionedVariables()) for factor in factors]
    factors_domains = [factor.variableDomainsDict() for factor in factors]

    if len(factors) > 1:
        intersect = reduce(lambda x, y: x & y, setsOfUnconditioned)
        if len(intersect) > 0:
            print "Factor failed joinFactors typecheck: ", factor
            raise ValueError, ("unconditionedVariables can only appear in one factor. \n"
                    + "unconditionedVariables: " + str(intersect) + 
                    "\nappear in more than one input factor.\n" + 
                    "Input factors: \n" +
                    "\n".join(map(str, factors)))
        else:
            final_uncondition = reduce(lambda x, y: x | y, setsOfUnconditioned)
            final_condition = reduce(lambda x, y: x | y, setsOfConditioned)-final_uncondition
            final_domain = reduce(lambda x, y: dict(x.items()+y.items()), factors_domains)
            new_factor = Factor(final_uncondition, final_condition,final_domain)
            for assign_large in new_factor.getAllPossibleAssignmentDicts():
                assign_large_prob = 1
                for small_factor in factors:
                    # print(small_factor)
                    assign_large_prob *= small_factor.getProbability(get_new_assig(assign_large,small_factor))
                new_factor.setProbability(assign_large,assign_large_prob)
            return new_factor
    else:
        return factors[0]
开发者ID:yujianyu,项目名称:berkeley_summer_session,代码行数:61,代码来源:factorOperations.py

示例7: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 2: Your eliminate implementation 
        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.
        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.
        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        "*** YOUR CODE HERE ***"
        variableDomains         = factor.variableDomainsDict()
        conditionedVariables    = factor.conditionedVariables()
        unconditionedVariables  = factor.unconditionedVariables()
        if eliminationVariable in conditionedVariables:
            conditionedVariables.remove(eliminationVariable)
        if eliminationVariable in unconditionedVariables:
            unconditionedVariables.remove(eliminationVariable)
        del variableDomains[eliminationVariable]
        newFactor       = Factor(unconditionedVariables, conditionedVariables, variableDomains)
        newAssignments  = newFactor.getAllPossibleAssignmentDicts()
        assignments     = factor.getAllPossibleAssignmentDicts()
        for newAssignment in newAssignments:
            runningProbability = 0
            for assignment in assignments:
                if isSubset(assignment, newAssignment):
                    runningProbability += factor.getProbability(assignment)
            newFactor.setProbability(newAssignment, runningProbability)
        return newFactor
开发者ID:chashao,项目名称:CS188,代码行数:61,代码来源:factorOperations.py

示例8: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 4: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        else:
            new_condition = factor.conditionedVariables()
            new_uncondition = factor.unconditionedVariables() - set([eliminationVariable])
            eliminate_factor = Factor(new_uncondition, new_condition, factor.variableDomainsDict())
            # print(factor.unconditionedVariables(),eliminationVariable)
            # print(eliminate_factor)
            for assignment in factor.getAllPossibleAssignmentDicts():
                small_assign = get_new_assig(assignment, eliminate_factor)
                if eliminate_factor.getProbability(small_assign) != 0:
                    eliminate_factor.setProbability(small_assign, factor.getProbability(assignment)+eliminate_factor.getProbability(small_assign)) 
                else:
                    eliminate_factor.setProbability(small_assign, factor.getProbability(assignment))

            return eliminate_factor
开发者ID:yujianyu,项目名称:berkeley_summer_session,代码行数:59,代码来源:factorOperations.py

示例9: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 2: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        "*** YOUR CODE HERE ***"
        new_unconditioned = factor.unconditionedVariables()
        new_unconditioned.remove(eliminationVariable)
        new_Factor = Factor(new_unconditioned,factor.conditionedVariables(), factor.variableDomainsDict())
        for j in new_Factor.getAllPossibleAssignmentDicts():
            probabilitySum = 0
            for i in new_Factor.variableDomainsDict().get(eliminationVariable):
                j[eliminationVariable] = i
                currentProb = factor.getProbability(j)
                probabilitySum += currentProb
                del j[eliminationVariable]
            new_Factor.setProbability(j, probabilitySum)
        return new_Factor
开发者ID:xldennis,项目名称:Artificial-Intelligence,代码行数:58,代码来源:factorOperations.py

示例10: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def eliminate(factor, eliminationVariable):
        """
        Question 2: Your eliminate implementation 

        Input factor is a single factor.
        Input eliminationVariable is the variable to eliminate from factor.
        eliminationVariable must be an unconditioned variable in factor.
        
        You should calculate the set of unconditioned variables and conditioned 
        variables for the factor obtained by eliminating the variable
        eliminationVariable.

        Return a new factor where all of the rows mentioning
        eliminationVariable are summed with rows that match
        assignments on the other variables.

        Useful functions:
        Factor.getAllPossibleAssignmentDicts
        Factor.getProbability
        Factor.setProbability
        Factor.unconditionedVariables
        Factor.conditionedVariables
        Factor.variableDomainsDict
        """
        # autograder tracking -- don't remove
        if not (callTrackingList is None):
            callTrackingList.append(('eliminate', eliminationVariable))

        # typecheck portion
        if eliminationVariable not in factor.unconditionedVariables():
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Elimination variable is not an unconditioned variable " \
                            + "in this factor\n" + 
                            "eliminationVariable: " + str(eliminationVariable) + \
                            "\nunconditionedVariables:" + str(factor.unconditionedVariables()))
        
        if len(factor.unconditionedVariables()) == 1:
            print "Factor failed eliminate typecheck: ", factor
            raise ValueError, ("Factor has only one unconditioned variable, so you " \
                    + "can't eliminate \nthat variable.\n" + \
                    "eliminationVariable:" + str(eliminationVariable) + "\n" +\
                    "unconditionedVariables: " + str(factor.unconditionedVariables()))

        "*** YOUR CODE HERE ***"
        #uncondVarSet = set()
        condVarSet = factor.conditionedVariables()
        uncondVarSet = factor.unconditionedVariables()
        uncondVarSet.remove(eliminationVariable) #removes elimination variable
        newFactor = Factor(uncondVarSet, condVarSet, factor.variableDomainsDict()) 
        for assignment in newFactor.getAllPossibleAssignmentDicts():
            probSum = 0
            for val in factor.variableDomainsDict()[eliminationVariable]: 
                assignment[eliminationVariable] = val
                probSum += factor.getProbability(assignment) #obtain probability of all assignments affiliated to entry add to other rows it matches with
            newFactor.setProbability(assignment, probSum)
        return newFactor
开发者ID:ErickAndres,项目名称:cs188su15,代码行数:58,代码来源:factorOperations.py

示例11: inferenceByLikelihoodWeightingSampling

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def inferenceByLikelihoodWeightingSampling(bayesNet, queryVariables, evidenceDict, numSamples):
        """
        Question 7: Inference by likelihood weighted sampling

        This function should perform a probabilistic inference query that
        returns the factor:

        P(queryVariables | evidenceDict)

        It should perform inference by performing likelihood weighting
        sampling.  It should sample numSamples times.

        In order for the autograder's solution to match yours, 
        your outer loop needs to iterate over the number of samples, 
        with the inner loop sampling from each variable's factor.
        Use the ordering of variables provided by BayesNet.linearizeVariables in 
        your inner loop so that the order of samples matches the autograder's.
        There are typically many linearization orders of a directed acyclic 
        graph (DAG), however we just use a particular one.

        The sum of the probabilities should sum to one (so that it is a true 
        conditional probability, conditioned on the evidence).

        bayesNet:       The Bayes Net on which we are making a query.
        queryVariables: A list of the variables which are unconditioned in
                        the inference query.
        evidenceDict:   An assignment dict {variable : value} for the
                        variables which are presented as evidence
                        (conditioned) in the inference query. 
        numSamples:     The number of samples that should be taken.


        Useful functions:
        sampleFromFactor
        normalize
        BayesNet.getCPT
        BayesNet.linearizeVariables
        """

        sampleFromFactor = sampleFromFactorRandomSource(randomSource)

        "*** YOUR CODE HERE ***"
        linearVars = bayesNet.linearizeVariables() # queryVariables are unconditional variables
        newFactor = Factor(queryVariables, evidenceDict.keys(), bayesNet.getReducedVariableDomains(evidenceDict)) #keys of evidenceDict are the conditional vars
        for sample in range(numSamples):
            weight = 1
            assignment = dict()
            for variable in linearVars:
                if variable in evidenceDict:
                    assignment[variable] = evidenceDict.get(variable)
                    weight *= bayesNet.getCPT(variable).getProbability(assignment)
                else:
                    assignment.update(sampleFromFactor(bayesNet.getCPT(variable), assignment))
            newFactor.setProbability(assignment, weight + newFactor.getProbability(assignment))
        return normalize(newFactor)
开发者ID:ErickAndres,项目名称:cs188su15,代码行数:57,代码来源:inference.py

示例12: inferenceByLikelihoodWeightingSampling

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
    def inferenceByLikelihoodWeightingSampling(bayesNet, queryVariables, evidenceDict, numSamples):
        """
        Question 6: Inference by likelihood weighted sampling

        This function should perform a probabilistic inference query that
        returns the factor:

        P(queryVariables | evidenceDict)

        It should perform inference by performing likelihood weighting
        sampling.  It should sample numSamples times.

        In order for the autograder's solution to match yours, 
        your outer loop needs to iterate over the number of samples, 
        with the inner loop sampling from each variable's factor.
        Use the ordering of variables provided by BayesNet.linearizeVariables in 
        your inner loop so that the order of samples matches the autograder's.
        There are typically many linearization orders of a directed acyclic 
        graph (DAG), however we just use a particular one.

        The sum of the probabilities should sum to one (so that it is a true 
        conditional probability, conditioned on the evidence).

        bayesNet:       The Bayes Net on which we are making a query.
        queryVariables: A list of the variables which are unconditioned in
                        the inference query.
        evidenceDict:   An assignment dict {variable : value} for the
                        variables which are presented as evidence
                        (conditioned) in the inference query. 
        numSamples:     The number of samples that should be taken.


        Useful functions:
        sampleFromFactor
        normalize
        BayesNet.getCPT
        BayesNet.linearizeVariables
        """

        sampleFromFactor = sampleFromFactorRandomSource(randomSource)

        currentFactorsList = bayesNet.getAllCPTsWithEvidence(evidenceDict)
        newFactor = Factor(queryVariables, evidenceDict.keys(), currentFactorsList[0].variableDomainsDict())
        for _ in range(numSamples):
            w = 1.0
            conditionedAssignments = {}
            for variable in bayesNet.linearizeVariables():
                if variable in evidenceDict:
                    conditionedAssignments[variable] = evidenceDict[variable]
                    w = w * bayesNet.getCPT(variable).getProbability(conditionedAssignments)
                else:
                    conditionedAssignments.update(sampleFromFactor(bayesNet.getCPT(variable), conditionedAssignments))
            newFactor.setProbability(conditionedAssignments, w + newFactor.getProbability(conditionedAssignments))
        return normalize(newFactor)
开发者ID:jiajieli,项目名称:bayesNet,代码行数:56,代码来源:inference.py

示例13: joinTwoFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
def joinTwoFactors(factor1,factor2):
    conditionedVariables = set(factor1.conditionedVariables()) | set(factor2.conditionedVariables())
    unconditionedVariables = set(factor1.unconditionedVariables()) | set(factor2.unconditionedVariables())
    conditionedVariables = conditionedVariables - unconditionedVariables
    newFactor = Factor(list(unconditionedVariables),list(conditionedVariables),factor1.variableDomainsDict())
    for assignment in newFactor.getAllPossibleAssignmentDicts():
        variables1 = set(factor1.unconditionedVariables()) | set(factor1.conditionedVariables())
        assignment1 = {key:value for key,value in assignment.items() if key in variables1}
        prob1 = factor1.getProbability(assignment1)
        variables2 = set(factor2.unconditionedVariables()) | set(factor2.conditionedVariables())
        assignment2 = {key:value for key,value in assignment.items() if key in variables2}
        prob2 = factor2.getProbability(assignment2)
        newFactor.setProbability(assignment,prob1*prob2)
    return newFactor
开发者ID:KentZiqi,项目名称:bayes,代码行数:16,代码来源:factorOperations.py

示例14: normalize

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
def normalize(factor):
    """
    Question 3: Your normalize implementation 

    Input factor is a single factor.

    The set of conditioned variables for the normalized factor consists 
    of the input factor's conditioned variables as well as any of the 
    input factor's unconditioned variables with exactly one entry in their 
    domain.  Since there is only one entry in that variable's domain, we 
    can either assume it was assigned as evidence to have only one variable 
    in its domain, or it only had one entry in its domain to begin with.
    This blurs the distinction between evidence assignments and variables 
    with single value domains, but that is alright since we have to assign 
    variables that only have one value in their domain to that single value.

    Return a new factor where the sum of the all the probabilities in the table is 1.
    This should be a new factor, not a modification of this factor in place.

    If the sum of probabilities in the input factor is 0,
    you should return None.

    This is intended to be used at the end of a probabilistic inference query.
    Because of this, all variables that have more than one element in their 
    domain are assumed to be unconditioned.
    There are more general implementations of normalize, but we will only 
    implement this version.

    Useful functions:
    Factor.getAllPossibleAssignmentDicts
    Factor.getProbability
    Factor.setProbability
    Factor.unconditionedVariables
    Factor.conditionedVariables
    Factor.variableDomainsDict
    """

    # typecheck portion
    variableDomainsDict = factor.variableDomainsDict()
    for conditionedVariable in factor.conditionedVariables():
        if len(variableDomainsDict[conditionedVariable]) > 1:
            print "Factor failed normalize typecheck: ", factor
            raise ValueError, ("The factor to be normalized must have only one " + \
                            "assignment of the \n" + "conditional variables, " + \
                            "so that total probability will sum to 1\n" + 
                            str(factor))

    "*** YOUR CODE HERE ***"
    all_possible_assignments = factor.getAllPossibleAssignmentDicts()
    all_unconditioned = factor.unconditionedVariables()
    all_conditioned = factor.conditionedVariables()
    vars_domain = factor.variableDomainsDict()

    for unconditioned in all_unconditioned:
        if(len(vars_domain[unconditioned]) == 1):
            all_unconditioned.remove(unconditioned)
            all_conditioned.append(unconditioned)
    normalized_factor = Factor(all_unconditioned, all_conditioned, vars_domain)

    sum_prob = 0
    for assign in all_possible_assignments:
        sum_prob += factor.getProbability(assign)
    #print sum_prob
    for assign in all_possible_assignments:
        normalized_factor.setProbability(assign, (factor.getProbability(assign)) / sum_prob)

    return normalized_factor
开发者ID:philigobears,项目名称:PacMan,代码行数:69,代码来源:factorOperations.py

示例15: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import setProbability [as 别名]
def joinFactors(factors):
    """
    Question 1: Your join implementation 

    Input factors is a list of factors.  
    
    You should calculate the set of unconditioned variables and conditioned 
    variables for the join of those factors.

    Return a new factor that has those variables and whose probability entries 
    are product of the corresponding rows of the input factors.

    You may assume that the variableDomainsDict for all the input 
    factors are the same, since they come from the same BayesNet.

    joinFactors will only allow unconditionedVariables to appear in 
    one input factor (so their join is well defined).

    Hint: Factor methods that take an assignmentDict as input 
    (such as getProbability and setProbability) can handle 
    assignmentDicts that assign more variables than are in that factor.

    Useful functions:
    Factor.getAllPossibleAssignmentDicts
    Factor.getProbability
    Factor.setProbability
    Factor.unconditionedVariables
    Factor.conditionedVariables
    Factor.variableDomainsDict
    """

    # typecheck portion
    setsOfUnconditioned = [set(factor.unconditionedVariables()) for factor in factors]
    if len(factors) > 1:
        intersect = reduce(lambda x, y: x & y, setsOfUnconditioned)
        if len(intersect) > 0:
            print "Factor failed joinFactors typecheck: ", factor
            raise ValueError, ("unconditionedVariables can only appear in one factor. \n"
                    + "unconditionedVariables: " + str(intersect) + 
                    "\nappear in more than one input factor.\n" + 
                    "Input factors: \n" +
                    "\n".join(map(str, factors)))


    "*** YOUR CODE HERE ***"
    set_of_unconditioned = set(factors[0].unconditionedVariables())
    set_Of_variables = set(factors[0].variables())
    variable_domains = factors[0].variableDomainsDict()
    
    for factor in factors[1:]:
        for var in factor.variables():
            set_Of_variables.add(var)
        for var in factor.unconditionedVariables():
            set_of_unconditioned.add(var)

    set_of_conditioned = set_Of_variables - set_of_unconditioned
    new_factor = Factor(list(set_of_unconditioned), list(set_of_conditioned), variable_domains)
    #print isinstance(new_factor, Factor)
    all_possible_assignments = new_factor.getAllPossibleAssignmentDicts()

    for assignment in all_possible_assignments:
        prob = factors[0].getProbability(assignment)
        for factor in factors[1:]:
            prob = prob * factor.getProbability(assignment)
            #print prob
        new_factor.setProbability(assignment, prob)
    return new_factor
开发者ID:philigobears,项目名称:PacMan,代码行数:69,代码来源:factorOperations.py


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