Search⌘ K
AI Features

Solution: Create a Bayesian Network Using Simulated Data

Explore how to construct a Bayesian network from simulated data by creating a data frame, defining network structure, training the model, and running baseline queries. This lesson guides you through using Python to build and analyze Bayesian networks, reinforcing your understanding of probabilistic relationships and model evaluation.

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:

Baseline probabilities for the Rain Model (simulated data)
Baseline probabilities for the Rain Model (simulated data)

This is the solution of the exercise:

Python 3.8
#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
...