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: