...

/

Solution: Create a Bayesian Network Using Simulated Data

Solution: Create a Bayesian Network Using Simulated Data

Understand the steps to create a simple Bayesian network fed with simulated data in Python.

We'll cover the following...

The solution to the exercise

In the last exercise we had to completely create a Bayesian network using simulated data.

The baseline query must match the probabilities in the next diagram:

Press + to interact
Baseline probabilities for the Rain Model (simulated data)
Baseline probabilities for the Rain Model (simulated data)

This is the solution of the exercise:

Press + to interact
#The code for the simulation has alread been done
# Create a DataFrame from the generated boolean arrays
df = pd.DataFrame({"Cloudy": cloudy, "Sprinkler": sprinkler, "Rain": rain, "Wet_Grass": wet_grass})
# Define the network structure
sm = StructureModel()
# adding the edges
sm.add_edges_from([
('Cloudy', 'Sprinkler'),
('Cloudy', 'Rain'),
('Sprinkler', 'Wet_Grass'),
('Rain', 'Wet_Grass')])
#Create the model
bn = BayesianNetwork(sm)
#use the df (columns) to create the nodes of the network
bn = bn.fit_node_states(df)
#fit the model with the train set
bn = bn.fit_cpds(df, method="BayesianEstimator", bayes_prior="K2")
# Create the query
ie = InferenceEngine(bn)
marginals = ie.query()
# Query the baseline
baseline = ie.query({})
#Round the Baseline
rounded_baseline = {
outer_key: {inner_key: round(value, 2) for inner_key, value in inner_dict.items()}
for outer_key, inner_dict in baseline.items()}
print(rounded_baseline)
def test(n={}):
return rounded_baseline
...