Machine Learning with scikit-learn

Decision Tree in Python with scikit-learn

Train a tree of yes/no questions, print it with export_text, and limit its depth to stop it memorising.

  • Intermédiaire
  • 2 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • DecisionTreeClassifier and max_depth
  • Reading the rules with export_text
  • Spotting overfitting from train and test scores
The depth-2 iris tree
  • petal width <= 0.75
    • class 0
    • petal length <= 4.75
      • class 1
      • class 2

A tree of questions

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

Points clés

  1. The first question is petal width (cm) <= 0.75: if yes, the flower is class 0.
  2. Otherwise petal length (cm) <= 4.75 separates class 1 from class 2.
  3. The depth-2 tree scores 0.956 on the test set.
  4. Without a limit the tree reaches depth 6 and 1.000 on the training data, a sign of memorising.

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_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, test_size=0.3, random_state=1, stratify=iris.target
)

# max_depth=2 keeps the tree small enough to read
tree = DecisionTreeClassifier(max_depth=2, random_state=0)
tree.fit(X_train, y_train)
print(f"Test accuracy (depth 2): {tree.score(X_test, y_test):.3f}")
print(export_text(tree, feature_names=list(iris.feature_names)))

deep = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"No depth limit: depth {deep.get_depth()}, train {deep.score(X_train, y_train):.3f}, test {deep.score(X_test, y_test):.3f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Test accuracy (depth 2): 0.956
|--- petal width (cm) <= 0.75
|   |--- class: 0
|--- petal width (cm) >  0.75
|   |--- petal length (cm) <= 4.75
|   |   |--- class: 1
|   |--- petal length (cm) >  4.75
|   |   |--- class: 2

No depth limit: depth 6, train 1.000, test 0.978

Explication du code

Cet exemple montre Decision Tree 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