Skip to main content
JustPaste
HomeAboutDonateContactTerms of UsePrivacy Policy

© 2026 Just Paste. All rights reserved.

Made with ❤️ by TakiDev

Untitled Page | JustPaste.app
Publish 6 months ago146 views

import pandas as pd

from sklearn.model_selection import train_test_split

from sklearn.tree import DecisionTreeClassifier, plot_tree

from sklearn.metrics import accuracy_score

import matplotlib.pyplot as plt

# Step 1: Load iris.csv

data = pd.read_csv('iris.csv')

# Step 2: Prepare features and target

X = data.iloc[:, :-1] # all columns except last one

y = data.iloc[:, -1] # last column (species)

# Step 3: Split into train and test sets

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

# Step 4: Create and train Decision Tree Classifier

clf = DecisionTreeClassifier(criterion='entropy', max_depth=3)

clf.fit(X_train, y_train)

# Step 5: Predict on test data

y_pred = clf.predict(X_test)

# Step 6: Accuracy

accuracy = accuracy_score(y_test, y_pred)

print(f"Accuracy on test data: {accuracy*100:.2f}%")

# Step 7: Visualize the tree

plt.figure(figsize=(12,8))

plot_tree(clf, filled=True, feature_names=X.columns, class_names=clf.classes_, rounded=True)

plt.show()