Submission
Submission
'''
WRITE YOUR CODE BELOW.
'''
import random
from numpy import zeros, float32
# pgmpy
import pgmpy
from pgmpy.models import BayesianModel
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
#You are not allowed to use following set of modules from 'pgmpy'
Library.
#
# pgmpy.sampling.*
# pgmpy.factors.*
# pgmpy.estimators.*
def make_power_plant_net():
"""Create a Bayes Net representation of the above power plant
problem.
Use the following as the name attribute: "alarm","faulty alarm",
"gauge","faulty gauge", "temperature". (for the tests to work.)
"""
bayes_net.add_nodes_from(nodes)
bayes_net.add_edges_from(edges)
#raise NotImplementedError
return bayes_net
def set_probability(bayes_net):
"""Set probability distribution for each node in the power plant
system.
Use the following as the name attribute: "alarm","faulty alarm",
"gauge","faulty gauge", "temperature". (for the tests to work.)
"""
# TODO: set the probability distribution for each node
#raise NotImplementedError
return bayes_net
def get_alarm_prob(bayes_net):
"""Calculate the marginal
probability of the alarm
ringing in the
power plant system."""
# TODO: finish this function
solver = VariableElimination(bayes_net)
alarm_prob = marginal_prob['alarm'].values
#raise NotImplementedError
return alarm_prob
def get_gauge_prob(bayes_net):
"""Calculate the marginal
probability of the gauge
showing hot in the
power plant system."""
# TODO: finish this function
solver = VariableElimination(bayes_net)
gauge_prob = marginal_prob['gauge'].values
#raise NotImplementedError
return gauge_prob
def get_temperature_prob(bayes_net):
"""Calculate the conditional probability
of the temperature being hot in the
power plant system, given that the
alarm sounds and neither the gauge
nor alarm is faulty."""
# TODO: finish this function
solver = VariableElimination(bayes_net)
conditional_prob = solver.query(variables=['temperature'],
evidence={'gauge':0, 'faulty alarm':0, 'alarm':1}, joint=False)
temp_prob = conditional_prob['temperature'].values
#raise NotImplementedError
return temp_prob
def get_game_network():
"""Create a Bayes Net representation of the game problem.
Name the nodes as "A","B","C","AvB","BvC" and "CvA". """
BayesNet = BayesianModel()
BayesNet.add_nodes_from(nodes)
BayesNet.add_edges_from(edges)
#raise NotImplementedError
return BayesNet
def calculate_posterior(bayes_net):
"""Calculate the posterior distribution of the BvC match given that A
won against B and tied C.
Return a list of probabilities corresponding to win, loss and tie
likelihood."""
posterior = [0,0,0]
# TODO: finish this function
solver = VariableElimination(bayes_net)
posterior = posterior['BvC'].values
#raise NotImplementedError
return posterior # list
v = ['A','B','C','AvB','AvC','CvB']
num_of_samples = 6
solver = VariableElimination(bayes_net)
sol = list()
for _ in range(num_of_samples):
v__ = random.choice(v)
prob = prob[v__].values
sol.append(prob)
sample = tuple(sol)
#raise NotImplementedError
return sample
#sample = tuple(initial_state)
# TODO: finish this function
sample = list()
sig = 0.3
r = 0
for i in initial_state:
i_p = np.random.normal(loc=i, scale=sig)
a = np.exp(i_p**2) * (2+np.sin(i_p*5) + np.sin(i_p*2))
b = np.exp(sig**2) * (2+np.sin(sig*5) + np.sin(sig*2))
acc_p = a/b
u = np.random.randn()
if u <= acc_p:
c = i_p
else:
c = i
r += 1
sample.append(c)
sample = tuple(sample)
#raise NotImplementedError
return sample
t1 = time.now()
g_ = Gibbs_sampler(bayes_net, initial_state)
t2 = time.now()
Gibbs_count = t2-t1
t3 = time.now()
mh_ = MH_sampler(bayes_net, initial_state)
t4 = time.now()
MH_count = t4-t3
r = 0
for i in mh_:
if i not in initial_state:
r += 1
MH_rejection_count = r
g = g_[-3:]
Gibbs_convergence = g # posterior distribution of the BvC match as
produced by Gibbs
mh = mh_[-3:]
MH_convergence = mh # posterior distribution of the BvC match as
produced by MH
#raise NotImplementedError
return Gibbs_convergence, MH_convergence, Gibbs_count, MH_count,
MH_rejection_count
def sampling_question():
"""Question about sampling performance."""
# TODO: assign value to choice and factor
options = ['Gibbs','Metropolis-Hastings']
if g > h:
choice = 1
factor = g/h
else:
choice = 0
factor = h/g
#raise NotImplementedError
return options[choice], factor
def return_your_name():
"""Return your name from this function"""
# TODO: finish this function
#raise NotImplementedError
return 'John Doe'