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


Python Factor.getAllPossibleAssignmentDicts方法代码示例

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


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

示例1: normalize

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例2: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例3: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例4: normalize

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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 ***"

    conditionedVariables = []
    for each in factor.unconditionedVariables():
        if len(factor.variableDomainsDict()[each]) == 1:
            conditionedVariables.append(each)
    conditionedVariables = list(set(conditionedVariables + list(factor.conditionedVariables())))

    unconditionedVariables = []
    for each in factor.unconditionedVariables():
        if each not in conditionedVariables:
            unconditionedVariables.append(each)

    newFactor = Factor(unconditionedVariables, conditionedVariables, factor.variableDomainsDict())
    z = 0
    for each in factor.getAllPossibleAssignmentDicts():
        z += factor.getProbability(each)
    for each in newFactor.getAllPossibleAssignmentDicts():
        newFactor.setProbability(each, factor.getProbability(each) / z)
    return newFactor
    util.raiseNotDefined()
开发者ID:SanityL,项目名称:Projects,代码行数:73,代码来源:factorOperations.py

示例5: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例6: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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 ***"
    unconditionals, conditionals, variableDomainsDict = getVariablesFromAllFactors(factors)
    newFactor   = Factor(unconditionals, conditionals, variableDomainsDict)
    for unconditional in unconditionals:
        toRemove    = []
        newFactor   = Factor(unconditionals, conditionals, variableDomainsDict)
        possAssigns = newFactor.getAllPossibleAssignmentDicts()
        newFactor   = initiateProbsToOne(newFactor, possAssigns)
        for factor in factors:
            factorUnconditionals    = factor.unconditionedVariables()
            factorConditionals      = factor.conditionedVariables()
            if unconditional in factorUnconditionals and not unconditional in factorConditionals:
                toRemove.append(factor)
                assignments = factor.getAllPossibleAssignmentDicts()
                for assignment in assignments:
                    for possAssign in possAssigns:
                        newFactor = adjustProbability(possAssign, assignment, newFactor, factor)
        factors = purgeFactors(toRemove, factors, newFactor)
    return newFactor
开发者ID:chashao,项目名称:CS188,代码行数:59,代码来源:factorOperations.py

示例8: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例9: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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: joinTwoFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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

示例11: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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 
    [{'W': 'sun'}, {'W': 'rain'}]
    
    Factor.getProbability 
    factor.getProbability({'W': 'sun'}) 
    
    Factor.setProbability 
    factor.setProbability({'W': 'sun'}, probability):

    Factor.unconditionedVariables 
    ['W']
    
    Factor.conditionedVariables 
    []
    
    Factor.variableDomainsDict 
    {'D': ['wet', 'dry'], 'W': ['sun', 'rain']}

    P(unconditioned|conditioned)
    """

    # 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 ***"

    setsOfUnconditioned = [set(factor.unconditionedVariables()) for factor in factors]
    setsOfUnconditioned =  reduce(lambda x, y: x | y, setsOfUnconditioned)
    setsOfConditioned = [set(factor.conditionedVariables()) for factor in factors]
    setsOfConditioned = reduce(lambda x, y: x | y, setsOfConditioned)
    overlap = setsOfUnconditioned.intersection(setsOfConditioned)
    # print setsOfUnconditioned
    # print setsOfConditioned
    # print overlap
    setsOfUnconditioned = setsOfUnconditioned.union(overlap)
    setsOfConditioned = setsOfConditioned.difference(overlap)
    # print 'NEW unconditioned'
    # print setsOfUnconditioned
    # print 'NEW conditioned'
    # print setsOfConditioned

    domain = factor.variableDomainsDict()
    for factor in factors:
        domain.update(factor.variableDomainsDict())

    newFactor = Factor(setsOfUnconditioned, setsOfConditioned, domain)
    for assignments in newFactor.getAllPossibleAssignmentDicts():
        listP = [factor.getProbability(assignments) for factor in factors]
        probability = 1
        for p in listP:
            probability *= p 
        newFactor.setProbability(assignments, probability)
    return newFactor
开发者ID:poywoo,项目名称:188proj4,代码行数:88,代码来源:factorOperations.py

示例12: inferenceByVariableElimination

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [as 别名]
    def inferenceByVariableElimination(bayesNet, queryVariables, evidenceDict, eliminationOrder):
        """
        Question 4: Your inference by variable elimination implementation

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

        P(queryVariables | evidenceDict)

        It should perform inference by interleaving joining on a variable
        and eliminating that variable, in the order of variables according
        to eliminationOrder.  See inferenceByEnumeration for an example on
        how to use these functions.

        You need to use joinFactorsByVariable to join all of the factors 
        that contain a variable in order for the autograder to 
        recognize that you performed the correct interleaving of 
        joins and eliminates.

        If a factor that you are about to eliminate a variable from has 
        only one unconditioned variable, you should not eliminate it 
        and instead just discard the factor.  This is since the 
        result of the eliminate would be 1 (you marginalize 
        all of the unconditioned variables), but it is not a 
        valid factor.  So this simplifies using the result of eliminate.

        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. 
        eliminationOrder: The order to eliminate the variables in.

        Hint: BayesNet.getAllCPTsWithEvidence will return all the Conditional 
        Probability Tables even if an empty dict (or None) is passed in for 
        evidenceDict. In this case it will not specialize any variable domains 
        in the CPTs.

        Useful functions:
        BayesNet.getAllCPTsWithEvidence
        normalize
        eliminate
        joinFactorsByVariable
        joinFactors
        """

        # this is for autograding -- don't modify
        joinFactorsByVariable = joinFactorsByVariableWithCallTracking(callTrackingList)
        eliminate             = eliminateWithCallTracking(callTrackingList)
        if eliminationOrder is None: # set an arbitrary elimination order if None given
            eliminationVariables = bayesNet.variablesSet() - set(queryVariables) -\
                                   set(evidenceDict.keys())
            eliminationOrder = sorted(list(eliminationVariables))

        "*** YOUR CODE HERE ***"
        # evidenceVariablesSet = set(evidenceDict.keys())
        # queryVariablesSet = set(queryVariables)
        # print evidenceVariablesSet
        # print queryVariables
        # print eliminationOrder
        currentFactorsList = bayesNet.getAllCPTsWithEvidence(evidenceDict)
      
        for elim_var in eliminationOrder:
            currentFactorsList, joinedFactor = joinFactorsByVariable(currentFactorsList, elim_var)
            if (len(joinedFactor.unconditionedVariables()) > 1):
                elim_factor = eliminate(joinedFactor, elim_var)
                currentFactorsList.append(elim_factor)

        fullJointOverQueryAndEvidence = joinFactors(currentFactorsList)
        queryConditionedOnEvidence = normalize(fullJointOverQueryAndEvidence)

        set_of_unconditioned = set(queryVariables)
        set_Of_variables = set(queryConditionedOnEvidence.variables())
        variable_domains = queryConditionedOnEvidence.variableDomainsDict()
        set_of_conditioned = set_Of_variables - set_of_unconditioned
        new_factor = Factor(list(set_of_unconditioned), list(set_of_conditioned), variable_domains)
        all_possible_assignments = new_factor.getAllPossibleAssignmentDicts()

        for assignment in all_possible_assignments:
            prob = queryConditionedOnEvidence.getProbability(assignment)
            new_factor.setProbability(assignment, prob)
        #print queryConditionedOnEvidence.unconditionedVariables()
        #print queryConditionedOnEvidence.conditionedVariables()
        return new_factor
开发者ID:philigobears,项目名称:PacMan,代码行数:90,代码来源:inference.py

示例13: eliminate

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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 ***"
        #print factor
        unconditioned = factor.unconditionedVariables()
        conditioned = factor.conditionedVariables()
        for item in unconditioned:
            if item == eliminationVariable:
                unconditioned.remove(item)
        for item in conditioned:
            if item == eliminationVariable:
                conditioned.remove(item)
        variableDomainsDict = factor.variableDomainsDict()

        newFactor = Factor(unconditioned, conditioned, factor.variableDomainsDict())
        # print "newFactor"
        # print newFactor

        for newPossibleAssignment in newFactor.getAllPossibleAssignmentDicts():
            # print("new possible assignment", newPossibleAssignment)
            assignment = 0
            for possibleAssignment in factor.getAllPossibleAssignmentDicts():
                if all(item in possibleAssignment.items() for item in newPossibleAssignment.items()):
                #check if newpossibleassignment is a subset of possibleassignment
                    # print("possible assignment", possibleAssignment)
                    prob = factor.getProbability(possibleAssignment)
                    # print("prob", prob)
                    assignment += prob
            newFactor.setProbability(newPossibleAssignment, assignment)
        return newFactor
开发者ID:wongdaniel8,项目名称:Portfolio,代码行数:73,代码来源:factorOperations.py

示例14: joinFactors

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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]
    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)))

    total_conditioned_variables = set()
    total_unconditioned_variables = set()
    mega_variable_domains = {}

    for factor in factors:
        mega_variable_domains.update(factor.variableDomainsDict())

    for factor in factors:
        for unc_var in factor.unconditionedVariables():
            total_unconditioned_variables.add(unc_var)
        for con_var in factor.conditionedVariables():
            total_conditioned_variables.add(con_var)

    total_conditioned_variables.difference_update(total_unconditioned_variables)

    new_factor = Factor(total_unconditioned_variables, total_conditioned_variables, mega_variable_domains)

    for ass in new_factor.getAllPossibleAssignmentDicts():
        multiple = 1

        for factor in factors:
            multiple *= factor.getProbability(ass)
            
        Factor.setProbability(new_factor, ass, multiple)

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

示例15: normalize

# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getAllPossibleAssignmentDicts [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))

    "*** YOUR CODE HERE ***"
    # If the sum of probabilities in the input factor is 0,
    # you should return None.
    variableDomainsDict = factor.variableDomainsDict()
    unconditioned = factor.unconditionedVariables()
    conditioned = factor.conditionedVariables()

    prob_sum = 0
    old_assignments = factor.getAllPossibleAssignmentDicts()
    for row in old_assignments:
        prob_sum += factor.getProbability(row)
    if prob_sum == 0:
        return None

    for var in unconditioned:
        if len(variableDomainsDict[var]) == 1:
            conditioned.add(var)
    unconditioned = [var for var in unconditioned if var not in conditioned]
    newFactor = Factor(unconditioned, conditioned, variableDomainsDict)

    for assignment in newFactor.getAllPossibleAssignmentDicts():
        prob = factor.getProbability(assignment)
        newFactor.setProbability(assignment, prob / prob_sum)
    return newFactor
开发者ID:namidairo777,项目名称:Pacman-MultiAgent-Search,代码行数:73,代码来源:factorOperations.py


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