Loading, please wait...
🚀 Now Available on Google Play

VTU Circle

Your complete VTU student companion. Check VTU results, track SGPA & CGPA, access study resources, stay updated with VTU notifications, and connect with classmates—all in one simple and fast app.

📊 VTU Results 🎯 SGPA & CGPA 📄 Result PDF 📈 Analytics 📚 Notes 📖 Syllabus 📝 Question Papers 🛠 Study Tools 🔔 VTU Updates 🏆 Rankings 👥 Classmates 💬 Chat
Download on Google Play

BAIL606 Program 8

8. Develop a program to implement the Naive Bayesian classifier considering Iris dataset for training. Compute the accuracy of the classifier, considering the test data.

PROGRAM:

# install required packages
#pip install numpy scikit-learn

import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix

# ==============================
# 1. Load Iris Dataset
# ==============================
iris = load_iris()

X = iris.data
y = iris.target

print("Feature Names:")
print(iris.feature_names)

print("\nTarget Names:")
print(iris.target_names)

# ==============================
# 2. Train-Test Split
# ==============================
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.3,
    random_state=42,
    stratify=y
)

# ==============================
# 3. Train Naive Bayes Model
# ==============================
model = GaussianNB()
model.fit(X_train, y_train)

# ==============================
# 4. Prediction
# ==============================
y_pred = model.predict(X_test)

# ==============================
# 5. Evaluation
# ==============================
accuracy = accuracy_score(y_test, y_pred)

print("\n--- Naive Bayes Results ---")
print("Accuracy:", accuracy)

print("\nClassification Report:")
print(classification_report(y_test, y_pred, target_names=iris.target_names))

print("\nConfusion Matrix:")
print(confusion_matrix(y_test, y_pred))

OUTPUT:

Feature Names:
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)']

Target Names:
['setosa' 'versicolor' 'virginica']

--- Naive Bayes Results ---
Accuracy: 0.9111111111111111

Classification Report:
              precision    recall  f1-score   support

      setosa       1.00      1.00      1.00        15
  versicolor       0.82      0.93      0.88        15
   virginica       0.92      0.80      0.86        15

    accuracy                           0.91        45
   macro avg       0.92      0.91      0.91        45
weighted avg       0.92      0.91      0.91        45


Confusion Matrix:
[[15  0  0]
 [ 0 14  1]
 [ 0  3 12]]
Syllabus Papers
SGPA CGPA