-
Notifications
You must be signed in to change notification settings - Fork 0
/
factorOperations.py
209 lines (170 loc) · 8.7 KB
/
factorOperations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# factorOperations.py
# -------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from typing import List
from bayesNet import Factor
import functools
from util import raiseNotDefined
def joinFactorsByVariableWithCallTracking(callTrackingList=None):
def joinFactorsByVariable(factors: List[Factor], joinVariable: str):
"""
Input factors is a list of factors.
Input joinVariable is the variable to join on.
This function performs a check that the variable that is being joined on
appears as an unconditioned variable in only one of the input factors.
Then, it calls your joinFactors on all of the factors in factors that
contain that variable.
Returns a tuple of
(factors not joined, resulting factor from joinFactors)
"""
if not (callTrackingList is None):
callTrackingList.append(('join', joinVariable))
currentFactorsToJoin = [factor for factor in factors if joinVariable in factor.variablesSet()]
currentFactorsNotToJoin = [factor for factor in factors if joinVariable not in factor.variablesSet()]
# typecheck portion
numVariableOnLeft = len([factor for factor in currentFactorsToJoin if joinVariable in factor.unconditionedVariables()])
if numVariableOnLeft > 1:
print("Factor failed joinFactorsByVariable typecheck: ", factor)
raise ValueError("The joinBy variable can only appear in one factor as an \nunconditioned variable. \n" +
"joinVariable: " + str(joinVariable) + "\n" +
", ".join(map(str, [factor.unconditionedVariables() for factor in currentFactorsToJoin])))
joinedFactor = joinFactors(currentFactorsToJoin)
return currentFactorsNotToJoin, joinedFactor
return joinFactorsByVariable
joinFactorsByVariable = joinFactorsByVariableWithCallTracking()
########### ########### ###########
########### QUESTION 2 ###########
########### ########### ###########
def joinFactors(factors: List[Factor]):
"""
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 = functools.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 ***"
# Get each factor
cond_vars = set()
uncond_vars = set()
inputVariableDomainsDict = {}
for factor in factors:
# Store the conditionedVariables then multiply with next factor unconditionedVariables
cond_vars = cond_vars.union(factor.conditionedVariables())
uncond_vars = uncond_vars.union(factor.unconditionedVariables())
inputVariableDomainsDict = factor.variableDomainsDict()
# Update cond_vars, avoid duplicate
cond_vars = cond_vars - uncond_vars
# Generate new factor
newF = Factor(uncond_vars, cond_vars, inputVariableDomainsDict)
# Use for loop to set probability for the new factor
for assign in newF.getAllPossibleAssignmentDicts():
prob = 1
for factor in factors:
prob *= factor.getProbability(assign)
newF.setProbability(assign, prob)
return newF
"*** END YOUR CODE HERE ***"
########### ########### ###########
########### QUESTION 3 ###########
########### ########### ###########
def eliminateWithCallTracking(callTrackingList=None):
def eliminate(factor: Factor, eliminationVariable: str):
"""
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 ***"
cond_vars = set()
uncond_vars = set()
# Store the conditionedVariables then multiply with next factor unconditionedVariables
cond_vars = cond_vars.union(factor.conditionedVariables())
uncond_vars = uncond_vars.union(factor.unconditionedVariables())
inputVariableDomainsDict = factor.variableDomainsDict()
# Pop eliminate
inputVariableDomainsDict.pop(eliminationVariable)
uncond_vars = list(uncond_vars)
uncond_vars.remove(eliminationVariable)
uncond_vars = set(uncond_vars)
cond_vars = cond_vars - uncond_vars
# Create new Factor
newF = Factor(uncond_vars, cond_vars, inputVariableDomainsDict)
# For D: +D, -D
for assign in newF.getAllPossibleAssignmentDicts():
prob = 0
# For W: +W, -W
for assign2 in factor.variableDomainsDict()[eliminationVariable]:
new_dict = assign
new_dict[eliminationVariable] = assign2
eliminationProb = factor.variableDomainsDict()[eliminationVariable]
prob += factor.getProbability(new_dict)
# Set Probabilty
newF.setProbability(assign, prob)
return newF
"*** END YOUR CODE HERE ***"
return eliminate
eliminate = eliminateWithCallTracking()