用python代码通过自己编写决策树、KNN、AdaBoost、随机森林、朴素贝叶斯、感知机六种算法写一个数据挖掘方面的心脏病预测
时间: 2023-07-04 11:10:19 浏览: 85
Machine-Learning-决策树python代码
好的,我们可以用sklearn库中的心脏病数据集来进行实现。代码如下:
```python
from sklearn.datasets import load_heartdisease
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.metrics import accuracy_score
# 加载数据集
heart_disease = load_heartdisease()
X, y = heart_disease.data, heart_disease.target
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 决策树
dt_clf = DecisionTreeClassifier()
dt_clf.fit(X_train, y_train)
y_pred = dt_clf.predict(X_test)
print("Decision Tree Accuracy:", accuracy_score(y_test, y_pred))
# KNN
knn_clf = KNeighborsClassifier()
knn_clf.fit(X_train, y_train)
y_pred = knn_clf.predict(X_test)
print("KNN Accuracy:", accuracy_score(y_test, y_pred))
# AdaBoost
ada_clf = AdaBoostClassifier()
ada_clf.fit(X_train, y_train)
y_pred = ada_clf.predict(X_test)
print("AdaBoost Accuracy:", accuracy_score(y_test, y_pred))
# 随机森林
rf_clf = RandomForestClassifier()
rf_clf.fit(X_train, y_train)
y_pred = rf_clf.predict(X_test)
print("Random Forest Accuracy:", accuracy_score(y_test, y_pred))
# 朴素贝叶斯
nb_clf = GaussianNB()
nb_clf.fit(X_train, y_train)
y_pred = nb_clf.predict(X_test)
print("Naive Bayes Accuracy:", accuracy_score(y_test, y_pred))
# 感知机
perceptron_clf = Perceptron()
perceptron_clf.fit(X_train, y_train)
y_pred = perceptron_clf.predict(X_test)
print("Perceptron Accuracy:", accuracy_score(y_test, y_pred))
```
运行后将输出六种算法的准确率。注意,这里只是简单的调用了库中自带的算法,如果需要使用自己编写的算法,需要自行实现相应的代码。
阅读全文