首页 > 解决方案 > 决策树总是为不同的输入返回相同的值

问题描述

我是编码新手。我正在用python学习机器学习。使用决策树,我尝试使用来自 Kaggle 的数据集来预测个人心脏病发作的机会。建模后,当我尝试预测不同的输入时,它总是返回相同的输出 [1]。可能是什么问题?我能做些什么?这是我的代码。

import pandas as pd
import numpy as np
heart=pd.read_csv('heart_attack.csv')
heart.fillna(heart.mean(),inplace=True)
x=heart.iloc[:,:-1]
y=heart.iloc[:,-1]
import sklearn
from sklearn.preprocessing import LabelEncoder
x=x.apply(LabelEncoder().fit_transform)
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test= train_test_split(x,y,test_size=0.20, random_state=85)
from sklearn.tree import DecisionTreeClassifier
result=DecisionTreeClassifier()
result.fit(x_train,y_train)
y_pred=result.predict(x_test)

这是我存储输入值的代码

Patient_Data = [Patient_Age,Patient_Gender,Patient_pain,Patient_RBP,Patient_chol,Patient_FBS,Patient_ECG,Patient_thalach,Patient_exang,Patient_oldpeak,Patient_slope,Patient_thal]
Patient_Data_New= pd.DataFrame([Patient_Data],columns=['Age','Gender','cp','restbps','chol','FBS','restecg','thalach','exang','oldpeak','slope', 'thal'])
Patient= result.predict(Patient_Data_New)
if Patient>0:
print ('This patient has a chance to get heart attack')
else:
print ('This patient does not have a chance to get heart attack')

提前致谢。

标签: pythonmachine-learningdata-sciencedecision-tree

解决方案


这可能是因为您正在预测训练集中已经存在的数据的值,因此您的模型能够正确预测所有值,从而提供 100% 的准确度。

尝试这个

result.score

如果结果是 100%,那么这是一个过度拟合的例子,您需要删除几列并使用k-fold cross validation找到最佳参数。


推荐阅读