🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Random Forests

A random forest is a group of decision trees that vote. Each tree sees a different sample of the rows, and the majority vote wins.

Ten trees against one hundred

n_estimators sets the tree count. The forest with 100 trees scores higher on the test rows here.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.ensemble import RandomForestClassifier
small = RandomForestClassifier(n_estimators=10, random_state=42)
small.fit(X_train, y_train)
big = RandomForestClassifier(n_estimators=100, random_state=42)
big.fit(X_train, y_train)
print(round(small.score(X_test, y_test), 3))
print(round(big.score(X_test, y_test), 3))

The most useful feature

feature_importances_ scores each feature. argmax() picks the highest score, and the name shows which feature won.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
print(data.feature_names[forest.feature_importances_.argmax()])

The forest predicts

predict() runs every tree and counts the votes. The first three test rows all get the right label here.

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
print(forest.predict(X_test[:3]).tolist())
print(y_test[:3].tolist())

Example

from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
data = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(data.data, data.target, test_size=0.2, random_state=42)
tree = DecisionTreeClassifier(max_depth=3, random_state=42)
tree.fit(X_train, y_train)
forest = RandomForestClassifier(n_estimators=100, random_state=42)
forest.fit(X_train, y_train)
print("One tree test accuracy:", round(tree.score(X_test, y_test), 3))
print("Forest test accuracy:", round(forest.score(X_test, y_test), 3))
print("Forest train accuracy:", round(forest.score(X_train, y_train), 3))
print("Trees in the forest:", len(forest.estimators_))
top = data.feature_names[forest.feature_importances_.argmax()]
print("Most useful feature:", top)

Key points

  • Ensemble: a group of models that vote together on one answer
  • Random forest: an ensemble of decision trees, each trained on a different sample
  • Use RandomForestClassifier to build a forest for classification
  • Use n_estimators to set how many trees the forest holds
  • Each tree votes once. The class with the most votes is the forest answer.
  • Use forest.feature_importances_ to see which features the forest used most
  • A forest beats one tree when the trees make different mistakes

In this example, the forest learns from breast cancer measurements, each row labelled benign or malignant. The split keeps 20 percent of the rows aside for testing. A single tree with max_depth=3 scores 0.947 on the test rows. A forest of 100 trees scores 0.965 on the same test rows. The forest holds 100 trees, and its most useful feature is worst area. The vote of many trees beats one tree here.

Note

More trees steady the vote, but they do not fix a bad split of the data.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Why does a random forest often beat one decision tree?