Decision Tree (Decision Tree)
A decision tree is a commonly used machine learning algorithm, widely applied to classification and regression problems.
A decision tree represents the decision process with a tree structure: each internal node represents a test of a feature or attribute, each branch represents the outcome of the test, and each leaf node represents a class or value.
Basic Concepts of Decision Trees
- Node: Each point in the tree is called a node. The root node is the starting point of the tree, internal nodes are decision points, and leaf nodes are the final decision outcomes.
- Branch: The path from one node to another is called a branch.
- Split: The process of dividing a dataset into multiple subsets based on a certain feature.
- Purity: A measure of whether the samples in a subset belong to the same class. The higher the purity, the more similar the samples in that subset.
How Decision Trees Work
A decision tree builds its structure by recursively splitting the dataset into smaller subsets. The specific steps are as follows:
- Select the Best Feature: Choose the best feature for splitting based on some criterion (such as information gain, Gini index, etc.).
- Split the Dataset: Divide the dataset into multiple subsets based on the selected feature.
- Recursively Build Subtrees: Repeat the above process for each subset until a stopping condition is met (for example, all samples belong to the same class or the maximum depth is reached).
- Generate Leaf Nodes: When a stopping condition is met, generate a leaf node and assign it a class or value.
Criteria for Building Decision Trees
When building a decision tree, we need to select the best feature for splitting; commonly used criteria are:
1. Information Gain
Used for classification problems; it measures the increase in the purity of the dataset after selecting a certain feature. The calculation formula is:

where Entropy is the entropy of the dataset, used to measure the uncertainty of the data.
2. Gini Index
Also a splitting criterion used for classification problems; the calculation formula is:

where pi is the proportion of samples belonging to class i. The smaller the Gini index, the purer the dataset.
3. Mean Squared Error (MSE)
Used for regression problems; it measures the difference between predicted values and true values.
The smaller the MSE, the better the predictive performance of the regression tree.
Advantages and Disadvantages of Decision Trees
Advantages
- Easy to Understand and Interpret: The structure of a decision tree is intuitive and easy to understand and interpret.
- Handles Multiple Data Types: It can handle both numeric and categorical data.
- No Data Standardization Required: Decision trees do not require data to be standardized or normalized.
Disadvantages
- Prone to Overfitting: Decision trees are prone to overfitting, especially when the dataset is small or the tree depth is large.
- Sensitive to Noise: Decision trees are relatively sensitive to noisy data, which may lead to degraded model performance.
- Unstable: Small changes in the data can lead to a completely different tree being generated.
Implementing a Decision Tree in Python
Next, we will use thescikit-learnlibrary to implement a simple decision tree classifier.
1. Install the Necessary Libraries
First, make sure you have installed thescikit-learnlibrary. If not, you can install it with the following command:
pip install scikit-learn
2. Import Libraries and Load the Dataset
We will usescikit-learnthe built-in Iris dataset to demonstrate the use of decision trees.
Example
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
tree
import
DecisionTreeClassifier
from
sklearn.
metrics
import
accuracy_score
Load the Iris dataset
iris
=
load_iris
(
)
X
=
iris.
data
y
=
iris.
target
Split the Dataset into Training and Test Sets
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
,
random_state
=
42
)
3. Train the Decision Tree Model
Next, we useDecisionTreeClassifierto train the decision tree model.
Example
Create a decision tree classifier
clf
=
DecisionTreeClassifier
(
)
Train the model
clf.
fit
(
X_train
,
y_train
)
4. Prediction and Evaluation
Use the trained model to make predictions on the test set and evaluate the model's accuracy.
Example
Make predictions on the test set
y_pred
=
clf.
predict
(
X_test
)
Compute accuracy
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
(
f
"Model Accuracy: {accuracy:.2f}"
)
Output result:
模型准确率: 1.00
5. Visualize the Decision Tree
To understand the structure of the decision tree more intuitively, we can use thegraphvizlibrary to visualize the decision tree.
graphviz download address:https://graphviz.org/download/
- On Windows, you can download an installer package for Windows (.msi file).
- On Linux, you can install it with a package manager command, such as apt install graphviz
- On macOS, the installation command is brew install graphviz.
You can also install from source by downloading the latest source package (.tar.gz file).
tar -zxvf graphviz-.tar.gz
cd graphviz-
./configure
make
sudo make install
After installation, you can verify that Graphviz was installed successfully with the following command:
dot -V
Output similar to the following indicates a successful installation:
dot - graphviz version 12.2.1 (20241206.2353)
Installation graphviz Libraries:
Example
pip
install
graphviz
Then, use the following code to generate a visualization of the decision tree:
Example
from
sklearn.
datasets
import
load_iris
from
sklearn.
model_selection
import
train_test_split
from
sklearn.
tree
import
DecisionTreeClassifier
from
sklearn.
metrics
import
accuracy_score
from
sklearn.
tree
import
export_graphviz
import
graphviz
Load the Iris dataset
iris
=
load_iris
(
)
X
=
iris.
data
y
=
iris.
target
Split the Dataset into Training and Test Sets
X_train
,
X_test
,
y_train
,
y_test
=
train_test_split
(
X
,
y
,
test_size
=
0.3
,
random_state
=
42
)
Create a decision tree classifier
clf
=
DecisionTreeClassifier
(
)
Train the model
clf.
fit
(
X_train
,
y_train
)
Make predictions on the test set
y_pred
=
clf.
predict
(
X_test
)
Compute accuracy
accuracy
=
accuracy_score
(
y_test
,
y_pred
)
(
f
"Model Accuracy: {accuracy:.2f}"
)
Export the decision tree to a dot file
dot_data
=
export_graphviz
(
clf
,
out_file
=
None
,
feature_names
=
iris.
feature_names
,
class_names
=
iris.
target_names
,
filled
=
True
,
rounded
=
True
,
special_characters
=
True
)
Render the decision tree using graphviz
graph
=
graphviz.
Source
(
dot_data
)
graph.
render
(
"iris_decision_tree"
)
Save as a PDF file
graph.
view
(
)
View in a browser
Running the above code generates an iris_decision_tree.pdf file, shown below:
