12.18
(1)从scikit-learn 库中加载 iris 数据集,使用留出法留出 1/3 的样本作为测试集(注意同分布取样);
(2)使用训练集训练分类带有预剪枝和后剪枝的C4.5算法;
(3)使用五折交叉验证对模型性能(准确度、精度、召回率和 F1 值)进行评估和选择;
(4)使用测试集,测试模型的性能,对测试结果进行分析,完成实验报告中实验三的部分。
import pandas as pd
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_predict, KFold
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# 加载 Iris 数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分数据集,将 1/3 的样本作为测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, stratify=y, random_state=42)
print(f"训练集大小: {X_train.shape[0]}, 测试集大小: {X_test.shape[0]}")
# 使用决策树分类器进行建模,实现预剪枝
clf = DecisionTreeClassifier(criterion='entropy', max_depth=4, random_state=42) # C4.5 的标准
clf.fit(X_train, y_train)
# 五折交叉验证评估模型性能
kf = KFold(n_splits=5, random_state=42, shuffle=True)
# 获取交叉验证的预测结果
y_pred = cross_val_predict(clf, X_train, y_train, cv=kf)
# 计算绩效指标
accuracy = accuracy_score(y_train, y_pred)
precision = precision_score(y_train, y_pred, average='weighted')
recall = recall_score(y_train, y_pred, average='weighted')
f1 = f1_score(y_train, y_pred, average='weighted')
print("交叉验证结果:")
print(f"准确度: {accuracy:.2f}")
print(f"精度: {precision:.2f}")
print(f"召回率: {recall:.2f}")
print(f"F1 值: {f1:.2f}")
# 使用测试集,测试模型性能
y_test_pred = clf.predict(X_test)
# 计算测试集的性能指标
test_accuracy = accuracy_score(y_test, y_test_pred)
test_precision = precision_score(y_test, y_test_pred, average='weighted')
test_recall = recall_score(y_test, y_test_pred, average='weighted')
test_f1 = f1_score(y_test, y_test_pred, average='weighted')
print("在测试集上的性能指标:")
print(f"准确度: {test_accuracy:.2f}")
print(f"精度: {test_precision:.2f}")
print(f"召回率: {test_recall:.2f}")
print(f"F1 值: {test_f1:.2f}")
函数参数说明
load_data()返回值: 返回 Iris 数据集(特征和标签)。
test_size: 测试集所占比例。
random_state: 随机种子,用于结果复现(整数)。返回训练集和测试集的特征及标签。
train_model(X_train, y_train, max_depth):X_train: 训练集特征数据(ndarray)。y_train: 训练集标签(ndarray)。max_depth: 决策树的最大深度(整数)。返回训练好的决策树模型。
evaluate_model(clf, X_train, y_train, n_splits):clf: 训练好的决策树模型。X_train: 训练集特征数据(ndarray)。y_train: 训练集标签(ndarray)。n_splits: 交叉验证的折数(整数)。返回交叉验证的准确度、精度、召回率和 F1 值。
test_model(clf, X_test, y_test):clf: 训练好的决策树模型。X_test: 测试集特征数据(ndarray)。y_test: 测试集标签(ndarray)。返回值: 返回测试集上的准确度、精度、召回率和 F1 值。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统