【问题标题】:RandomForestClassifier in ColabColab 中的随机森林分类器
【发布时间】:2020-07-02 05:39:32
【问题描述】:

我在 colab 单元中有以下代码:

import sklearn.datasets
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
import sklearn
from sklearn.ensemble import RandomForestClassifier

#Create a Gaussian Classifier
rfc=RandomForestClassifier(n_estimators=5, max_depth=3)
iris_sklearn_ds=sklearn.datasets.load_iris()
X_ndarray = iris_sklearn_ds.data
y_ndarray = iris_sklearn_ds.target.astype(np.int32)
X_ndarray_train,X_ndarray_test,y_ndarray_train,y_ndarray_test = train_test_split(X_ndarray,
                                                 y_ndarray,
                                                 test_size=0.30,
                                                 random_state=42)

#Train the model using the training sets y_pred=clf.predict(X_test)
rfc.fit(X_ndarray_train,y_ndarray_train)
y_pred=rfc.predict(X_ndarray_test)
print("Accuracy RFC:",metrics.accuracy_score(y_ndarray_test, y_pred))
print(metrics.confusion_matrix(y_ndarray_test, y_pred))

当我第一次执行单元格时,它给出:

Accuracy RFC: 0.9333333333333333
[[16  0  0]
 [ 0 14  0]
 [ 0  3 12]]

好吧,为什么不...但是当我第二次执行它时,我有:

Accuracy RFC: 1.0
[[16  0  0]
 [ 0 14  0]
 [ 0  0 15]]

谁能告诉我为什么?有缓存之类的吗?我需要重置一些东西吗?

【问题讨论】:

标签: python machine-learning scikit-learn google-colaboratory


【解决方案1】:

您需要在调用RandomForestClassifier() 时添加参数random_state,就像您对train_test_split() 所做的那样,因为此分类器的部分操作基于随机性,并且随机性在每次执行时具有不同的结果。

【讨论】:

    猜你喜欢
    • 2018-02-18
    • 2018-05-20
    • 2018-03-05
    • 1970-01-01
    • 2019-09-05
    • 2013-09-22
    • 2020-04-27
    • 2019-08-11
    • 1970-01-01
    相关资源
    最近更新 更多