# import necessary libraries
import pandas as pd
from sklearn.datasets import load_iris
# load the iris dataset
iris = load_iris()
# convert the data to a Pandas dataframe
df = pd.DataFrame(iris.data, columns=iris.feature_names)
# add the target column to the dataframe
df['target'] = iris.target
# view the dataset
print(df.sample(5))
# import train_test_split
from sklearn.model_selection import train_test_split
# split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
iris.data,
iris.target,
test_size = 0.2,
random_state = 42)
# import necessary libraries
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeClassifier, plot_tree
# create a decision tree classifier
model = DecisionTreeClassifier(random_state=42)
# train the classifier on the training data
model.fit(X_train, y_train)
# calculate the accuracy of the model on the testing data
accuracy = model.score(X_test, y_test)
print("Accuracy on testing data:", accuracy)
# plot the decision tree
plt.figure(figsize=(20,10))
plot = plot_tree(model, filled=True, rounded=True, fontsize=14)
plt.show()