使用决策树对心脏病数据进行模型评估代码
时间: 2023-08-22 12:07:48 浏览: 90
20151910042-刘鹏-DM实验06-对心脏病数据进行决策树分析1
以下是使用决策树对心脏病数据进行模型评估的Python代码示例:
```python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载数据
data = pd.read_csv('heart_disease.csv')
# 特征工程
X = data.drop('target', axis=1)
y = data['target']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
# 模型训练
model = DecisionTreeClassifier(max_depth=3)
model.fit(X_train, y_train)
# 模型评估
y_pred = model.predict(X_test)
acc = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
print('Accuracy:', acc)
print('Precision:', precision)
print('Recall:', recall)
print('F1:', f1)
```
其中,`DecisionTreeClassifier`是决策树模型,`max_depth`参数用于设置决策树的最大深度,`accuracy_score`、`precision_score`、`recall_score`和`f1_score`用于计算模型评估指标。在实际应用中,可以通过交叉验证等方法调整决策树的参数,以获得更好的模型性能。
阅读全文