Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Decision Tree (Decision Tree)

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

How Decision Trees Work

A decision tree builds its structure by recursively splitting the dataset into smaller subsets. The specific steps are as follows:

  1. Select the Best Feature: Choose the best feature for splitting based on some criterion (such as information gain, Gini index, etc.).
  2. Split the Dataset: Divide the dataset into multiple subsets based on the selected feature.
  3. 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).
  4. 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

Disadvantages


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

)

print

(

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/

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

)

print

(

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: