使用bnlearn中predict函数触发check.data数据缺失报错的原因
报错原因及解决办法
核心报错原因
你调用predict()时使用了method="bayes-lw"(贝叶斯加权抽样法),这个方法需要依赖原始训练数据进行抽样计算,但你没有在predict()函数中通过data参数传入训练数据集data_computer,导致函数找不到抽样所需的数据源,直接触发了the data are missing错误。
另外需要额外注意:要确保测试数据集data_computer_test的因子水平和训练数据集完全一致(比如Student的取值大小写、是否和训练集的因子水平匹配),否则可能引发后续的兼容性问题,但当前报错的直接原因是未传入训练数据。
解决办法
方案1:补充传入训练数据
在predict()调用中添加data=data_computer参数,让bayes-lw方法能获取到抽样所需的原始训练数据:
new_predictions <- predict(learned.network, newdata=data_computer_test, node="Buy.Computer", method="bayes-lw", data=data_computer)
方案2:更换无需训练数据的预测方法
如果不想依赖原始训练数据,可以改用method="parents"或method="bayes"(注意此bayes与bayes-lw不是同一方法),这两种方法仅依赖拟合好的贝叶斯网络参数即可完成预测:
# 使用父节点条件概率直接计算预测结果 new_predictions <- predict(learned.network, newdata=data_computer_test, node="Buy.Computer", method="parents")
内容的提问来源于stack exchange,提问作者Naim Assis Ismail
相关产品推荐
相关产品推荐

