-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path5_decision tree for species classification.py
More file actions
51 lines (41 loc) · 1.44 KB
/
5_decision tree for species classification.py
File metadata and controls
51 lines (41 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Develop a decision tree model to classify species in the Iris dataset.
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.metrics import classification_report, accuracy_score
import matplotlib.pyplot as plt
# Load the dataset
dataset_path = r"C:\Users\KIIT\Desktop\Lab Experiment\AD Lab\IRIS (week 1,5).csv"
df = pd.read_csv(dataset_path)
print("Dataset:")
print(df.head())
X = df.iloc[:, :-1]
y = df.iloc[:, -1]
# Split features (X) and labels (y)
X = df[['sepal_length', 'sepal_width', 'petal_length', 'petal_width']]
y = df['species']
# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.35, random_state=42)
# Decision Tree
dt_model = DecisionTreeClassifier(random_state=42)
dt_model.fit(X_train, y_train)
y_pred = dt_model.predict(X_test)
# Accuracy
accuracy = accuracy_score(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.2f}")
# Classification Report
print("\nClassification Report:")
print(classification_report(y_test, y_pred))
# Visualization
plt.figure(figsize=(15, 10))
plot_tree(
dt_model,
feature_names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'],
class_names=dt_model.classes_,
filled=True,
rounded=True,
fontsize=12,
)
plt.title("Decision Tree:", fontsize=12)
plt.tight_layout()
plt.show()