TypeError: 'DiscreteFactor' object is not subscriptable

TypeError: 'DiscreteFactor' object is not subscriptable

我有一个贝叶斯算法程序要执行,我正在使用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

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

您用来获取数据的 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']) 


 

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

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']。 这里的输出实际上是试图将自己存储到数组对象中,但是输出实际上是特殊的 table 格式,无法存储到数组中,因此打印实际答案 'q' 会给你一个需要的结果。

print(q)

这就完成了你的工作..!!