Machine Learning with scikit-learn

Random Forest in Python with scikit-learn

Let 200 decision trees vote, measure the accuracy and find out which features the forest relies on.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • RandomForestClassifier and n_estimators
  • Reading feature_importances_
  • Why many trees beat one
One prediction
  1. 1200 treesEach tree votes
  2. 2benign / malignantCount the votes
  3. 3benignMajority wins

Many trees, one vote

Découvrez Random Forest in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. n_estimators=200 builds 200 trees; random_state=42 makes the result repeatable.
  2. The forest classifies 95.8% of the test tumours correctly.
  3. feature_importances_ sums to 1; worst perimeter (0.146) and worst area (0.137) come first.
  4. Trees do not need scaled features, so there is no StandardScaler.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

main.py
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
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.25, random_state=42, stratify=data.target
)

# 200 decision trees, each trained on a random sample of rows and features
forest = RandomForestClassifier(n_estimators=200, random_state=42)
forest.fit(X_train, y_train)
print(f"Test accuracy: {forest.score(X_test, y_test):.3f}")

# Which features did the trees rely on most?
ranked = sorted(zip(forest.feature_importances_, data.feature_names), reverse=True)
print("Top 5 features:")
for importance, name in ranked[:5]:
    print(f"  {name:<22} {importance:.3f}")

print("Prediction for the first test tumour:", data.target_names[forest.predict(X_test[:1])[0]])
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Test accuracy: 0.958
Top 5 features:
  worst perimeter        0.146
  worst area             0.137
  worst concave points   0.107
  mean concave points    0.104
  worst radius           0.076
Prediction for the first test tumour: benign

Explication du code

Cet exemple montre Random Forest in Python with scikit-learn en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon