Do you want to know **How to Implement Bayesian Network in Python?**… If yes, this blog is for you. In this blog, I will explain step-by-step method **to Implement Bayesian Network in Python**.

**How to Implement Bayesian Network in Python?**

**How to Implement Bayesian Network in Python?**

**What Are Bayesian Networks?**

Imagine you want to predict the weather, and you know that it depends on factors like temperature, rain, and humidity. Bayesian networks help us understand and predict these kinds of relationships. We use them to model the connections between different things.

**Nodes**are like the things we want to understand (like temperature, rain, or humidity).**Edges**show how these things affect each other.

Let’s start building our own Bayesian network in Python.

**Getting Ready**

Before we start, we need a few things:

**Python**: If you don’t have Python, you can download it from**python.org**.**Jupyter Notebook (Optional)**: This tool is great for working with Python. You can install it with`pip`

, which is a tool that helps you install Python stuff.

```
pip install jupyter
```

**Useful Library**: We’ll use a special Python library called`pgmpy`

. You can also install it with`pip`

:

```
pip install pgmpy
```

Now that we have the tools ready, we can start creating our Bayesian network.

**Step 1: Defining Things and How They Connect**

Creating a Bayesian network means deciding what things we want to understand and how they connect to each other.

**Step 1.1: Picking Things (Variables)**

In Python, we begin by choosing the things we want to understand. These things are like “variables.” If we’re predicting the weather, our variables could be** “Temperature,” “Rain,” and “Humidity.”**

```
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
# Our Empty Bayesian Network
model = BayesianNetwork()
# Picking Our Variables
model.add_node("Temperature")
model.add_node("Rain")
model.add_node("Humidity")
```

**Step 1.2: Connecting the Dots (Dependencies)**

Next, we need to tell our Python program how our variables are connected. We do this by creating **“Conditional Probability Distributions” (CPDs).**

Think of CPDs like little pieces of information that say how one thing depends on another. For example, we can say, “The chance of rain depends on the temperature.”

```
# How Variables Depend on Each Other
cpd_temperature = TabularCPD(variable="Temperature", variable_card=3, values=[[0.7], [0.2], [0.1]])
cpd_rain = TabularCPD(
variable="Rain",
variable_card=2,
values=[[0.4], [0.6]],
evidence=["Temperature"],
evidence_card=[3],
)
cpd_humidity = TabularCPD(
variable="Humidity",
variable_card=2,
values=[[0.8], [0.2]],
evidence=["Rain"],
evidence_card=[2],
)
# Putting It All Together
model.add_cpds(cpd_temperature, cpd_rain, cpd_humidity)
# Check if Everything Makes Sense
model.check_model()
```

Now our program knows the connections between our variables. We’ve got the foundation of our Bayesian network!

**Step 2: Creating the Bayesian Network**

Creating the actual Bayesian network is simple. We add our variables and their dependencies to the model.

```
# Creating the Bayesian Network
model = BayesianNetwork()
model.add_node("Temperature")
model.add_node("Rain")
model.add_node("Humidity")
model.add_cpds(cpd_temperature, cpd_rain, cpd_humidity)
# Making Sure It All Fits Together
model.check_model()
```

Now, you’ve successfully built a Bayesian network in Python. It’s ready for some cool predictions and analysis!

**Step 3: Making Predictions**

In a Bayesian network, we use the information we’ve set up to make predictions or answer questions. We call this** “inference.”**

**Step 3.1: Finding Probabilities**

To find the probability of something happening, we can ask our Bayesian network. For instance, if we want to know the probability of rain when it’s hot, we can use Python to help us:

```
from pgmpy.inference import VariableElimination
inference = VariableElimination(model)
probability = inference.query(variables=["Rain"], evidence={"Temperature": 2})
print(probability)
```

This tells us the chances of rain when the temperature is hot.

**Step 3.2: Predicting Values**

Sometimes, we want to predict what’s most likely to happen. For example, if we have some information, we can predict the humidity:

```
predicted = inference.map_query(variables=["Humidity"], evidence={"Rain": 1})
print(predicted)
```

This helps us make educated guesses.

**Step 3.3: Playing with Randomness**

In some cases, we like surprises! We can ask Python to give us random answers from our Bayesian network:

```
samples = model.sample(size=5)
print(samples)
```

This is like running simulations and seeing what might happen.

**Step 4: Seeing Is Believing**

Seeing your Bayesian network helps you understand it better. We can create a visual representation using Python.

**Step 4.1: Installing the Right Tools**

To draw our network, we need to install a couple of Python tools:

```
pip install networkx matplotlib
```

**Step 4.2: Making It Visual**

Now we can create a picture of our Bayesian network:

```
import networkx as nx
import matplotlib.pyplot as plt
# Turning Our Bayesian Network into a Picture
graph = model.to_daft()
# Showing Our Picture
nx.draw(graph, with_labels=True, node_size=500, node_color="skyblue", font_size=10, font_color="black")
plt.show()
```

This picture helps you understand how your variables connect.

**Where Can We Use Bayesian Networks?**

Bayesian networks are like a Swiss Army knife for understanding relationships. They’re used in many fields:

**Medical Diagnosis**: Helping doctors figure out what’s wrong with patients.**Talking to Computers**: Making your computer understand and talk like a human.**Insurance**: Deciding how much you should pay for insurance based on risks.**Seeing the World**: Teaching computers to recognize objects in photos.**Recommendations**: Like when Netflix suggests what to watch next.

**Conclusion**

You’ve done it! You’ve built your first Bayesian network in Python. Now you have a powerful tool for understanding and predicting all sorts of things. Remember, practice makes perfect. Try out different things, explore real-world problems, and keep learning.

Happy Learning!

**Also, Read**

**Best Math Courses for Machine Learning- Find the Best One!****9 Best Tensorflow Courses & Certifications Online- Discover the Best One!****Machine Learning Engineer Career Path: Step-by-Step Complete GuideBest Online Courses On Machine Learning You Must Know in 2024**

**Best Machine Learning Courses for Finance You Must Know**

Best Resources to Learn Machine Learning Online in 2024

Best Resources to Learn Machine Learning Online in 2024

Thank YOU!

Though of the Day…

– Henry Ford

‘Anyone who stops learning is old, whether at twenty or eighty. Anyone who keeps learning stays young.

### Written By Aqsa Zafar

Founder of MLTUT, Machine Learning Ph.D. scholar at Dayananda Sagar University. Research on social media depression detection. Create tutorials on ML and data science for diverse applications. Passionate about sharing knowledge through website and social media.