Write a program to implement the naïve Bayesian classifier for a sample training data set stored as a CSV file. Compute the accuracy of the classifier, considering few test data sets.
We can use a simple Weather → Play Tennis dataset. The program will:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
import csv
data = [
["Outlook", "Temperature", "Humidity", "Windy", "Play"],
["Sunny", "Hot", "High", "False", "No"],
["Sunny", "Hot", "High", "True", "No"],
["Overcast", "Hot", "High", "False", "Yes"],
["Rain", "Mild", "High", "False", "Yes"],
["Rain", "Cool", "Normal", "False", "Yes"],
["Rain", "Cool", "Normal", "True", "No"],
["Overcast", "Cool", "Normal", "True", "Yes"],
["Sunny", "Mild", "High", "False", "No"],
["Sunny", "Cool", "Normal", "False", "Yes"],
["Rain", "Mild", "Normal", "False", "Yes"],
["Sunny", "Mild", "Normal", "True", "Yes"],
["Overcast", "Mild", "High", "True", "Yes"],
["Overcast", "Hot", "Normal", "False", "Yes"],
["Rain", "Mild", "High", "True", "No"]
]
with open("weather.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("weather.csv created successfully!")
df = pd.read_csv("weather.csv")
print(df)
Our dataset has four input attributes:
and one output: Play
X_features = df.drop("Play", axis=1)
y_target = df["Play"]
X_features contains the input features:
y_target contains the target/output:
Play
So:
X_features → Features/Input
y_target → Target/Output
Naïve Bayes in this example needs numerical input.
We need to convert these categories into numbers.
label_encoders = {}
for column in X_features.columns:
le = LabelEncoder()
X_features[column] = le.fit_transform(X_features[column])
label_encoders[column] = le
label_encoder_y = LabelEncoder()
y_target = label_encoder_y.fit_transform(y_target)
print("Features")
print(X_features)
print("target")
print(y_target)
No → 0
Yes → 1
NOTE: LabelEncoder is simply assigning a number to each category.
For example:
Sunny → 2
Overcast → 0
Rain → 1
The exact numbers are not important; they are simply numerical representations of the categories.
X_train, X_test, y_train, y_test = train_test_split(
X_features,
y_target,
test_size=0.30,
random_state=42
)
# 30% → Testing data
# 70% → Training data
The classifier needs to learn from one set of records and then be tested on records that it did not use for learning.
We can create a Naïve Bayes classifier using GaussianNB.
GaussianNB is the Gaussian Naïve Bayes implementation available in scikit-learn.
model = GaussianNB()
This is the most important step.
The classifier examines the training data and learns the relationship between:
Features → Class
For example:
Sunny + Hot + High + False → No
Rain + Mild + Normal + False → Yes
model.fit(X_train, y_train)
Now give the classifier the testing data:
y_pred = model.predict(X_test)
print(y_test)
print(y_pred)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
print("Accuracy percentage:", accuracy * 100, "%")
cm = confusion_matrix(
y_test,
y_pred
)
print(cm)
| Predicted: No | Predicted: Yes | |
|---|---|---|
| Actual: No | 1 (True Negative - TN) | 1 (False Positive - FP) |
| Actual: Yes | 1 (False Negative - FN) | 2 (True Positive - TP) |
new_data = pd.DataFrame({
"Outlook": ["Sunny", "Rain", "Overcast"],
"Temperature": ["Cool", "Mild", "Hot"],
"Humidity": ["High", "Normal", "High"],
"Windy": [False, False, False]
})
print("\nNew Test Data:")
print(new_data)
# --------------------------------------------------
# 10. Encode NEW test data
# --------------------------------------------------
new_data_encoded = new_data.copy()
for column in new_data_encoded.columns:
new_data_encoded[column] = label_encoders[column].transform(
new_data_encoded[column]
)
print("\nEncoded New Test Data:")
print(new_data_encoded)
# --------------------------------------------------
# Predict new data
# --------------------------------------------------
predictions = model.predict(new_data_encoded)
# --------------------------------------------------
# Convert 0/1 back to Yes/No
# --------------------------------------------------
predicted_classes = label_encoder_y.inverse_transform(predictions)
print("\nPredictions:")
for i in range(len(predicted_classes)):
print(
new_data.iloc[i].to_dict(),
"=>",
predicted_classes[i]
)
accuracy_score(actual_classes, predicted_classes)
This is possible only when you know the actual class labels for those new records.
If you don't know the actual answers, you can show the predictions, but you cannot calculate accuracy.
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
cm = confusion_matrix(y_test, y_pred)
print(cm)