0% found this document useful (0 votes)
11 views6 pages

Build a Decision Tree Classifier Guide

The document outlines the process of building a Decision Tree Classifier using Gini criteria with a dataset, specifically the Iris dataset. It includes code snippets for loading the dataset, training the classifier, hyperparameter tuning with GridSearchCV, and visualizing the decision tree. The conclusion emphasizes the importance of understanding Decision Tree Classifiers for creating accurate machine learning models.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Build a Decision Tree Classifier Guide

The document outlines the process of building a Decision Tree Classifier using Gini criteria with a dataset, specifically the Iris dataset. It includes code snippets for loading the dataset, training the classifier, hyperparameter tuning with GridSearchCV, and visualizing the decision tree. The conclusion emphasizes the importance of understanding Decision Tree Classifiers for creating accurate machine learning models.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Practical -15

Aim:-Write a program a Build a Decision Tree Classifier using Gini Criteria in a Dataset.

A Decision Tree Classifier is a type of supervised learning algorithm that uses a tree-like
model to classify data into different categories. The algorithm works by recursively
partitioning the data into smaller subsets based on the values of the input features. Each
internal node in the tree represents a feature or attribute, and each leaf node represents a
class label. The classification process involves traversing the tree from the root node to a leaf
node, with each node providing a decision based on the input features.

Input:-

from [Link] import load_iris

from sklearn.model_selection import train_test_split

from [Link] import DecisionTreeClassifier

from [Link] import accuracy_score

# load iris dataset

iris = load_iris()

X = [Link]

y = [Link]

# split dataset to training and test set

X_train, X_test, y_train, y_test = train_test_split(

X, y, test_size=0.3, random_state = 99)

# initialize decision tree classifier

clf = DecisionTreeClassifier(random_state=1)
# train the classifier

[Link](X_train, y_train)

# predict using classifier

y_pred = [Link](X_test)

# claculate accuracy

accuracy = accuracy_score(y_test, y_pred)

print(f'Accuracy: {accuracy}')

Output:-

Accuracy: 0.9555555555555556

Input:-

from sklearn.model_selection import GridSearchCV

# Hyperparameter to fine tune

param_grid = {

'max_depth': range(1, 10, 1),

'min_samples_leaf': range(1, 20, 2),

'min_samples_split': range(2, 20, 2),

'criterion': ["entropy", "gini"]

# Decision tree classifier

tree = DecisionTreeClassifier(random_state=1)

# GridSearchCV

grid_search = GridSearchCV(estimator=tree, param_grid=param_grid,

cv=5, verbose=True)

grid_search.fit(X_train, y_train)
# Best score and estimator

print("best accuracy", grid_search.best_score_)

print(grid_search.best_estimator_)

Output:

Fitting 5 folds for each of 1620 candidates, totalling 8100 fits


best accuracy 0.9714285714285715
DecisionTreeClassifier(criterion='entropy', max_depth=4,
min_samples_leaf=3, random_state=1)

Visualizing the Decision Tree Classifier

Input:-

from [Link] import plot_tree

import [Link] as plt

# best estimator

tree_clf = grid_search.best_estimator_

# plot

[Link](figsize=(18, 15))

plot_tree(tree_clf, filled=True, feature_names=iris.feature_names,

class_names=iris.target_names)
[Link]()

Output:-

Input:-

import pandas as pd

import [Link] as plt

# load dataset

dataset_link = '[Link]
content/uploads/20240620175612/spam_email.csv'

df = pd.read_csv(dataset_link)
# plot the category count

df['Category'].value_counts().[Link](color = ["g","r"])

[Link]('Total number of ham and spam in the dataset')

[Link]()

Input:-

import seaborn as sns

# confusion matrix

cmat = confusion_matrix(y_test, pred)


# plot heatmap

[Link](cmat, annot=True, cmap='Paired',

cbar=False, fmt="d", xticklabels=[

'Not Spam', 'Spam'], yticklabels=['Not Spam', 'Spam'])

Output:-

Conclusion:-

In this article, we have explored the world of Decision Tree Classifiers using Scikit-Learn. We
have covered the theoretical foundations, implementation, and practical applications of
Decision Tree Classifiers, providing a comprehensive guide for both beginners and
experienced practitioners. By understanding the strengths and limitations of Decision Tree
Classifiers, we can harness their power to build accurate and interpretable machine learning
models.

Common questions

Powered by AI

GridSearchCV is useful for systematically evaluating a designated parameter grid by performing cross-validation to find the optimal combination of hyperparameters, such as max_depth and criterion, enhancing the model's performance. However, its limitations include being computationally expensive as it exhaustively evaluates every combination, which may not be feasible for large datasets or complex models with many parameters .

The splitting criterion determines how the Decision Tree Classifier evaluates the quality of a split. Gini impurity measures the likelihood of an incorrect classification of a randomly chosen element if it was randomly labeled according to the distribution of labels in the subset. Entropy measures the uncertainty or impurity in the subset. The choice between them can affect model outcomes but both aim to prioritize splits that increase pureness, although their calculations and sensitivity to purity levels differ .

Overfitting occurs in decision trees when the model becomes too complex, capturing noise instead of the underlying data distribution. This results in poor generalization to new data. Mitigation techniques include pruning the tree, setting a maximum depth, adjusting minimum samples per leaf, or using ensemble methods (like Random Forests) for more robust models. Hyperparameter tuning is also a practical approach to finding an optimal balance .

To handle class imbalance in a Decision Tree model, improvements can include using techniques like SMOTE (Synthetic Minority Over-sampling Technique) to balance the classes, adjusting class weights to penalize misclassifying minority classes, and employing ensemble techniques like Balanced Random Forests. Additionally, using metrics such as F1-score and ROC-AUC rather than accuracy provides a more comprehensive evaluation of performance, particularly in imbalanced datasets .

Decision Tree Classifiers are advantageous in practical applications due to their interpretability, as they can be easily visualized and understood. They handle both numerical and categorical data, require little data preprocessing, and can model complex decision boundaries. However, compared to other methods, they are prone to overfitting without careful tuning, although ensemble methods like Random Forests can alleviate this issue .

A Decision Tree Classifier determines which feature to split on by evaluating the impurity of the dataset using criteria such as Gini impurity or entropy. It chooses the feature that results in the greatest reduction in impurity after the split, leading to a purer subset of data. This process is repeated recursively to build a tree model .

Visualizing a Decision Tree using a tool such as plot_tree in Matplotlib helps clarify the decision-making process by mapping out each decision node and possible outcomes visually. It shows which features lead to specific decisions and how input data is partitioned, making the tree interpretable and the model's logic transparent, assisting users in understanding the predictive factors and relationships .

The train-test split is crucial as it separates the data into training and testing sets, preserving the integrity of the model evaluation by ensuring testing on unseen data. A common split is 70-30, with 70% data used for training and 30% for testing. This division allows for evaluating the model’s ability to generalize, thus helping assess performance through metrics like accuracy, which was reported as 95.6% with given splits .

Hyperparameter tuning significantly impacts the performance of a Decision Tree Classifier by optimizing parameters such as max_depth, min_samples_leaf, min_samples_split, and splitting criterion (e.g., entropy or Gini). Proper tuning, which can be performed using techniques like GridSearchCV, helps to achieve better accuracy and avoid overfitting, as demonstrated by improving the classifier accuracy to 0.9714285714285715 using the best parameters .

The choice of dataset splitting and cross-validation strategy profoundly impacts the robustness of a Decision Tree model’s evaluation. A balanced train-test split ensures sufficient data for training and unbiased testing. Cross-validation, such as k-fold, divides the dataset into multiple parts, training on some while validating on another, leading to a more reliable performance estimate. This helps mitigate overfitting by exposing the model to varied data permutations, although it increases computational load .

You might also like