使用pgmpy生成随机贝叶斯网络存为BIFXML时遇序列化错误的解决
问题与解决:pgmpy随机贝叶斯网络保存为BIFXML报错
问题场景
使用pgmpy生成随机贝叶斯网络并尝试用XMLBIFWriter保存为BIFXML文件,代码如下:
model = BayesianModel.get_random(10, 0.5, 2) writer = XMLBIFWriter(model) writer.get_definition() writer.get_properties() writer.get_states() writer.get_values() writer.get_variables() writer.write_xmlbif('test.xml')
运行后触发错误:TypeError: cannot serialize 1 (type int)
问题原因
该错误确实由整数类型节点导致——get_random()生成的网络节点为整数类型,而XMLBIFWriter在序列化时无法直接处理整数内容,本质是XMLBIFWriter与get_random()生成的贝叶斯网络格式不兼容。
解决方法
修改XMLBIFWriter的源码,将所有直接赋值文本内容的代码(如boofar.text = foobar)替换为:
boofar.text = str(foobar)
通过强制将所有待序列化内容转为字符串类型,规避整数无法序列化的问题。
内容的提问来源于stack exchange,提问作者Lia Toutou
相关产品推荐
相关产品推荐

