0% found this document useful (0 votes)
0 views

Decision Tree

The document outlines a Python implementation of a Decision Tree Classifier using the Iris dataset. It includes steps for loading the dataset, splitting it into training and testing sets, training the classifier, making predictions, and calculating accuracy. Additionally, it provides a visualization of the trained decision tree.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Decision Tree

The document outlines a Python implementation of a Decision Tree Classifier using the Iris dataset. It includes steps for loading the dataset, splitting it into training and testing sets, training the classifier, making predictions, and calculating accuracy. Additionally, it provides a visualization of the trained decision tree.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

Decision Tree:

# Import necessary libraries


from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt

# Load the Iris dataset


iris = load_iris()
X = iris.data # Features (sepal and petal lengths & widths)
y = iris.target # Target labels (setosa, versicolor, virginica)

# Split the dataset into training and testing sets


X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42)

# Initialize the Decision Tree Classifier


clf = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=42)

# Train the classifier on the training data


clf.fit(X_train, y_train)

# Make predictions on the test data


y_pred = clf.predict(X_test)

# Calculate and print the accuracy


accuracy = accuracy_score(y_test, y_pred)
print("Decision Tree Accuracy:", accuracy)

# Visualize the decision tree


plt.figure(figsize=(12, 8))
plot_tree(clf, filled=True,
feature_names=iris.feature_names,
class_names=iris.target_names,
rounded=True)
plt.title("Decision Tree Trained on Iris Dataset")
plt.show()

Output:

You might also like