The Wayback Machine - https://web.archive.org/web/20240613135425/https://www.geeksforgeeks.org/how-to-extract-the-decision-rules-from-scikit-learn-decision-tree/
Open In App

How to Extract the Decision Rules from scikit-learn Decision-tree?

Last Updated : 30 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

You might have already learned how to build a Decision-Tree Classifier, but might be wondering how the scikit-learn actually does that. So, in this article, we will cover this in a step-by-step manner. You can run the code in sequence, for better understanding. 

Decision-Tree uses tree-splitting criteria for splitting the nodes into sub-nodes until each splitting becomes pure with respect to the classes or targets. In each splitting, to know the purity of splitting we calculate a Gini Impurity/Gini Index, which ranges between 0 & 1. For pure splitting, the Gini Index is 0, and the tree stops there, or else the tree continues to split for the non-zero values. The splitting criteria are chosen by an algorithm, such that the Gini index always remains minimum for each split. This algorithm is also called CART (Classification and Regression Trees). This can also be done by calculating Entropy instead of Gini Impurity. To extract the decision rules from the decision tree we use the sci-kit-learn library. Let’s see by an example, how this is done.

Importing Libraries

Python libraries make it very easy for us to handle the data and perform typical and complex tasks with a single line of code.

  • Pandas – This library helps to load the data frame in a 2D array format and has multiple functions to perform analysis tasks in one go.
  • Numpy – Numpy arrays are very fast and can perform large computations in a very short time.
  • Matplotlib– This library is used to draw visualizations.
  • Sklearn – This module contains multiple libraries having pre-implemented functions to perform tasks from data preprocessing to model development and evaluation.

Python3




import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier
  
from sklearn import tree


Importing Dataset

In this example, we will look into a binary-classification problem, where the label for the salary of an employee greater than 100k is 1 and less than 100k is 0. The code to load the data is as follows:

Python3




url = 'https://raw.githubusercontent.com/\
Stitaprajna/Practise-codes/main/salaries.csv'
df = pd.read_csv(url)
df


Output:

The Employee dataset with job type, degree and salary structure

The Employee dataset with job type, degree, and salary structure  

Next, we will build a Decision-tree using sci-kit-learn, and then finally we will plot the tree using sklearn.tree.plot_tree(). The code is as follows:

Python3




# Setting the Input
input = df.drop('salary_more_then_100k', axis=1)
  
# Label Encoding the Ordinal columns in 
# the dataset
le = LabelEncoder()
input['company_n'] = le.fit_transform(input['company'])
input['jobs_n'] = le.fit_transform(input['job'])
input['degree_n'] = le.fit_transform(input['degree'])
  
# Building the Descision-Tree
input_n = input[['company_n','jobs_n','degree_n']]
model = DecisionTreeClassifier()
model.fit(input_n, df.salary_more_then_100k)
  
# Creating the tree plot
tree.plot_tree(model, filled=True)
plt.rcParams['figure.figsize'] = [10,10]


Output:

The Binary Decision-Tree created showing the tree splitting criteria and Gini Index for the Employee Dataset

The Binary Decision-Tree created showing the tree splitting criteria and Gini Index for the Employee Dataset

Features of the model

Features of the model

Now, let’s try to understand this diagram and try to extract the decision rules used by sklearn for splitting. 

  • If we begin from the Root Node, which is the topmost light blue box, you can see that the splitting criteria are X[0] <= 0.5, with a Gini index of 0.469. So, there will be splitting into two categories based on the fact that, if it satisfies the splitting criteria of X[0] or not. The ones that satisfy the criteria go to the right & the others go left of the tree.
  • Now, we have two nodes and again based on the Gini Index the splitting happens. If the Gini Index is 0.0, the grouped data is considered pure and no further splitting occurs. 
  • You might be able to see the ‘deep orange’ and ‘deep blue’ boxes, with zero Gini index, these are actually the pure class (0 or 1). The color is ‘blue’ or ‘orange’ based on the fact that it’s either 0 or 1 class (salary_more_then_100k). The density of the color defines its purity, and if the color is ‘white’, then the grouped data has equal numbers of 0 and 1 classes. 


Similar Reads

How to Extract Information from the Decision Rules in rpart Package?
The rpart package in R is widely used for creating decision tree models. Decision trees are valuable because they provide a clear and interpretable set of rules for making predictions. Extracting and understanding these rules can offer insights into how the model makes decisions and which features are most important. This article will guide you thr
4 min read
Map Data to a Normal Distribution in Scikit Learn
A Normal Distribution, also known as a Gaussian distribution, is a continuous probability distribution that is symmetrical around its mean. It is defined by its norm, which is the center of the distribution, and its standard deviation, which is a measure of the spread of the distribution. The normal distribution is often used to model continuous an
5 min read
ML | Cancer cell classification using Scikit-learn
Machine Learning is a sub-field of Artificial Intelligence that gives systems the ability to learn themselves without being explicitly programmed to do so. Machine Learning can be used in solving many real world problems. Let's classify cancer cells based on their features, and identifying them if they are 'malignant' or 'benign'. We will be using
10 min read
ML | Implement Face recognition using k-NN with scikit-learn
k-Nearest Neighbors: k-NN is one of the most basic classification algorithms in machine learning. It belongs to the supervised learning category of machine learning. k-NN is often used in search applications where you are looking for “similar” items. The way we measure similarity is by creating a vector representation of the items, and then compare
5 min read
Implementing PCA in Python with scikit-learn
In this article, we will learn about PCA (Principal Component Analysis) in Python with scikit-learn. Let's start our learning step by step. WHY PCA? When there are many input attributes, it is difficult to visualize the data. There is a very famous term ‘Curse of dimensionality in the machine learning domain.Basically, it refers to the fact that a
4 min read
Probability Calibration for 3-class Classification in Scikit Learn
Probability calibration is a technique to map the predicted probabilities of a model to their true probabilities. The probabilities predicted by some classification algorithms like Logistic Regression, SVM, or Random Forest may not be well calibrated, meaning they may not accurately reflect the true probabilities of the target classes. This can lea
4 min read
Pipelines - Python and scikit-learn
The workflow of any machine learning project includes all the steps required to build it. A proper ML project consists of basically four main parts are given as follows: Gathering data: The process of gathering data depends on the project it can be real-time data or the data collected from various sources such as a file, database, survey and other
4 min read
How To Create/Customize Your Own Scorer Function In Scikit-Learn?
A well-known Python machine learning toolkit called Scikit-learn provides a variety of machine learning tools and methods to assist programmers in creating sophisticated machine learning models. A strong framework for assessing the effectiveness of these models using a variety of metrics and scoring functions is also offered by Scikit-learn. To ass
4 min read
Clustering Performance Evaluation in Scikit Learn
In this article, we shall look at different approaches to evaluate Clustering Algorithms using Scikit Learn Python Machine Learning Library. Clustering is an Unsupervised Machine Learning algorithm that deals with grouping the dataset to its similar kind data point. Clustering is widely used for Segmentation, Pattern Finding, Search engine, and so
3 min read
How to Get Regression Model Summary from Scikit-Learn
In this article, we are going to see how to get a regression model summary from sci-kit learn. It can be done in these ways: Scikit-learn PackagesStats model packageExample 1: Using scikit-learn. You may want to extract a summary of a regression model created in Python with Scikit-learn. Scikit-learn does not have many built-in functions for analyz
3 min read