...
/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...
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
This is the solution of the exercise:
Press + to interact
Python 3.8
#The code for the simulation has alread been done# Create a DataFrame from the generated boolean arraysdf = pd.DataFrame({"Cloudy": cloudy, "Sprinkler": sprinkler, "Rain": rain, "Wet_Grass": wet_grass})# Define the network structuresm = StructureModel()# adding the edgessm.add_edges_from([('Cloudy', 'Sprinkler'),('Cloudy', 'Rain'),('Sprinkler', 'Wet_Grass'),('Rain', 'Wet_Grass')])#Create the modelbn = BayesianNetwork(sm)#use the df (columns) to create the nodes of the networkbn = bn.fit_node_states(df)#fit the model with the train setbn = bn.fit_cpds(df, method="BayesianEstimator", bayes_prior="K2")# Create the queryie = InferenceEngine(bn)marginals = ie.query()# Query the baselinebaseline = ie.query({})#Round the Baselinerounded_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
...