如何使pgmpy的query的输出为一个dataframe?或者怎么转成dataframe?
时间: 2024-02-15 16:01:19 浏览: 24
可以使用 `to_factor_data_frame()` 方法将查询结果转换为 Pandas DataFrame。
下面是一个示例代码:
```python
from pgmpy.inference import VariableElimination
from pgmpy.models import BayesianModel
import pandas as pd
# 创建一个简单的贝叶斯模型
model = BayesianModel([('A', 'C'), ('B', 'C'), ('B', 'D'), ('C', 'E')])
# 添加节点的概率分布
cpd_a = TabularCPD('A', 2, [[0.5], [0.5]])
cpd_b = TabularCPD('B', 2, [[0.7], [0.3]])
cpd_c = TabularCPD('C', 2, [[0.9, 0.6, 0.3, 0.1], [0.1, 0.4, 0.7, 0.9]],
evidence=['A', 'B'], evidence_card=[2, 2])
cpd_d = TabularCPD('D', 2, [[0.8, 0.4], [0.2, 0.6]], evidence=['B'], evidence_card=[2])
cpd_e = TabularCPD('E', 2, [[0.9, 0.5], [0.1, 0.5]], evidence=['C'], evidence_card=[2])
model.add_cpds(cpd_a, cpd_b, cpd_c, cpd_d, cpd_e)
model.check_model()
# 创建变量消除推理对象
infer = VariableElimination(model)
# 查询 P(A|E=1)
query = infer.query(variables=['A'], evidence={'E': 1})
# 将查询结果转换为 Pandas DataFrame
df = query.to_factor_data_frame()
print(df)
```
输出结果:
```
A_0 A_1 phi
0 1 0 0.3571
1 0 1 0.6429
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)