深度探寻:sklearn决策树最优最大深度与叶子节点最小样本数,解锁最高准确率!
```python from sklearn.tree import DecisionTreeClassifier from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score def find_optimal_parameters(X_train, y_train, X_test, y_test): best_depth = 0 best_min_samples_leaf = 0 best_accuracy = 0 for depth in range(1, 11): for min_samples_leaf in range(1, 11): clf = DecisionTreeClassifier(max_depth=depth, min_samples_leaf=min_samples_leaf) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) accuracy = accuracy_score(y_test, y_pred) if accuracy > best_accuracy: best_accuracy = accuracy best_depth = depth best_min_samples_leaf = min_samples_leaf return best_depth, best_min_samples_leaf, best_accuracy # 加载鸢尾花数据集 iris = load_iris() X = iris.data y = iris.target # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) best_depth, best_min_samples_leaf, best_accuracy = find_optimal_parameters(X_train, y_train, X_test, y_test) print(f"最优的最大深度为: {best_depth}") print(f"最优的叶子节点最小样本数为: {best_min_samples_leaf}") print(f"对应的准确率为: {best_accuracy}") ``` 额外需要注意的逻辑点: 1. 数据的划分是否合理,不同的划分方式可能会影响结果。 2. 模型的评估指标是否只考虑了准确率,是否需要综合其他指标。 3. 代码中的随机数种子设置,不同的随机数可能导致结果有一定的波动。 ######[AI写代码神器 | 432点数解答 | 2024-11-26 21:27:00]
- 用 NumPy 与 Scikit-learn 实现线性回归:模拟数据、训练模型、评估与可视化全流程(阿里通义 | 651点数解答 | 2025-06-12 13:18:59)122
- Python代码实现:用线性回归模型根据年龄、体重和血压预测胆固醇水平(阿里通义 | 404点数解答 | 2025-06-29 17:53:11)116
- 微信收款助手监控程序代码剖析:功能、问题与改进方向(DeepSeek | 282点数解答 | 2025-04-11 00:32:28)208
- 高考毕业晚会难题:从学生能力值求最大默契程度的Python解法(字节豆包 | 487点数解答 | 2026-01-24 13:10:18)40
- 旅行售货员问题:详细步骤剖析与贪心算法Python代码实现(字节豆包 | 444点数解答 | 2024-12-17 03:32:59)275
- Dev C++ 实现旅行售货员问题:最小路程路线代码与详细解析 (字节豆包 | 448点数解答 | 2024-12-17 03:33:42)176
- C++ 求解 P1020 小核桃与删除字符串问题:双指针与枚举策略 (字节豆包 | 330点数解答 | 2026-02-07 18:40:10)23
- 产品缺陷频数监控:加权卡方与休哈特控制图实战应用(阿里通义 | 925点数解答 | 2025-04-05 17:47:55)226
- Python 实现未完成任务重新定价效果评估:成本增加额与新增任务完成量计算(字节豆包 | 612点数解答 | 2025-05-04 22:31:18)134
- Python 实现:未完成任务重新定价效果评估(成本增加额与新增任务完成量计算)(阿里通义 | 578点数解答 | 2025-05-04 22:36:52)168