本文整理汇总了Python中bayesNet.Factor.getProbability方法的典型用法代码示例。如果您正苦于以下问题:Python Factor.getProbability方法的具体用法?Python Factor.getProbability怎么用?Python Factor.getProbability使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bayesNet.Factor
的用法示例。
在下文中一共展示了Factor.getProbability方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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
示例2: eliminate
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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
示例3: eliminate
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
tmp = factor.unconditionedVariables()
unconditionedVars = [x for x in tmp if x != eliminationVariable]
newFactor = Factor(unconditionedVars, factor.conditionedVariables(), factor.variableDomainsDict())
for assignmentDict in factor.getAllPossibleAssignmentDicts():
prob = newFactor.getProbability(assignmentDict) + factor.getProbability(assignmentDict)
newFactor.setProbability(assignmentDict, prob)
return newFactor
示例4: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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)
示例5: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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)
示例6: joinFactors
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
factor1 = factors[0]
totalUnconditionedVars = set()
totalConditionedVars = set()
varsToDomain = {}
for factor in factors:
for uncon in factor.unconditionedVariables():
if uncon not in totalUnconditionedVars:
totalUnconditionedVars.add(uncon)
varsToDomain[uncon] = factor.variableDomainsDict()[uncon]
for factor in factors:
for con in factor.conditionedVariables():
if con not in totalUnconditionedVars and con not in totalConditionedVars:
totalConditionedVars.add(con)
varsToDomain[con] = factor.variableDomainsDict()[con]
newFactor = Factor(list(totalUnconditionedVars), list(totalConditionedVars), varsToDomain)
for ass in newFactor.getAllPossibleAssignmentDicts():
newFactor.setProbability(ass, float(1.0))
for factor in factors:
asses = newFactor.getAllPossibleAssignmentDicts()
for ass in asses:
for facAss in factor.getAllPossibleAssignmentDicts():
pro = factor.getProbability(facAss)
works = True
for var in facAss.keys():
if facAss[var] != ass[var]:
works = False
break
if works:
newFactor.setProbability(ass, newFactor.getProbability(ass) * pro)
break
return newFactor
示例7: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
# create a conditionedAssignments dict
conditionedAssignments = {}
#print conditionedAssignments
#print bayesNet.getCPT()
variableList = bayesNet.linearizeVariables()
evidenceList = set(evidenceDict.keys())
# build a new blank factor
variableDomainsDict = bayesNet.getReducedVariableDomains(evidenceDict)
#print variableDomainsDict
#print queryVariables
#print evidenceList
newFactor = Factor(queryVariables, evidenceList, variableDomainsDict)
#print newFactor
# sample numSamples times
for idx in range(numSamples):
weight = 1.0
assignmentDict = {}
for variable in variableList:
factor = bayesNet.getCPT(variable)
#print factor
if (variable in evidenceList):
assignmentDict[variable] = evidenceDict[variable]
prob = factor.getProbability(assignmentDict)
#print 'Prob: ', prob
weight *= prob
else:
newDict = sampleFromFactor(factor, assignmentDict)
# update assignment dict
for key in newDict:
assignmentDict[key] = newDict[key]
#print 'new assignment dict: ', assignmentDict
# what to do with final Assignment and weight?
finalAssignment = assignmentDict
#print finalAssignment
currentProb = newFactor.getProbability(finalAssignment)
newProb = currentProb + weight
newFactor.setProbability(finalAssignment, newProb)
# normalize
queryConditionedOnEvidence = normalize(newFactor)
return queryConditionedOnEvidence
示例8: eliminate
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
unconditioned = set()
conditioned = set()
for eachVar in factor.unconditionedVariables():
if not eachVar == eliminationVariable:
unconditioned.add(eachVar)
for eachVar in factor.conditionedVariables():
conditioned.add(eachVar)
# build a new blank factor
variableDomainsDict = factor.variableDomainsDict()
newFactor = Factor(unconditioned, conditioned, variableDomainsDict)
# eliminate the given variables
assignmentDicts = factor.getAllPossibleAssignmentDicts()
for assignment in assignmentDicts:
oldProb = factor.getProbability(assignment)
newProb = newFactor.getProbability(assignment)
newFactor.setProbability(assignment, oldProb + newProb)
return newFactor
示例9: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
# print ("evidence",evidenceDict)
unconditioned = evidenceDict.keys()
sampleToWeightList = [] #list of tuples, each tuple is of type(dictionary, weight)
weights = []
count = 0
reduced = bayesNet.getReducedVariableDomains(evidenceDict)
# itemsToRemove =[]
# for item in reduced:
# print item
# if (item not in queryVariables) or (item not in evidenceDict):
# print "removed"
# itemsToRemove.append(item)
# for item in itemsToRemove:
# reduced.pop(item)
# print ("reduced", reduced)
# print ("queryVariables", queryVariables)
# print("linearized", bayesNet.linearizeVariables())
# print ("BAYES NET")
# print bayesNet
sample = {}
while count != numSamples:
sample = {}
weight = 1
for variable in bayesNet.linearizeVariables():
# print ("variable", variable)
# print("sample", sample)
factor = bayesNet.getCPT(variable)
if variable in evidenceDict.keys():
# print ("presample", sample)
sample.update({variable: evidenceDict[variable]})
# print("post", sample)
prob = factor.getProbability(sample)
# print ("prob", prob)
weight = weight * prob
else:
assignmentDict = sampleFromFactor(factor, sample)
sample.update(assignmentDict)
# print ("appended", assignmentDict)
# print (sample)
# print "=========="
tup = (sample, weight)
sampleToWeightList.append(tup)
count += 1
# print("====================================")
# conditioned = queryVariables
# conditionedFactor = Factor(queryVariables, [], bayesNet.variableDomainsDict())
# print "conditionedFactor"
# print conditionedFactor
# conditionedDomain = conditionedFactor.variableDomainsDict()
# print ("conditionedDomain", conditionedDomain)
# unconditionedFactor = Factor(unconditioned, [], bayesNet.variableDomainsDict())
# unconditionedDomain = unconditionedFactor.variableDomainsDict()
# print "unconditionedFactor"
# print unconditionedFactor
# print ("unconditionedDomain", unconditionedDomain)
# print "AAAAAAA"
#.........这里部分代码省略.........
示例10: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
linearizeVars = bayesNet.linearizeVariables()
varDomainsDict = bayesNet.variableDomainsDict()
# create a new factor
queryEvidenceDomainsDict = {}
for query in queryVariables:
queryEvidenceDomainsDict[query] = varDomainsDict[query]
for evidence, value in evidenceDict.items():
queryEvidenceDomainsDict[evidence] = [value]
sampleFactor = Factor(queryVariables, evidenceDict, queryEvidenceDomainsDict)
#number of samples to take
for x in xrange(1,numSamples+1):
w = 1.0
sampleVars = {} #vars set and encountered so far, including both the unconditioned and conditioned variables
for var in linearizeVars:
if var in evidenceDict.keys(): #if var is an evidence variable
factor = bayesNet.getCPT(var)
sampleVars[var] = evidenceDict[var]
probability = factor.getProbability(sampleVars)
w = w * probability
else: #take a sample
sampleDict = sampleFromFactor(bayesNet.getCPT(var), sampleVars)
sampleVars.update(sampleDict)
#update the corresponding row in the factor
sampleFactor.setProbability(sampleVars, w+(sampleFactor.getProbability(sampleVars)))
return normalize(sampleFactor)
util.raiseNotDefined()
示例11: joinFactors
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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)))
"*** YOUR CODE HERE ***"
# print "@@@@@@factorlength ", len(factors)
# print "@@@@@@@factor 1", factors[0]
# print "@@@@@@@factor 2", factors[1]
# print "@@@@@@@variableDomainsDict ", Factor.variableDomainsDict(factors[0]), len(Factor.variableDomainsDict(factors[0]))
# print "@@@@@@@conditionedVariables ", Factor.conditionedVariables(factors[0])
# print "@@@@@@@getAllPossibleAssignmentDicts ", Factor.getAllPossibleAssignmentDicts(factors[0])
# print "@@@@@@@oneassignmentdict ", Factor.getAllPossibleAssignmentDicts(factors[0])[0], Factor.getAllPossibleAssignmentDicts(factors[0])[0].get("W")
# print "@@@@@@@getProbability ", Factor.getProbability(factors[0], Factor.getAllPossibleAssignmentDicts(factors[0])[0])
#Factor.getAllPossibleAssignmentDicts(factors[0])
joinedConditionedVariables = set()
joinedUnconditionedVariables = set()
for factor in factors:
for condVar in factor.conditionedVariables():
joinedConditionedVariables.add(condVar)
for uncondVar in factor.unconditionedVariables():
joinedUnconditionedVariables.add(uncondVar)
# joinedConditionedVariables.union(factor.conditionedVariables())
# joinedUnconditionedVariables.union(factor.unconditionedVariables())
# print "@@@@@factor.unconditionedVariables() ", factor.unconditionedVariables(), type(factor.unconditionedVariables())
# print "@@@@joinedConditionedVariables ", joinedConditionedVariables
# print "@@@@joinedUnconditionedVariables ", joinedUnconditionedVariables
# print "@@@@factor.conditionedVariables() ", factor.conditionedVariables()
# print "@@@@factor.unconditionedVariables() ", factor.unconditionedVariables()
# joinedUnconditionedVariables.remove(eliminationVariable)
# reducedFactor = Factor(reducedUnconditionedVariables, factor.conditionedVariables(), factor.variableDomainsDict())
for uncondVar in joinedUnconditionedVariables:
if uncondVar in joinedConditionedVariables:
joinedConditionedVariables.remove(uncondVar)
# print "@@@@@@joinedUnconditionedVariables ", joinedUnconditionedVariables
# print "@@@@@@joinedConditionedVariables ", joinedConditionedVariables
joinedFactor = Factor(joinedUnconditionedVariables, joinedConditionedVariables, factors[0].variableDomainsDict())
# print "@@@@joinedFactor.unconditionedVariables() ", joinedFactor.unconditionedVariables()
# print "@@@@joinedFactor.conditionedVariables() ", joinedFactor.conditionedVariables()
for joinedAssignment in joinedFactor.getAllPossibleAssignmentDicts():
# print "@@@@joinedAssignment ", joinedAssignment
factorAssignmentProduct = 1
for factor in factors:
# print "probability of ", joinedAssignment, Factor.getProbability(factor, joinedAssignment)
factorAssignmentProduct = factorAssignmentProduct * Factor.getProbability(factor, joinedAssignment)
Factor.setProbability(joinedFactor, joinedAssignment, factorAssignmentProduct)
return joinedFactor
示例12: inferenceByLikelihoodWeightingSampling
# 需要导入模块: from bayesNet import Factor [as 别名]
# 或者: from bayesNet.Factor import getProbability [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 ***"
# create return factor
newFactor = Factor(queryVariables, evidenceDict, bayesNet.variableDomainsDict())
reducedVariableDomains = bayesNet.getReducedVariableDomains(evidenceDict)
newFactor = newFactor.specializeVariableDomains(reducedVariableDomains)
for i in range(numSamples):
weight = 1.0
allAssignments = {}
allAssignments.update(evidenceDict)
for var in bayesNet.linearizeVariables():
tmpCPT = bayesNet.getCPT(var)
if var in evidenceDict:
# accumulate weight
weight *= tmpCPT.getProbability(allAssignments)
else:
newAssignment = sampleFromFactor(tmpCPT, allAssignments)
allAssignments.update(newAssignment)
# accumulate sample
p = newFactor.getProbability(allAssignments)
newFactor.setProbability(allAssignments, p + weight)
return normalize(newFactor)
util.raiseNotDefined()