4

I have the following code in a colab cell :

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

When I execute the cell for the first time, it gives :

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

Ok, why not... But when I execute it a second time, I have :

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

Can anybody teel me why ? Is there a cache or something ? Do I have to reset something ?

1 Answers1

2

You need to add the parameter random_state when you call RandomForestClassifier(), as you did for train_test_split(), because this classifier bases part of its operation on randomness and the randomness has different result at each execution.

XavierBrt
  • 1,179
  • 8
  • 13