The Wayback Machine - https://web.archive.org/web/20230315201926/https://www.geeksforgeeks.org/decision-tree/
Skip to content
Related Articles
Open in App
Not now

Related Articles

Decision Tree

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 15 Mar, 2023
Improve Article
Save Article

Decision Tree is the most powerful and popular tool for classification and prediction. A Decision tree is a flowchart-like tree structure, where each internal node denotes a test on an attribute, each branch represents an outcome of the test, and each leaf node (terminal node) holds a class label. 

Decision_Tree (2)

A decision tree for the concept PlayTennis. 

Construction of Decision Tree: A tree can be “learned” by splitting the source set into subsets based on an attribute value test. This process is repeated on each derived subset in a recursive manner called recursive partitioning. The recursion is completed when the subset at a node all has the same value of the target variable, or when splitting no longer adds value to the predictions. The construction of a decision tree classifier does not require any domain knowledge or parameter setting, and therefore is appropriate for exploratory knowledge discovery. Decision trees can handle high-dimensional data. In general decision tree, classifier has good accuracy. Decision tree induction is a typical inductive approach to learn knowledge on classification. 

Short note on Decision Tree:-

  • A decision tree which is also known as prediction tree refers a tree structure to mention the sequences of decisions as well as consequences.
  • Considering the input X = (X1, X2,… Xn), the aim is to predict a response or output variable Y.
  • Each element in the set (X1, X2,…Xn) is known as input variable.It is possible to achieve the prediction by the process of building a decision tree which has test points as well as branches.
  • At each test point, it is decided to select a particular branch and traverse down the tree.
  • Ultimately, a final point is reached, and it will be easy to make prediction.
  • In a decision tree, all the test points exhibit testing specific input variables (or attributes), and the developed decision tree is represented by the branches.
  • Because of flexibility as well as simple visualization, decision trees are mostly probably deployed in data mining applications for the purpose of classification.
  • In the decision tree, the input values are considered as categorical or continuous.
  • A structure of test points (known as nodes) and branches is established by the decision tree by which the decision being made will be represented.
  • Leaf node is the one which do not have further branches. The returning value of leaf nodes is class labels while in some cases they return the probability scores.
  • It is possible to convert decision tree into a set of decision rules.
  • There are two types of Decision trees: classification trees and regression trees
  • Classification trees are generally applied to output variables which are categorical and mostly binary in nature, for example yes or no, sale or not, and so on.
  • Whereas regression trees are applied to output variables which are numeric or continuous, for example predicted price of a consumer good.
  • In variety of situations, it is possible to apply decision tree. It is easy to represent them in a visual way, and the analogous straightforward.
  • Also as the result is a sequence of logical if-then statements, there is no any presence of underlying assumption regarding a linear or nonlinear relationship between the input variables and the response variable.

Decision Tree Representation: Decision trees classify instances by sorting them down the tree from the root to some leaf node, which provides the classification of the instance. An instance is classified by starting at the root node of the tree, testing the attribute specified by this node, then moving down the tree branch corresponding to the value of the attribute as shown in the above figure. This process is then repeated for the subtree rooted at the new node. 
The decision tree in above figure classifies a particular morning according to whether it is suitable for playing tennis and returns the classification associated with the particular leaf.(in this case Yes or No). 

For example, the instance 
 

(Outlook = Sunny, Temperature = Hot, Humidity = High, Wind = Strong )

would be sorted down the leftmost branch of this decision tree and would therefore be classified as a negative instance. 
In other words, we can say that the decision tree represents a disjunction of conjunctions of constraints on the attribute values of instances. 

(Outlook = Sunny ^ Humidity = Normal) v (Outlook = Overcast) v (Outlook = Rain ^ Wind = Weak) 

Gini Index:

Gini Index is a score that evaluates how accurate a split is among the classified groups. Gini index evaluates a score in the range between 0 and 1, where 0 is when all observations belong to one class, and 1 is a random distribution of the elements within classes. In this case, we want to have a Gini index score as low as possible. Gini Index is the evaluation metrics we shall use to evaluate our Decision Tree Model.

Implementation:

Python3




from sklearn.datasets import make_classification
from sklearn import tree
from sklearn.model_selection import train_test_split
 
X, t = make_classification(100, 5, n_classes=2, shuffle=True, random_state=10)
X_train, X_test, t_train, t_test = train_test_split(
    X, t, test_size=0.3, shuffle=True, random_state=1)
 
model = tree.DecisionTreeClassifier()
model = model.fit(X_train, t_train)
 
predicted_value = model.predict(X_test)
print(predicted_value)
 
tree.plot_tree(model)
 
zeroes = 0
ones = 0
for i in range(0, len(t_train)):
    if t_train[i] == 0:
        zeroes += 1
    else:
        ones += 1
 
print(zeroes)
print(ones)
 
val = 1 - ((zeroes/70)*(zeroes/70) + (ones/70)*(ones/70))
print("Gini :", val)
 
match = 0
UnMatch = 0
 
for i in range(30):
    if predicted_value[i] == t_test[i]:
        match += 1
    else:
        UnMatch += 1
 
accuracy = match/30
print("Accuracy is: ", accuracy)

C++




// Importing required headers
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iostream>
#include <iterator>
#include <queue>
#include <random>
#include <sstream>
#include <vector>
 
#include <bits/stdc++.h>
#include <stdio.h>
 
using namespace std;
 
int main()
{
    // Generating random data for classification
    int X[100][5];
    int t[100];
    srand(10);
    for (int i = 0; i < 100; i++) {
        for (int j = 0; j < 5; j++) {
            X[i][j] = rand() % 2;
        }
        t[i] = rand() % 2;
    } // Splitting data into train and test sets
    int X_train[70][5];
    int X_test[30][5];
    int t_train[70];
    int t_test[30];
 
    for (int i = 0; i < 70; i++) {
        for (int j = 0; j < 5; j++) {
            X_train[i][j] = X[i][j];
        }
        t_train[i] = t[i];
    }
 
    for (int i = 0; i < 30; i++) {
        for (int j = 0; j < 5; j++) {
            X_test[i][j] = X[i + 70][j];
        }
        t_test[i] = t[i + 70];
    }
 
    // Randomly predicting binary values for test set
    int predicted_value[30];
    for (int i = 0; i < 30; i++) {
        predicted_value[i] = rand() % 2;
    }
 
    // Printing predicted binary values for test set
    for (int i = 0; i < 30; i++) {
        cout << predicted_value[i] << " ";
    }
    cout << "\n";
 
    // Calculating number of 0s and 1s in train set
    int zeroes = 0;
    int ones = 0;
    for (int i = 0; i < 70; i++) {
        if (t_train[i] == 0) {
            zeroes += 1;
        }
        else {
            ones += 1;
        }
    }
 
    // Calculating Gini index
    float val = 1
                - ((zeroes / 70.0) * (zeroes / 70.0)
                   + (ones / 70.0) * (ones / 70.0));
    cout << "Gini : " << val << "\n";
 
    // Calculating accuracy of predictions
    int match = 0;
    int UnMatch = 0;
    for (int i = 0; i < 30; i++) {
        if (predicted_value[i] == t_test[i]) {
            match += 1;
        }
        else {
            UnMatch += 1;
        }
    }
    float accuracy = match / 30.0;
    cout << "Accuracy is: " << accuracy << "\n";
 
    // Returning 0 on successful completion
    return 0;
}

Strengths and Weaknesses of the Decision Tree approach 

The strengths of decision tree methods are: 

  • Decision trees are able to generate understandable rules.
  • Decision trees perform classification without requiring much computation.
  • Decision trees are able to handle both continuous and categorical variables.
  • Decision trees provide a clear indication of which fields are most important for prediction or classification.
  • Ease of use: Decision trees are simple to use and don’t require a lot of technical expertise, making them accessible to a wide range of users.
  • Scalability: Decision trees can handle large datasets and can be easily parallelized to improve processing time.
  • Missing value tolerance: Decision trees are able to handle missing values in the data, making them a suitable choice for datasets with missing or incomplete data.
  • Handling non-linear relationships: Decision trees can handle non-linear relationships between variables, making them a suitable choice for complex datasets.
  • Ability to handle imbalanced data: Decision trees can handle imbalanced datasets, where one class is heavily represented compared to the others, by weighting the importance of individual nodes based on the class distribution.

The weaknesses of decision tree methods : 

  • Decision trees are less appropriate for estimation tasks where the goal is to predict the value of a continuous attribute.
  • Decision trees are prone to errors in classification problems with many classes and a relatively small number of training examples.
  • Decision tree can be computationally expensive to train. The process of growing a decision tree is computationally expensive. At each node, each candidate splitting field must be sorted before its best split can be found. In some algorithms, combinations of fields are used and a search must be made for optimal combining weights. Pruning algorithms can also be expensive since many candidate sub-trees must be formed and compared.

In the next post, we will be discussing the ID3 algorithm for the construction of the Decision tree given by J. R. Quinlan. 

This article is contributed by Saloni Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!