一、关于 pgmpy
1、项目概览
pgmpy 是一个用于 贝叶斯网络 及相关模型的因果与概率建模的Python库。它提供统一的API用于构建、学习和分析以下模型:
- 贝叶斯网络
- 动态贝叶斯网络
- 有向无环图(DAGs)
- 结构方程模型(SEMs)
通过整合概率推断和因果推断工具,pgmpy 使用户能够在预测分析和干预分析之间无缝切换。
2、相关链接资源
- Github:https://github.com/pgmpy/pgmpy
- 官网:https://www.pgmpy.org
- 官方文档:https://pgmpy.org/
- 示例:https://github.com/pgmpy/pgmpy/tree/dev/examples
- 教程:https://github.com/pgmpy/pgmpy_notebook
- 社区支持:Discord | Stack Overflow
- License:MIT License
3、功能特性
功能 | 描述 |
---|---|
因果发现/结构学习 | 从数据中学习模型结构,可选择性整合专家知识 |
因果验证 | 评估因果结构与数据的兼容性 |
参数学习 | 从观测数据中估计模型参数(如条件概率分布) |
概率推断 | 计算基于观测证据的后验分布 |
因果推断 | 使用do-演算计算干预和反事实分布 |
数据模拟 | 在指定证据或干预下生成合成数据 |
二、安装配置
# 通过PyPI安装
pip install pgmpy
# 通过conda安装
conda install conda-forge::pgmpy
三、使用示例
1、离散数据建模
from pgmpy.utils import get_example_model
# 加载离散贝叶斯网络并模拟数据
discrete_bn = get_example_model('alarm')
alarm_df = discrete_bn.simulate(n_samples=100)
# 从数据学习网络结构
from pgmpy.estimators import PC
dag = PC(data=alarm_df).estimate(ci_test='chi_square', return_type='dag')
# 学习模型参数
dag_fitted = dag.fit(alarm_df)
dag_fitted.get_cpds()
# 使用学习模型进行预测
evidence_df = alarm_df.drop(columns=['FIO2'], axis=1)
pred_FIO2 = dag_fitted.predict(evidence_df)
2、线性高斯数据建模
# 加载高斯贝叶斯网络并模拟数据
gaussian_bn = get_example_model('ecoli70')
ecoli_df = gaussian_bn.simulate(n_samples=100)
# 从数据学习网络结构
from pgmpy.estimators import PC
dag = PC(data=ecoli_df).estimate(ci_test='pearsonr', return_type='dag')
# 学习模型参数
from pgmpy.models import LinearGausianBayesianNetwork
gaussian_bn = LinearGausianBayesianNetwork(dag.edges())
dag_fitted = gaussian_bn.fit(ecoli_df)
dag_fitted.get_cpds()
# 使用学习模型进行预测
evidence_df = ecoli_df.drop(columns=['ftsJ'], axis=1)
pred_ftsJ = dag_fitted.predict(evidence_df)
伊织 xAI 2025-05-27(二)