iTranslated by AI
Plotting Learning Curves for Random Forest
Introduction
As human beings, we all find joy in looking at graphs, don't we?
For all you humans out there, this article introduces how to draw the learning curve[1] for a Random Forest (hereinafter RF).
Even for those who don't find joy in looking at graphs, you're probably curious about whether your RF model is actually improving its performance as you add more weak learners.
Why Look at RF Learning Curves?
For models like deep learning, the benefits of looking at learning curves are easy to understand because training takes time and losses can diverge (especially in models with training instability).
But why is it meaningful to look at a graph depicting evaluation metrics for each number of weak learners in an RF?
My answer to that is "to check the degree of overfitting in the RF."
For example, if the out-of-sample learning curve is downward-sloping, you might suspect overfitting to the training data or a lack of diversity among the trees. (To prevent overfitting to the training data, lowering max_depth might be effective. If there's insufficient diversity among trees, lowering the ratio of features selected during bagging might help.)
Implementation
This is an implementation using the Iris classification dataset. The multi-class classification problem is solved with RF, and the cross-entropy loss is displayed in a graph.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
data = load_iris()
X = data.data[:, :]
y = data.target
label_num = np.unique(y).size
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, shuffle=True)
rf_param = {
'n_estimators': 100,
'max_depth': 3,
'max_leaf_nodes': 4,
'random_state': 60,
'max_samples': 0.1
}
rf_model = RandomForestClassifier(**rf_param)
rf_model.fit(X, y)
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import log_loss
# plot metrics by n_estimators
# cf: https://www.kaggle.com/code/ahmedabdulhamid/best-n-estimators-for-randomforest
def evalplot_by_n_estimators(x, y, title):
prediction_array = np.ndarray((x.shape[0], label_num))
scores = list()
tree_cnt = 0
for tree in rf_model.estimators_:
pred = tree.predict_proba(x)
prediction_array = float(tree_cnt) / float(tree_cnt + 1) * np.nan_to_num(prediction_array, nan=0.5) + np.nan_to_num(pred, nan=0.5) / float(tree_cnt + 1)
scores.append(log_loss(y, prediction_array))
tree_cnt += 1
assert tree_cnt == len(rf_model.estimators_)
n_estimators = range(1, tree_cnt+1)
plt.figure(figsize=(10, 6))
plt.plot(n_estimators, scores, label=title)
plt.xlabel('Number of Estimators')
plt.ylabel('Score')
plt.title(title)
plt.legend()
plt.grid(True)
plt.show()
import numpy as np
evalplot_by_n_estimators(X_train, y_train, "cross entropy loss score in sample")
evalplot_by_n_estimators(X_test, y_test, "cross entropy loss score out of sample")
Results


The resulting graphs are not very interesting. It seems the Iris dataset was too simple.
(When plotted with a model solving a cryptocurrency price prediction problem, the resulting graphs seemed reasonably meaningful.)


References
https://www.kaggle.com/code/ahmedabdulhamid/best-n-estimators-for-randomforest I referred to the implementation in this article, but since the implementation that allocates memory every time ran out of RAM, I changed it to update the average online.
-
This name is probably not appropriate. However, since I didn't know what else to call it, in this article, I refer to a graph where the horizontal axis represents
n_estimators(the number of weak learners comprising the RF) and the vertical axis represents an evaluation metric (such as ROC-AUC for binary classification) as a "learning curve." Since RF is not a model that learns by minimizing an evaluation metric, I think the name "learning" curve is a bit questionable, and for the same reason, I believe terms like "loss curve" are also inappropriate. ↩︎
Discussion
これスプリットする前のデータに対してfitしてしまってるのでtestもtrainもfitしきるのは当たりまえですね。