首页 > 解决方案 > 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.])

标签: pythonmachine-learningscikit-learnclassificationrandom-forest

解决方案


代码很好,您拥有的数据集很容易分离,您可以将其可视化:

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()

在此处输入图像描述


推荐阅读