pgmpy / pgmpy

Python Library for learning (Structure and Parameter), inference (Probabilistic and Causal), and simulations in Bayesian Networks.
https://pgmpy.org/
MIT License
2.75k stars 717 forks source link

Tutorial notebooks for Linear Gaussian Bayesian Networks #1842

Open ankurankan opened 1 month ago

ankurankan commented 1 month ago

We currently have an example notebook: https://pgmpy.org/examples/Creating%20a%20Discrete%20Bayesian%20Network.html for creating discrete Bayesian networks but not for Linear Gaussian BNs. Write a similar notebook with tutorial on creating gaussian bayesian networks.

Vishnu-sai-teja commented 1 month ago

Hey @ankurankan, can you assign this to me ?

guptaabhishek07 commented 3 weeks ago

Importing Libraries

from pgmpy.models import BayesianNetwork from pgmpy.factors.continuous import GaussianCPD

Creating a Bayesian Network

model = BayesianNetwork([('Age', 'BloodPressure'), ('Smoking', 'BloodPressure'), ('Age', 'HeartDisease'), ('BloodPressure', 'HeartDisease')])

Adding CPDs

cpd_age = GaussianCPD('Age', mu=30, sigma=5) cpd_smoking = GaussianCPD('Smoking', mu=0.2, sigma=0.1) cpd_bp = GaussianCPD('BloodPressure', parents=['Age', 'Smoking'], mu=lambda pa: 110 + pa['Age'] + 20 * pa['Smoking'], sigma=15) cpd_hd = GaussianCPD('HeartDisease', parents=['Age', 'BloodPressure'], mu=lambda pa: 1/(1 + np.exp(-(pa['Age'] - 50)/10 - pa['BloodPressure']/20)), sigma=0.1)

model.add_cpds(cpd_age, cpd_smoking, cpd_bp, cpd_hd)

Inference

print(model.query(variables=['HeartDisease'], evidence={'Age': 40, 'Smoking': 0}))

This code defines a simple Gaussian Bayesian network with four variables: Age, Smoking, BloodPressure, and HeartDisease. The CPDs are defined using the GaussianCPD class, which specifies the mean and sigma of the Gaussian distribution for each variable. The parents argument is used to specify the parent variables for each CPD.

The query function is then used to perform inference on the network. In this case, we are querying for the probability of HeartDisease given that Age is 40 and Smoking is 0.