本文整理汇总了Python中bayesNet.Factor类的典型用法代码示例。如果您正苦于以下问题:Python Factor类的具体用法?Python Factor怎么用?Python Factor使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Factor类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: inferenceByLikelihoodWeightingSampling
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
示例2: joinFactors
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]
示例3: eliminate
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
示例4: eliminate
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
示例5: eliminate
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
示例6: normalize
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
示例7: eliminate
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
示例8: joinFactors
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
示例9: eliminate
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
示例10: eliminate
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
示例11: inferenceByLikelihoodWeightingSampling
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)
示例12: inferenceByLikelihoodWeightingSampling
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)
示例13: joinTwoFactors
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
示例14: eliminate
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
示例15: joinFactors
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)))
"*** YOUR CODE HERE ***"
unconditioned = []
conditioned = []
variableDomainsDict = {}
if factors and len(factors) > 0:
variableDomainsDict = factors[0].variableDomainsDict()
for f in factors:
temp_unconditioned = f.unconditionedVariables()
temp_conditioned = f.conditionedVariables()
unconditioned.extend(temp_unconditioned)
for conditioned_var in temp_conditioned:
if conditioned_var not in conditioned:
conditioned.append(conditioned_var)
conditioned = [var for var in conditioned if var not in unconditioned]
newFactor = Factor(unconditioned, conditioned, variableDomainsDict)
assignments = newFactor.getAllPossibleAssignmentDicts()
for assignment in assignments:
prob = 1
for factor in factors:
prob *= factor.getProbability(assignment)
newFactor.setProbability(assignment, prob)
return newFactor