1

我有一个要执行的贝叶斯算法程序,我正在使用 python 3

import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination


heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Few examples from the dataset are given below')
print(heartDisease.head())

model = BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),('exang','trestbps'),('trestbps','heartdisease'),('fbs','heartdisease'),('heartdisease','restecg'),('heartdisease','thalach'),('heartdisease','chol')])

print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')
HeartDisease_infer = VariableElimination(model)

print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])

print('\n 2. Probability of HeartDisease given cholesterol=100')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'chol':100})
print(q['heartdisease'])

我运行贝叶斯网络程序时收到的错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-7-84a6b48627b2> in <module>
     23 print('\n 1. Probability of HeartDisease given Age=28')
     24 q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
---> 25 print(q['heartdisease'])
     26 
     27 print('\n 2. Probability of HeartDisease given cholesterol=100')

TypeError: 'DiscreteFactor' object is not subscriptable

到目前为止,我还没有在 stackoverflow 上看到这个确切的错误。谁能解释我为什么会收到这个错误?

4

2 回答 2

4

在尝试解决错误后,我想出了解决方案。

print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])
print(q['heartdisesase']

在这部分代码片段中,我刚刚删除了 ['heartdisease']。 这里的输出实际上是试图将自己存储到一个数组对象中,但是输出实际上是特殊的表格格式,不能存储到一个数组中,所以打印实际答案“q”会给你一个需要的结果。

print(q)

这让你的工作完成..!!

于 2021-01-15T02:43:30.923 回答
0

您用来获取数据的 API 可能是旧的。您应该通过简单地将joint=False 作为第24 行的另一个参数传递给旧API。如

24 q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28},joint=False)
25 print(q['heartdisease'])
print(prob_offer['Offer']) 


 
于 2021-01-13T18:04:25.247 回答