酷代码 AI
菜单
服务商

深度探寻: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]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]