我通过RandomForestClassifier构建了一个随机森林,并绘制了决策树.参数"值"(用红色箭头表示)是什么意思?为什么[]中的两个数字之和不等于"样本"的数量?我看到了其他一些例子,[]中的两个数字之和等于"样本"的数量.为什么我的情况不是这样?

df = pd.read_csv("Dataset.csv")
df.drop(['Flow ID', 'Inbound'], axis=1, inplace=True)
df.replace([np.inf, -np.inf], np.nan, inplace=True)
df.dropna(inplace = True)
df.Label[df.Label == 'BENIGN'] = 0
df.Label[df.Label == 'DrDoS_LDAP'] = 1
Y = df["Label"].values
Y = Y.astype('int')
X = df.drop(labels = ["Label"], axis=1)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.5)
model = RandomForestClassifier(n_estimators = 20)
model.fit(X_train, Y_train)
Accuracy = model.score(X_test, Y_test)
        
for i in range(len(model.estimators_)):
    fig = plt.figure(figsize=(15,15))
    tree.plot_tree(model.estimators_[i], feature_names = df.columns, class_names = ['Benign', 'DDoS'])
    plt.savefig('.\\TheForest\\T'+str(i))

enter image description here

推荐答案

接得好.

虽然没有记录,但这是由于bootstrap sampling默认发生在随机森林模型中(关于RF算法的详细信息及其与决策树的区别,请参阅我在Why is Random Forest with a single tree much better than a Decision Tree classifier?中的答案).

让我们看一个包含iris个数据的示例:

from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier

iris = load_iris()

rf = RandomForestClassifier(max_depth = 3)
rf.fit(iris.data, iris.target)

tree.plot_tree(rf.estimators_[0]) # take the first tree

enter image description here

这里的结果与您报告的结果类似:除了右下角的 node 外,其他 node 的sum(value)不等于samples,因为a "simple" decision tree应该是这样.

一个谨慎的观察者可能会注意到一些奇怪的事情:虽然iris数据集有150个样本:

print(iris.DESCR)

.. _iris_dataset:

Iris plants dataset
--------------------

**Data Set Characteristics:**

    :Number of Instances: 150 (50 in each of three classes)
    :Number of Attributes: 4 numeric, predictive attributes and the class

树的基本 node 应该包括所有 node ,第一个 node 的samples个 node 只有89个.

这是为什么?这里到底发生了什么?看看,让我们安装第二个RF模型,这次是without bootstrap sampling(即bootstrap=False):

rf2 = RandomForestClassifier(max_depth = 3, bootstrap=False) # no bootstrap sampling
rf2.fit(iris.data, iris.target)

tree.plot_tree(rf2.estimators_[0]) # take again the first tree

enter image description here

好了,现在我们已经禁用了 bootstrap 采样,一切看起来都"不错":每个 node 中value的总和等于samples,而基本 node 实际上包含整个数据集(150个样本).

因此,您描述的行为似乎确实是由于自举采样,在创建样本with replacement(即,最终为集合中的每个单独决策树生成duplicate个样本)时,这些重复样本不会反映在树 node 的sample个值中,这些值显示了unique个样本的数量;然而,它is反映在 node value中.

这种情况与RF回归模型完全类似——参见sklearn RandomForestRegressor discrepancy in the displayed tree values中的答案.

Python相关问答推荐

如何在Python中增量更新DF

为什么基于条件的过滤会导致pandas中的空数据框架?

强制venv在bin而不是收件箱文件夹中创建虚拟环境

如何使用Python中的clinicalTrials.gov API获取完整结果?

Python -根据另一个数据框中的列编辑和替换数据框中的列值

Pandas 都是(),但有一个门槛

如果条件不满足,我如何获得掩码的第一个索引并获得None?

如何从数据库上传数据到html?

将JSON对象转换为Dataframe

Asyncio:如何从子进程中读取stdout?

在www.example.com中使用`package_data`包含不包含__init__. py的非Python文件

Django admin Csrf令牌未设置

Tkinter菜单自发添加额外项目

使用特定值作为引用替换数据框行上的值

lityter不让我输入左边的方括号,'

如何在BeautifulSoup/CSS Select 器中处理regex?

巨 Python :逆向猜谜游戏

查看pandas字符列是否在字符串列中

如何在Airflow执行日期中保留日期并将时间转换为00:00

为什么后跟inplace方法的`.rename(Columns={';b';:';b';},Copy=False)`没有更新原始数据帧?