KNN算法和决策树算法进行心脏病预测的模型评估召回率,F1值代码
时间: 2024-03-02 18:54:04 浏览: 125
以下是KNN算法和决策树算法进行心脏病预测的模型评估召回率、F1值的Python代码:
```python
# 导入模块和数据集
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import recall_score, f1_score
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X = data.data
y = data.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# KNN算法
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train, y_train)
knn_y_pred = knn.predict(X_test)
# 计算KNN算法的召回率和F1值
knn_recall = recall_score(y_test, knn_y_pred)
knn_f1 = f1_score(y_test, knn_y_pred)
# 决策树算法
dt = DecisionTreeClassifier(max_depth=3, random_state=42)
dt.fit(X_train, y_train)
dt_y_pred = dt.predict(X_test)
# 计算决策树算法的召回率和F1值
dt_recall = recall_score(y_test, dt_y_pred)
dt_f1 = f1_score(y_test, dt_y_pred)
# 打印结果
print("KNN算法的召回率为:{:.2f},F1值为:{:.2f}".format(knn_recall, knn_f1))
print("决策树算法的召回率为:{:.2f},F1值为:{:.2f}".format(dt_recall, dt_f1))
```
请注意,这里使用了 Sklearn 中的“乳腺癌”数据集来进行演示。你可以根据自己的数据集进行适当的修改。
阅读全文