如何将pgmpy学习得到的CPD保存至Excel或PDF文件?
如何将pgmpy的CPD保存至Excel或PDF文件?
保存到Excel表格
pgmpy的TabularCPD对象支持直接转换为pandas DataFrame,之后就能用pandas的Excel写入工具轻松保存:
- 将CPD转为DataFrame
from pgmpy.factors.discrete import TabularCPD import pandas as pd # 假设你已得到训练后的CPD对象,比如cpd_fault(故障变量CPD)、cpd_symptom(症状变量CPD) cpd_df = cpd_fault.to_dataframe()
- 保存单个CPD到Excel
cpd_df.to_excel("cpd_results.xlsx", sheet_name="故障变量CPD", index=False)
- 保存多个CPD到同一Excel的不同工作表
如果模型包含多个节点的CPD,可循环写入不同sheet:
with pd.ExcelWriter("all_cpd_results.xlsx") as writer: # 遍历贝叶斯网络模型的所有节点(假设模型对象为model) for node in model.nodes(): cpd = model.get_cpds(node) cpd_df = cpd.to_dataframe() cpd_df.to_excel(writer, sheet_name=f"{node}_CPD", index=False)
保存到PDF文件
提供两种简单实现方式,按需选择:
方法1:基于DataFrame生成PDF(matplotlib)
将DataFrame渲染为表格图片后保存为PDF:
import matplotlib.pyplot as plt from pandas.plotting import table # 转换CPD为DataFrame cpd_df = cpd_fault.to_dataframe() # 创建绘图对象并隐藏坐标轴 fig, ax = plt.subplots(figsize=(12, 4)) ax.xaxis.set_visible(False) ax.yaxis.set_visible(False) ax.set_frame_on(False) # 生成表格并调整样式 tbl = table(ax, cpd_df, loc='center', cellLoc='center') tbl.auto_set_font_size(False) tbl.set_fontsize(10) tbl.scale(1.2, 1.2) # 保存为PDF plt.savefig("cpd_fault.pdf", bbox_inches='tight', dpi=300) plt.close()
方法2:基于文本表格生成PDF(tabulate+FPDF)
先生成格式化文本表格,再写入PDF:
from tabulate import tabulate from fpdf import FPDF # 转换CPD为DataFrame并生成网格格式的表格文本 cpd_df = cpd_fault.to_dataframe() table_text = tabulate(cpd_df, headers='keys', tablefmt='grid') # 初始化PDF对象并写入内容 pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=10) for line in table_text.split('\n'): pdf.cell(200, 10, txt=line, ln=True, align='C') # 保存PDF pdf.output("cpd_fault.pdf")
使用上述PDF方法前,需先安装依赖库:
pip install pandas matplotlib tabulate fpdf
内容的提问来源于stack exchange,提问作者hunterlineage
相关产品推荐
相关产品推荐

