# Q23. Compare Random Forest and Decision Tree

# Step 1: Import Libraries
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import precision_score, recall_score, f1_score, accuracy_score
from sklearn.preprocessing import LabelEncoder

# Step 2: Load Dataset
df = pd.read_csv("Iris.csv")
print("First Five Records:")
print(df.head())

# Step 3: Preprocess the Data
if "Id" in df.columns:
    df = df.drop("Id", axis=1)

X = df.drop("Species", axis=1)
y = df["Species"]

# Convert target labels into numbers if required
encoder = LabelEncoder()
y = encoder.fit_transform(y)

# Step 4: Split Dataset
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42, stratify=y
)

# Step 5: Train Decision Tree
dt_model = DecisionTreeClassifier(random_state=42)
dt_model.fit(X_train, y_train)
dt_pred = dt_model.predict(X_test)

# Step 6: Train Random Forest
rf_model = RandomForestClassifier(n_estimators=100, random_state=42)
rf_model.fit(X_train, y_train)
rf_pred = rf_model.predict(X_test)

# Step 7: Evaluate and Compare Models
for name, pred in [
    ("Decision Tree", dt_pred),
    ("Random Forest", rf_pred)
]:
    print("\n", name)
    print("Accuracy:", accuracy_score(y_test, pred))
    print("Precision:", precision_score(
        y_test, pred, average="weighted", zero_division=0
    ))
    print("Recall:", recall_score(
        y_test, pred, average="weighted", zero_division=0
    ))
    print("F1-Score:", f1_score(
        y_test, pred, average="weighted", zero_division=0
    ))

# Step 8: Conclusion
print("\nBoth models have been evaluated on the same test data.")


