步骤:
1. 导入库:
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
2. 准备数据:
# 读取数据集
data = pd.read_csv('your_dataset.csv')
# 分割特征和标签
X = data.drop('target_column', axis=1)
y = data['target_column']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
3. 选择模型并训练:
# 选择决策树分类器
model = DecisionTreeClassifier()
# 训练模型
model.fit(X_train, y_train)
4. 模型评估:
# 在测试集上进行预测
y_pred = model.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy}')
# 打印分类报告
print(classification_report(y_test, y_pred))
# 打印混淆矩阵
conf_matrix = confusion_matrix(y_test, y_pred)
print('Confusion Matrix:')
print(conf_matrix)
这个示例使用了 scikit-learn 中的 DecisionTreeClassifier 来构建决策树分类器。你可以根据需要调整参数,例如设置决策树的最大深度、最小样本拆分等。决策树易于理解和可解释,但也容易过拟合,因此在实际应用中需要谨慎调整参数以获得更好的泛化性能。
转载请注明出处:http://www.pingtaimeng.com/article/detail/12003/AI人工智能