python - scikit-learn RandomForestClassifier 怀疑过拟合二元分类玩具问题
问题描述
我正在尝试训练一个随机森林来对鸢尾花数据集中的一组花的种类进行分类。但是,验证对我来说有点奇怪,因为结果看起来很完美,这是我没想到的。
由于我想执行二进制分类,我从训练数据集中排除了物种属于类别“2”的花,因此我只有 0/1 朵花。
我的代码有问题吗?
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
iris = load_iris()
X = iris.data
y = iris.target
X = X[y != 2]
y = y[y != 2]
forest = RandomForestClassifier(n_estimators=100, max_depth=2, max_samples=0.7, max_features=2)
print(cross_val_score(forest, X, y, scoring='accuracy'))
输出:
array([1., 1., 1., 1., 1.])
解决方案
代码很好,您拥有的数据集很容易分离,您可以将其可视化:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1,2,figsize=(12,6))
ax[0].scatter(X[:,0],X[:,1],c = y)
ax[0].set_xlabel(iris.feature_names[0])
ax[0].set_xlabel(iris.feature_names[1])
ax[1].scatter(X[:,2],X[:,3],c = y)
ax[1].set_xlabel(iris.feature_names[2])
ax[1].set_xlabel(iris.feature_names[3])
右侧的图显示了您的第 3 列和第 4 列(花瓣宽度和长度),不同的颜色代表不同的标签。因此,如果您对 80% 的数据进行训练,您可以根据在第 3 列和第 4 列设置正确的拆分,轻松正确地预测剩余 20% 的验证数据。
您还可以通过其中 1 个折叠的重要性得分看到这一点:
from sklearn.model_selection import train_test_split
import pandas as pd
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
forest.fit(X_train,y_train)
importances = pd.Series(forest.feature_importances_,index=iris.feature_names)
importances = importances.sort_values()
importances.plot.barh()
推荐阅读
- http - 在浏览器选项卡中查询时如何保护 GET 请求
- pytest - 是否可以从找到 conftest 的某个文件夹运行 pytest,但在另一个文件夹中收集测试
- python - 将时间序列向量的 2D 矩阵重塑为序列(帧)的 3D 矩阵 - 重叠窗口
- java - 为什么我的程序在 vjudge.net 中被标记为错误答案,尽管我的输出是相同的?
- typescript - 如何添加索引签名以导出默认对象
- vb.net - 删除资源中的图像后,我的 VB 表单设计变为空白
- angular - 如何在提交功能(Angular)中传递路由导航数据
- omnet++ - 在静脉 omnet 中使用 timerManager 时如何取消计时器
- regex - Oracle:比较来自两个不同表的两列的逗号分隔值
- python - 如何防止将类对象的重复项附加到 Python 列表中?