Random Forest in Python with scikit-learn
Let 200 decision trees vote, measure the accuracy and find out which features the forest relies on.
- RandomForestClassifier and n_estimators
- Reading feature_importances_
- Why many trees beat one
- 1
200 treesEach tree votes - 2
benign / malignantCount the votes - 3
benignMajority 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
n_estimators=200builds 200 trees;random_state=42makes the result repeatable.- The forest classifies 95.8% of the test tumours correctly.
feature_importances_sums to 1; worst perimeter (0.146) and worst area (0.137) come first.- 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
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]])
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.
- Change random_state and see how much the score moves.
- Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
- Try a different model or hyperparameter and compare the scores.
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éfisOutils pour cette leçon
- Bases de la classification : softmax et k plus proches voisins en PythonTransformez des scores en probabilités de classes avec softmax, évaluez-les avec l'entropie croisée et classez des points avec les k plus proches voisins.
- Jupyter Notebook en ligne : exécuter des cellules Python dans le navigateurJupyter Notebook en ligne gratuit : exécutez des cellules Python avec pandas, NumPy et Matplotlib, ajoutez du texte en Markdown, ouvrez et téléchargez des fichiers .ipynb. Sans installation, sans compte.
- Basthon, Capytale ou CodeUtility : quel outil pour Python en ligne ?Basthon, Capytale et CodeUtility comparés pour écrire du Python en ligne au lycée : à quoi sert chaque outil, compte, débogueur, exercices et classes.