๐Ÿค–
B.TECH III YEAR โ€ข I SEMESTER โ€ข R22

Machine Learning - Lab Manual

Machine Learning Laboratory โ€ข Program Solution

๐Ÿ“˜ R22 Regulation ๐ŸŽ“ III Year ๐Ÿ“š I Semester ๐Ÿค– Machine Learning ๐Ÿงช Lab Program
Selected Program

Implementation of Decision tree using sklearn and its parameter tuning

โ† All Machine Learning Programs

Solution :


A Decision Tree is a supervised machine learning algorithm used for classification and regression tasks. It builds a tree-like model of decisions based on features of the data, splitting nodes based on conditions that maximize information gain or minimize impurity. Decision Trees are interpretable and useful for understanding the structure of data.

Dataset Overview

The Iris dataset is a well-known dataset in machine learning, containing 150 samples from three species of Iris flowers: setosa, versicolor, and virginica. Each sample has four features: sepal length, sepal width, petal length, and petal width.

Steps :

1. Importing Required Libraries:

2. Loading the Iris Dataset

3. Splitting the Dataset

4. Defining a Parameter Grid for Tuning

5. Initializing the Decision Tree Classifier

6. Performing Grid Search for Parameter Tuning

7. Getting the Best Model

8. Fitting the Best Classifier on Training Data

9. Making Predictions on the Test Set

10. Calculating Accuracy

11. Printing Classification Report

12. Visualizing the Best Decision Tree


Library Installation:

To install required library files, Open Command Prompt or Terminal and execute the following commands


$ pip install scikit-learn

$ pip install matplotlib


Source Code:

File Name: Dtree.py


# Importing required libraries
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report
import matplotlib.pyplot as plt
from sklearn import tree

# Load the Iris dataset
iris = load_iris()
X = iris.data # Features
y = iris.target # Target labels

# Split the dataset into training and testing sets (90% train, 10% test)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) # 10% test size

# Initialize the Decision Tree classifier with some tuning parameters
clf = DecisionTreeClassifier(max_depth=2, min_samples_split=2, min_samples_leaf=1, random_state=42)

# Fit the classifier on the training data
clf.fit(X_train, y_train)

# Make predictions on the test set
y_pred = clf.predict(X_test)

# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f'Accuracy: {accuracy:.2f}')

# Print classification report
print('Classification Report:')
print(classification_report(y_test, y_pred, target_names=iris.target_names))

# Visualize the Decision Tree
plt.figure(figsize=(10, 8))
tree.plot_tree(clf, filled=True, feature_names=iris.feature_names,class_names=iris.target_names, rounded=True)
plt.title("Decision Tree Visualization")
plt.show()

Output:


Sample Run:
--------------
$ python3 Dtree.py
Accuracy: 1.00
Classification Report:
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00         6
  versicolor       1.00      1.00      1.00         6
   virginica       1.00      1.00      1.00         3

    accuracy                           1.00        15
   macro avg       1.00      1.00      1.00        15
weighted avg       1.00      1.00      1.00        15


 

๐Ÿ’ป Run This Python Program

Implementation of Decision tree using sklearn and its parameter tuning
The selected Python program is loaded automatically into the editor. Edit the program, provide input if required and click Run.

The compiler is embedded using OneCompiler. Your Python program runs inside the embedded Python environment; Study Glance does not execute Python code directly on your web server. Machine Learning programs use libraries such as NumPy, Pandas, Matplotlib and scikit-learn, and graph windows (plt.show) cannot be displayed here. If a library is not available in the embedded compiler, use Copy Program and run the program on your computer (after pip install of the libraries) or in Google Colab.
โ† Back to Machine Learning Lab Programs ๐Ÿ“š All Lab Manuals