How to Train a Decision Tree Model in Python: Step-by-Step Tutorial

A student measures the shapes of different dry beans and asks a practical question: could Python learn simple rules that identify their varieties? Rather than manually inventing dozens of if–else conditions, a decision tree examines labeled examples and selects thresholds that separate categories. Its output can be surprisingly interpretable: to explain a prediction, we can follow the branches from the root to a leaf. But how does the computer choose these thresholds, and why can a tree become overconfident?

In this decision tree Python tutorial, we study the mathematical answers—Gini impurity, entropy, information gain, node samples and stopping rules—and build a real scikit-learn classifier. You will evaluate genuine predictions, inspect a fitted tree, trace an individual observation, tune hyperparameters using cross-validation, test cost-complexity pruning and safely save a reusable model. The code and figures come from an executed notebook and script.

Dataset transparency: The original plan was the UCI Dry Bean dataset, an authentic 13,611-row, 16-feature, seven-class image-measurement dataset. Its bytes could not be downloaded in the execution environment. Rather than invent Dry Bean results, the executed project uses scikit-learn’s built-in Wine chemical-measurement recognition dataset (178 observations, 13 numerical features, three encoded categories). It is an educational statistics and chemistry example, not advice about drinking alcohol. The principles, code structure and model-selection methods transfer to suitable other classification datasets.

This tutorial is more advanced than our first machine learning model project, which introduces basic training with Iris flowers. We will focus instead on the decision criteria, interpretation and model-selection discipline that make a tree experiment scientifically meaningful.

What is a decision tree in machine learning?

A decision tree is a predictive model that divides a feature space into regions by recursively applying learned conditions. In classification, its final regions produce predicted categories; in regression, they produce numerical estimates. At an internal node the model tests a feature, such as whether color_intensity is less than a learned threshold. One branch corresponds to the condition being true and the other to false. New observations follow the branches until reaching a terminal leaf.

A tree does not automatically follow rules invented by a programmer. In scikit-learn’s basic classification tree, the fitting procedure considers candidate thresholds and chooses splits according to the specified criterion, subject to limitations such as maximum depth and minimum leaf size. A greedy algorithm optimizes splits locally; it does not guarantee that the overall tree is the globally best possible decision structure.

Decision tree anatomy: roots, branches, leaves and depth

The root node is where every training observation begins. An internal node asks a question about a numerical feature; a branch represents its outcome; a leaf contains a terminal prediction. Depth counts how many edges separate a node from the root, and the root is depth zero in scikit-learn’s convention. Node samples describe the observations reaching it. Impurity measures the mixture of classes in a classification node.

Illustrative decision tree with root internal nodes true false branches and leaf predictions.
Conceptual anatomy. The example feature thresholds are illustrative, not trained on the dataset.

Reading a tree involves following actual logical tests. A path such as feature_A ≤ 5.2 then feature_B > 1.7 means that both comparisons were satisfied for the observation. The resulting leaf may show class counts; a classifier commonly predicts whichever class has the largest weighted count at that leaf. Such paths explain the fitted algorithm’s computation, not why a natural phenomenon occurs.

Classification trees versus regression trees

PropertyDecisionTreeClassifierDecisionTreeRegressor
TargetClass label, such as class_0Numerical quantity, such as strength
Typical split criteriaGini, entropy, log lossSquared error, Friedman MSE, absolute error, Poisson
Leaf outputClass decision or class proportionsNumeric prediction, often a leaf average
EvaluationAccuracy, F1, confusion matrixMAE, RMSE, R²

Classification impurity measures the mixture of labels, whereas regression objectives typically measure numerical prediction loss. A regression tree with squared-error splits predicts constant values within individual leaves, creating a piecewise-constant function that generally cannot extrapolate beyond the response behavior supported by training regions. Applying classification accuracy to its numerical outputs would be a category mistake. We include a small verified regression experiment near the end.

How a decision tree chooses a split

Imagine 10 fictional observations: six of Class A and four of Class B. A candidate splitting question divides them into two children. The algorithm considers whether the children become more homogeneous than the original mixed group. For continuous variables, it can evaluate thresholds between ordered feature values; the choice depends on both impurity reduction and configured constraints. It keeps splitting recursively until a stopping rule prevents further growth, or no useful eligible split remains.

A tree can find perfect rules for a small training sample and still perform badly on new measurements. That is why a model’s first training accuracy is not the final goal. We will reserve an independent test set, compare a naive baseline and select complexity settings using training-only cross-validation. This prevents a common experimental error: repeatedly choosing settings by looking at the supposed final test.

Gini impurity explained with verified arithmetic

For a classification node with class proportions p₁, p₂ and so on, Gini impurity is 1 − Σ pᵢ². It is zero when the node is pure (every observation has the same class). For our fictional parent with six Class A and four Class B observations, p(A)=0.6 and p(B)=0.4. Therefore Gini = 1 − (0.6² + 0.4²) = 1 − (0.36 + 0.16) = 0.48.

Consider a candidate split: the left child contains five A and one B (six observations), and the right child contains one A and three B (four observations). The left Gini is 0.2778; the right Gini is 0.3750. Because the children have different sizes, their contribution is weighted by 6/10 and 4/10. The weighted child impurity is approximately 0.3167, producing a Gini reduction of 0.1633.

NodeABGini
Parent640.4800
Left child510.2778
Right child130.3750
Weighted children6 total4 total0.3167
Code-generated plot of class proportions and verified Gini values for parent and child nodes.
Actual arithmetic: parent 0.4800 minus weighted children 0.3167 equals a reduction of 0.1633.

An impurity reduction tells us that this candidate split makes the classes more separated, according to Gini. It does not tell us whether this rule will generalize, and the algorithm also considers other eligible features and thresholds. The example uses made-up class counts solely to demonstrate the mathematics; it is not a computed split from the Wine recognition dataset.

Entropy and information gain: the same split examined differently

Another classification criterion is entropy, calculated as −Σ pᵢ log₂(pᵢ). It describes uncertainty in a distribution of class labels. For two equally likely classes, entropy is one bit; for a perfectly pure node, entropy is zero. When a class has probability zero, its term is handled by the mathematical limit 0 × log₂(0) = 0, not by trying to evaluate log₂(0) directly.

Using the same parent proportions of 0.6 and 0.4, entropy is 0.97095 bits. The children have entropies approximately 0.65002 and 0.81128 bits. Their size-weighted entropy is 0.71452 bits. The parent entropy minus that value is 0.25643 bits of information gain. All values were calculated using executable Python and checked in the companion verification record.

Information gain = parent entropy − weighted child entropy. Gini reduction and entropy-based information gain are related ideas, but their scales and mathematical formulas differ. You should not compare a 0.1633 Gini reduction to a 0.25643 entropy gain and declare one split universally superior based on the larger number. Each method evaluates its own criterion across the eligible candidate splits.

Actual mathematical curves comparing binary Gini and entropy as class mixture varies.
The functions both reach zero at pure nodes but use different scales and may prefer different splits.

Gini versus entropy: which should students use?

scikit-learn’s current DecisionTreeClassifier supports criterion='gini', 'entropy', and 'log_loss'. Entropy and log loss use Shannon-information-based splitting in the supported implementation. Differences can change fitted structure, but neither method is universally best. Practical results depend on the sample, feature relationships, stopping constraints and evaluation. The correct comparison uses identical training-only validation, not a claim that entropy is always more accurate or that Gini is always faster.

Trees can capture nonlinear feature interactions and often require little numerical feature scaling for basic threshold splitting. But they may be unstable under small data changes, overfit with deep branches, struggle with shifted populations and produce misleading importance rankings. A visually understandable tree is not automatically fair, scientifically causal or suitable for decisions about people.

Practical Python project: a decision tree on a verified chemical dataset

Our reproducible example asks whether 13 laboratory measurements can distinguish three class labels in a small historic chemistry benchmark. These are encoded as class_0, class_1 and class_2. The full dataset has 178 rows and 13 numeric features, with class counts 59, 71 and 48. That differs from the preferred Dry Bean dataset, which is described above but could not be downloaded in this runtime. No unverified Dry Bean prediction is presented as a result.

The project uses Python 3.13.5 and scikit-learn 1.8.0 in the tested environment, with Pandas, NumPy, Matplotlib and joblib. The public load_wine() dataset is bundled with scikit-learn, so it avoids the need for a network download. This task concerns numerical recognition and experimental design; it does not model consumer preferences or recommend alcohol consumption.

Step 1 — Define inputs and labels

The features are measured chemical attributes including alcohol, malic acid, ash, flavanoids, color intensity, hue and proline. The target is the known encoded category assigned to each observation. The dataset already supplies the 13 predictors and three known labels, so our task is supervised multiclass classification. A model learns associations between measurements and class, not the causes of a particular chemical composition.

Step 2 — Prepare Python or Google Colab

If using a local installation, install the required libraries in the same Python environment as your notebook. In Colab, verify package versions rather than assuming the runtime has identical dependencies. Avoid uploading private school data just to follow this public tutorial.

python -m pip install numpy pandas matplotlib scikit-learn joblib notebook

Step 3 — Import the libraries

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV, cross_val_score
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix, ConfusionMatrixDisplay

load_wine supplies the reference dataset; train_test_split separates independent evaluation observations; the decision tree class handles fitting and prediction; the metrics module compares predictions with known labels. Later, GridSearchCV will evaluate complexity settings using only the training part of the dataset.

Step 4 — Load and inspect the dataset

wine = load_wine(as_frame=True)
X = wine.data.copy()
y = wine.target.copy()
print('Features:', X.shape)
print('Target classes:', wine.target_names)
print(X.head())

The verified feature shape is (178, 13). The target contains exactly three classes, class_0, class_1 and class_2. These labels are encoded study categories rather than conclusions generated by the model. No image decoding or chemical laboratory work is necessary; we use numerical columns already included in the bundled dataset.

Step 5 — Explore class balance and missing values

print('Class counts:', y.value_counts().sort_index().to_dict())
print('Missing numeric cells:', X.isna().sum().sum())
print('Duplicate feature rows:', X.duplicated().sum())
print(X.describe().round(2))

The executed inspection found zero missing cells and zero identical feature rows. Class counts are 59, 71 and 48—not perfectly balanced, but each has enough observations for the planned five-fold stratified training validation. Even when duplicates appear in another dataset, they are not automatically mistakes: legitimate repeated measurements may describe different observations. Review their provenance before removing them.

Actual count of 59, 71 and 48 observations in the three Wine recognition classes.
The columns are computed from actual bundled dataset labels, not invented proportions.

Step 6 — Prepare numerical data without leakage

For this particular dataset, all 13 predictors are numerical and no values are missing. A simple decision tree can operate directly on their original values; standardization is not necessary for its threshold comparisons. Another dataset with missing values or text categories may require an appropriate preprocessing approach. Current scikit-learn versions provide conditional support for missing numeric values in some tree settings; categorical strings still need suitable encoding. Check the estimator and criterion before relying on any particular behavior.

If preprocessing learns statistics from observations, fit it on training data only, preferably inside a pipeline. The target must not be among the predictors, and future information must not leak into a supposedly earlier prediction. Our executable script uses the already-separated wine.data and wine.target variables, making the intended feature-target boundary clear.

Step 7 — Confirm the feature and target arrays

assert X.shape == (178, 13)
assert len(y) == 178
assert X.notna().all().all()
print(X.columns.tolist())

Column names must be retained for interpreting thresholds and for later prediction. If a student changes their order when constructing a new observation, the tree may apply the rule for proline to a value that was intended for some other feature. Preserve both the names and the original measurement units throughout training and prediction.

Step 8 — Separate training and held-out testing

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.20, stratify=y, random_state=42
)
print(len(X_train), len(X_test))

This reproducible split yields 142 training observations and 36 held-out test observations. Stratification approximately maintains class proportions. The test records must not be used to select the maximum depth, leaf size, splitting criterion or cost-complexity parameter. We will reserve them to estimate performance after the training-only development procedure is chosen.

Step 9 — Train the initial pre-pruned tree

tree_model = DecisionTreeClassifier(
    criterion='gini', max_depth=5,
    min_samples_leaf=3, random_state=42
)
tree_model.fit(X_train, y_train)

The gini setting selects Gini-based split scoring; max_depth=5 limits a root-to-leaf path to at most five edges; min_samples_leaf=3 requires at least three training observations in each resulting leaf. These are starting teaching settings, not an optimal recommendation. The actual fitted tree had depth 4 and seven leaves, because training may stop before the permitted maximum.

Step 10 — Predict the held-out labels

predictions = tree_model.predict(X_test)
print('First eight predicted labels:', predictions[:8].tolist())
print('First eight actual labels:', y_test.iloc[:8].tolist())

In the executed run, the first eight predictions and true labels were identical: class_0, class_2, class_0, class_1, class_1, class_0, class_0, class_1. The fact that the first few examples are correct does not establish the accuracy of the full test sample. We need to compare all 36 predictions with all 36 known labels.

Step 11 — Calculate test accuracy and a meaningful baseline

accuracy = accuracy_score(y_test, predictions)
print('Test accuracy:', round(accuracy, 4))

The initial tree got 34 of 36 held-out labels correct, for an accuracy of 0.9444 or 94.44%. The same script fitted a DummyClassifier(strategy='most_frequent') using only training labels; it achieved 38.89% on the test sample. Beating the baseline is useful evidence that the tree learned discriminating relationships, but a sample of 36 observations is far too small to establish how it will behave across unfamiliar measurement systems.

Step 12 — Read the multiclass classification report

print(classification_report(
    y_test, predictions,
    target_names=list(wine.target_names),
    zero_division=0
))

Precision describes how often a predicted category is correct. Recall describes how many known members of the category were recovered. F1 balances precision and recall; support is the number of true observations per class. A macro average treats each class equally, while a weighted average uses class support. Our initial model’s macro F1 was about 0.9475, and weighted F1 was about 0.9438. These reveal more than one overall percentage.

Step 13 — Plot an actual confusion matrix

matrix = confusion_matrix(y_test, predictions, labels=[0, 1, 2])
ConfusionMatrixDisplay(
    matrix, display_labels=wine.target_names
).plot(cmap='Greens', colorbar=False)
plt.show()
Actual classPredicted class_0Predicted class_1Predicted class_2
class_01020
class_10140
class_20010
Actual initial-model confusion matrix showing 34 correct labels and two class_0 samples predicted as class_1.
Rows are true classes; columns are predictions. The diagonal total is 10 + 14 + 10 = 34.

The matrix shows that both mistakes involved observations from actual class_0 predicted as class_1. All held-out examples from class_1 and class_2 were correct in this split. That does not establish perfect performance for those groups in future data. Class-specific errors, source quality and independent validation are necessary before any practical deployment claim.

Step 14 — Visualize the real fitted decision tree

plt.figure(figsize=(18, 9))
plot_tree(tree_model, feature_names=X.columns,
          class_names=wine.target_names,
          filled=True, rounded=True, fontsize=9,
          max_depth=3)
plt.show()
Actual Wine chemical classification tree with numerical split thresholds and truncated lower branches.
Actual fitted initial classifier. The first four levels are shown; grey ellipsis boxes indicate deeper hidden nodes.

This plot reveals the actual root condition color_intensity ≤ 3.82 for the trained model. Each internal box records the feature threshold, its node impurity, how many training observations reach it, the class counts and the most frequent class. The green, orange and purple fills visualize predicted categories, not the scientific importance of the split. The diagram is a compressed view: a more complete graphic can be exported with max_depth=None and examined at high resolution.

Step 15 — Follow one held-out observation through the rules

example = X_test.iloc[[0]]
node_path = tree_model.decision_path(example)
leaf_number = tree_model.apply(example)[0]
print('Terminal leaf:', leaf_number)
print('Predicted label:', tree_model.predict(example)[0])

A real held-out observation in the executed project had color_intensity = 5.75, which is greater than 3.82. It then satisfied flavanoids = 3.32 > 1.58, followed by proline = 1510 > 724.5, and the initial model predicted class_0. Its known actual label was also class_0. These are the trained model’s own thresholds, extracted from its fitted tree, not decorative values invented for the explanation.

Verified individual prediction path with observed color intensity 5.75 flavanoids 3.32 and proline 1510.
Three genuine comparisons lead to class_0. The path describes the classifier’s computation, not a chemical causal mechanism.

A decision path can be extremely helpful for debugging. Ask whether the input features are in their trained order, whether thresholds use consistent units, and whether the leaf contains adequate training support. A transparent explanation of a path does not mean the model has discovered a natural law. Correlated measurements may substitute for each other, and a small data change can alter which feature appears first.

Step 16 — Feature importance: useful but not causal

importances = tree_model.feature_importances_
feature_scores = pd.Series(importances, index=X.columns)
print(feature_scores.sort_values(ascending=False).head())
Actual impurity-based importance scores computed from the trained Wine recognition decision tree.
Impurity-based scores show normalized reduction associated with fitted splits; they do not establish causation.

In scikit-learn, feature_importances_ aggregates the normalized impurity reduction attributed to a feature in the fitted tree. The values sum to approximately one across features. They depend on the chosen split structure, and variables with many possible thresholds can receive inflated importance. Correlated predictors can also share or compete for apparent importance. Never claim that the top feature causes a category or that an unused feature has no scientific value.

A complementary method is permutation importance, which measures how much a fitted model’s evaluation score decreases when a feature is shuffled. Its interpretation still depends on the evaluation distribution and correlated variables. If you use test data for a final explanatory assessment, avoid feeding that importance result back into model selection, or the independent evaluation becomes compromised.

Step 17 — Recognize the difference between training and test accuracy

The initial model’s training accuracy was 97.18%, and the held-out test accuracy was 94.44%. A difference between these measures can signal the limits of generalization, but a single small split does not prove a particular level of overfitting. If both scores are low, the model may be too simple or the features inadequate. If training is perfect and validation deteriorates, the tree may be memorizing training-specific patterns.

Look beyond the two numbers. Check class balance, measurement quality, whether records are dependent or repeated, and whether a random split resembles the intended future use. For applications involving repeated records from the same person, object or instrument, group-aware validation may be more credible than an ordinary shuffled split.

Step 18 — Experiment with maximum depth using training-only validation

cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for depth in range(1, 13):
    candidate = DecisionTreeClassifier(max_depth=depth, random_state=42)
    score = cross_val_score(candidate, X_train, y_train,
                            cv=cv, scoring='balanced_accuracy').mean()
    print(depth, round(score, 4))
Actual training accuracy and training-only cross-validated balanced accuracy plotted against permitted depth.
A deeper tree can fit training examples perfectly without necessarily improving validation performance.

The graphic compares fit to the training records with cross-validated balanced accuracy, using only the 142 training rows. Balanced accuracy gives equal weight to class-specific recalls, which is useful when categories are unevenly represented. This experimental design keeps the 36 test examples out of complexity selection. Some depths may produce exactly the same tree because their other stopping conditions prevent further splitting; a line that becomes flat is not automatically a software problem.

Step 19 — Use GridSearchCV to choose parameters responsibly

parameter_grid = {
    'criterion': ['gini', 'entropy'],
    'max_depth': [2, 3, 4, 5, None],
    'min_samples_leaf': [1, 3, 5],
    'min_samples_split': [2, 6]
}
search = GridSearchCV(
    DecisionTreeClassifier(random_state=42),
    parameter_grid, scoring='balanced_accuracy', cv=cv, refit=True
)
search.fit(X_train, y_train)
selected_tree = search.best_estimator_
print(search.best_params_, search.best_score_)

The executed search evaluated 60 parameter combinations through five-fold stratified cross-validation. The selected values were criterion='gini', max_depth=5, min_samples_leaf=1, and min_samples_split=2. The mean training-only validation balanced accuracy was approximately 0.9113 (91.13%). The result is a selection among the tried settings, not proof of globally optimal hyperparameters.

Grid-search scores are development evidence. Because many choices were compared on the training folds, the best cross-validation number can itself be optimistic. For robust scientific studies, consider repeated outer validation or an independent external dataset. At a minimum, follow the classroom rule used here: tune only with training folds, then inspect the final held-out test once the model choice is fixed.

Step 20 — What does cost-complexity pruning actually do?

Pruning removes branches that are not justified under a chosen model-complexity tradeoff. Pre-pruning limits growth using settings such as max_depth, min_samples_split and min_samples_leaf. Minimal cost-complexity pruning adds a penalty for the number of leaves to an objective based on fit. scikit-learn exposes the nonnegative regularization parameter ccp_alpha: increasing it can produce a smaller tree, although the exact effects depend on the fitted data.

unrestricted = DecisionTreeClassifier(random_state=42).fit(X_train, y_train)
path = unrestricted.cost_complexity_pruning_path(X_train, y_train)
alphas = path.ccp_alphas[:-1]
# Compare eligible alphas using training-fold validation only.
# Full reproducible loop and plotting are in the downloadable notebook.
Actual cost complexity pruning candidates compared by stratified cross validation on training rows.
The selected alpha was 0.0. No stronger pruning value improved the development score in this experiment.

Here the validation-selected cost-complexity value was 0.0, representing no additional post-pruning. This is a genuine and educationally important result: pruning does not always improve a model. If a student instead chooses an alpha because it produces the highest final test accuracy, that is test-set leakage. The notebook records each evaluated alpha and its training-fold score so the method is reproducible.

Step 21 — Compare the three completed tree configurations

ModelDepthLeavesTraining accuracyTraining CV balanced accuracyHeld-out accuracy
Initial pre-pruned4797.18%89.93%94.44%
Grid-search selected48100.00%91.13%94.44%
Cost-complexity selected48100.00%91.13%94.44%

The three models were configured before their reported final test comparisons. Tuning modestly improved the mean training-fold balanced-accuracy estimate, but all three achieved the same 34/36 correctness on the particular test set. The selected post-pruned model is identical in structure to the unpruned candidate here because the best alpha was zero. The correct conclusion is not that pruning is useless; it is that this small experiment provided no validated reason to prune further.

Actual confusion matrix for the GridSearchCV selected decision tree with 34 of 36 test observations correct.
The tuned tree confused one class_0 record and one class_2 record with class_1.

Step 22 — Make a carefully labeled new prediction

For practice, take one held-out row in the exact original 13-column order and ask selected_tree.predict(X_test.iloc[[0]]). In the executed experiment this example is class_0. Its true label is also class_0, but that is only one observation. If you later supply a row collected elsewhere, confirm that every column, numerical meaning and unit match the training schema. A leaf’s predict_proba() proportions may be based on few observations and should not automatically be interpreted as well-calibrated confidence.

Step 23 — Save and safely reload your own trained tree

import joblib
joblib.dump(selected_tree, 'my_trusted_decision_tree.joblib')
# Load ONLY the file you created locally in a trusted environment:
restored = joblib.load('my_trusted_decision_tree.joblib')
assert (restored.predict(X_test) == selected_tree.predict(X_test)).all()

The complete script saved a fitted model together with column names, category labels and the scikit-learn version and verified identical predictions after reloading. Security warning: joblib is pickle-based; opening an unknown model file can execute malicious code. Only load a model you created or whose provenance is trusted, and keep versions compatible. A saved classifier is not self-documenting: preserve its code, data source, feature schema and evaluation record.

Step 24 — Write a reproducible findings report

Your README should state the research question, official source and collection limitations, observation counts, target and feature names, split procedure, initial algorithm, validation scoring, search space, chosen complexity settings, final held-out evaluation, decision path and important errors. Include the Python and scikit-learn versions, exact commands required to reproduce the charts and a limitation that the dataset is small and historic.

Example conclusion: A decision-tree classifier trained on 142 chemistry examples correctly recognized 34 of 36 held-out class labels (94.44%). A 60-configuration five-fold training-only grid search favored a particular Gini tree but did not improve this held-out accuracy. The cost-complexity comparison selected alpha zero; additional pruning had no demonstrated validation benefit. These results illustrate tree interpretation and model evaluation but do not establish broader real-world reliability.

Decision tree regression: a short runnable mini-lesson

Decision trees can also predict numbers. Here is an independent, explicitly fictional numerical sequence. We fit a depth-three DecisionTreeRegressor to nine observations and predict the next three. Regression differs from classification: the aim is a numerical target rather than one of a fixed set of labels, and mean absolute error (MAE) measures average absolute numerical miss.

import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import mean_absolute_error
x = np.arange(12).reshape(-1, 1)
y = np.array([2.,2.4,3.3,3.9,5.7,7.1,7.4,8.0,9.2,10.1,10.7,12.2])
reg = DecisionTreeRegressor(max_depth=3, random_state=42)
reg.fit(x[:9], y[:9])
predicted = reg.predict(x[9:])
print(predicted)
print(mean_absolute_error(y[9:], predicted))

In the executed result, the predicted values for the last three positions were 9.2, 9.2 and 9.2, while the fictional targets were 10.1, 10.7 and 12.2, giving MAE 1.8 in the example’s arbitrary units. The standard tree makes piecewise-constant predictions from its leaves; it does not extrapolate an increasing trend the way a correctly specified linear regression might. This synthetic example is not evidence about any real material or environmental process.

Actual fitted regression tree stepwise output compared with fictional held-out numerical values.
The code-generated line illustrates piecewise-constant predictions and why trees may extrapolate poorly.

Fourteen common decision-tree mistakes and how to correct them

  • Using a classifier for numeric targets: choose DecisionTreeRegressor and regression metrics for continuous outcomes.
  • Including the target as a feature: separate X and y before fitting.
  • Data leakage: keep future outcomes, test-derived transformations and answer columns out of training.
  • Training and testing on the same rows: reserve an independent evaluation set.
  • Growing an unlimited tree by default: consider complexity settings and cross-validation.
  • Selecting max_depth from training accuracy: use validation scores instead.
  • Ignoring uneven classes: inspect support, class recall and balanced accuracy.
  • Calling Gini a probability of correctness: it measures class mixture under its formula.
  • Confusing entropy and accuracy: entropy scores candidate splits, accuracy checks predicted labels.
  • Treating importance as causal evidence: report what the model uses, not what causes outcomes.
  • Unnecessary scaling: basic numerical threshold trees often do not need it.
  • Changing feature order: preserve original column names and units for new rows.
  • Selecting alphas from final test scores: use training-only folds for pruning selection.
  • Loading unknown joblib artifacts: never deserialize an untrusted model file.

Responsible model interpretation and ethical limits

Interpretable branches can make an algorithm easier to inspect, but they cannot guarantee accurate, fair or appropriate decisions. Historical measurement distributions may differ from current instruments or populations; a high score on a curated benchmark does not establish robustness to noisy readings, new categories or unusual operating conditions. The choice of features also matters: a tree may learn shortcuts or correlations that do not persist.

If a project involves real students, medical records, banking or hiring decisions, privacy and fairness considerations go well beyond this classroom example. Avoid collecting private records without authorization, evaluate subgroup errors where relevant and permitted, and require appropriate domain experts and human oversight for consequential use. The model’s probability estimates may be poorly calibrated in small leaves. Keep the difference between explaining one fitted decision and justifying its real-world consequences explicit.

Your four-week decision-tree learning roadmap

WeekLearning focusEvidence to produce
1Nodes, thresholds, Gini and entropyHand-calculated impurity reduction and an annotated concept tree
2Python training and evaluationNotebook with train/test separation, accuracy, baseline and confusion matrix
3Interpretation, cross-validation and pruningReal decision path, importance analysis and honest pruning comparison
4Independent project and reportingReproducible code, sources, README, limitations and a short presentation

The roadmap gives learners a manageable sequence, not a guarantee of mastery after four weeks. Students who are new to Python or statistics may need extra practice interpreting percentages, drawing graphs or debugging notebooks. Use the worksheet to demonstrate understanding before attempting a larger dataset or a real deployment.

Ten student practice exercises with solutions

Try to answer before expanding each explanation. The solutions are based on the verified arithmetic and model outputs, so they can be checked against the notebook.

1. Identify the root, branches and leaves in a tree.

The root is the starting decision node, branches correspond to results of comparisons, internal nodes contain further rules, and leaves contain terminal predictions.

2. Interpret the rule color_intensity ≤ 3.82.

An observation with color intensity at most 3.82 follows the left branch of that fitted test; one above 3.82 follows the right branch. This is a model rule, not a universal chemical law.

3. Calculate the Gini impurity of six A and four B observations.

1 − (0.6² + 0.4²) = 0.48.

4. Calculate the binary entropy for two equally likely classes.

−0.5 log₂(0.5) − 0.5 log₂(0.5) = 1 bit.

5. Calculate the Gini reduction for children (5 A, 1 B) and (1 A, 3 B).

Weighted children: 0.6×0.2778 + 0.4×0.3750 = 0.3167. Parent 0.48 − 0.3167 = 0.1633.

6. Name the scikit-learn class used for categorical predictions.

DecisionTreeClassifier. Its fit method learns thresholds from training examples and predict returns labels.

7. Explain why larger max_depth can overfit.

Deeper trees can split training observations into tiny groups and learn noise rather than broadly useful distinctions. Validation, not train score alone, guides complexity choice.

8. Interpret the initial confusion matrix.

34 of 36 test examples are correctly labeled. Two actual class_0 rows were classified as class_1; the other categories had no errors in this small split.

9. Why did cost-complexity pruning select alpha = 0 in this example?

The tested nonnegative alpha alternatives did not improve the selected training-fold validation criterion. Pruning is a conditional tradeoff, not an improvement guarantee.

10. Explain the measured decision path and one limitation.

The held-out class_0 example followed color intensity 5.75 > 3.82, flavanoids 3.32 > 1.58, and proline 1510 > 724.5. The path describes computation, not causation or reliability outside the dataset.

Download the complete student decision-tree learning resources

The Gini and entropy worksheet (PDF), worked answer guide (PDF) and model interpretation checklist (PDF) are hosted in the WordPress media library. The executed notebook, Python script, plots, verified output and full ZIP are provided separately with the publication completion report because the available WordPress media route does not support every archive and notebook format.

Optional further study — Coursera and Udemy

These two course pages are official optional resources for students who want broader Python and supervised learning practice. Disclosure: approved Notes for SHS affiliate tracking URLs could not be verified for this task. The links are ordinary course links and do not claim tracked commissions, special prices, discounts or certifications.

Editorial decision tree feature importance learning chart; not official Coursera course artwork

Supervised Machine Learning: Classification

Coursera: explores classification algorithms, evaluation and tree-based modeling concepts.

View official Coursera course details

Editorial illustration of an actual Python fitted decision tree, not official Udemy course artwork

Python for Data Science and Machine Learning Bootcamp

Udemy: broader Python, statistical analysis, visualization and machine learning practice.

View official Udemy course details

Frequently asked questions about decision trees

What is a decision tree in machine learning?

A supervised model that learns feature-based splitting rules and uses terminal leaves to predict categories or numbers.

How does a tree choose a split?

It compares eligible feature thresholds using its chosen impurity or error criterion, subject to stopping and complexity settings.

What is Gini impurity?

A classification node’s class mixture: 1 minus the sum of squared class proportions. It is zero for a pure node.

What is entropy in decision trees?

A measure of class uncertainty using negative sums of p times log base two p, with zero-probability terms treated by their limit.

Is Gini always better than entropy?

No. Either may produce useful trees. Compare using an appropriate training-only validation strategy on the actual problem.

What does max_depth control?

The maximum allowed number of splits along a root-to-leaf path, measured in edges from the root.

Why do decision trees overfit?

They can create highly specific rules matching training noise, especially without adequate limits on complexity.

What is cost-complexity pruning?

A method of trading tree fit against the number of terminal leaves, controlled by ccp_alpha in scikit-learn.

How do I visualize a fitted decision tree?

Call sklearn.tree.plot_tree with a fitted estimator and correct feature and class names; limit displayed depth if needed.

Can a decision tree predict numerical values?

Yes. DecisionTreeRegressor predicts numerical targets, commonly as piecewise-constant values within leaves.

Continue with Machine Learning for High School Students, Supervised vs. Unsupervised Learning, How to Build Your First Machine Learning Model, and 15 Beginner Machine Learning Projects. For coding foundations, see Python for Data Science Beginners. Each link points to a previously verified published post on the connected staging WordPress site.

Authoritative references: scikit-learn decision-tree guide, DecisionTreeClassifier API, cost-complexity pruning example, common pitfalls, model persistence, the executed dataset documentation, and original UCI Dry Bean dataset documentation. Sources are shown so students can check current APIs, provenance and limitations.

Conclusion: learn the splits, verify the model and interpret responsibly

A decision tree is more than a series of if–else statements. Its structure emerges from learned threshold tests, chosen impurity or error measures and constraints on complexity. You have calculated Gini and entropy, trained a real classifier, checked individual predictions against held-out labels, read a confusion matrix, followed a genuine decision path and investigated feature importance without confusing it with causation.

You have also learned why stronger training fit is not the same as better generalization. Training-only cross-validation was used to select tree settings and pruning parameters; this project found no validation benefit from additional post-pruning. The more transferable achievement is knowing how to report that evidence accurately. Use the downloadable notebook to reproduce the results, then try a new permitted dataset and explain how its errors, split rules and limitations differ.