# -*- coding: utf-8 -*-
"""P8-2 Naive Bayes Document Classifier.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1R4hGEod7Xzfmett09KGokYk375k1xX5W
"""

import pandas as pd

msg=pd.read_excel('/content/naivetext.xlsx')
msg

print('The dimensions of the dataset',msg.shape)

msg['labelnum']=msg.label.map({'pos':1,'neg':0})
X=msg.message
y=msg.labelnum
print(X)
print(y)

#splitting the dataset into train and test data
from sklearn.model_selection import train_test_split
xtrain,xtest,ytrain,ytest=train_test_split(X,y)

print ('\n The total number of Training Data :',ytrain.shape)

print ('\n The total number of Test Data :',ytest.shape)

#output of count vectoriser is a sparse matrix

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
xtrain_dtm = count_vect.fit_transform(xtrain)
xtest_dtm=count_vect.transform(xtest)
print('\n The words or Tokens in the text documents \n',count_vect.get_feature_names_out())

df = pd.DataFrame(xtrain_dtm.toarray(), columns=count_vect.get_feature_names_out())

# Training Naive Bayes (NB) classifier on training data
from sklearn.naive_bayes import MultinomialNB

clf = MultinomialNB().fit(xtrain_dtm,ytrain)
predicted = clf.predict(xtest_dtm)

#printing accuracy, Confusion matrix, Precision and Recall
from sklearn import metrics
print('\n Accuracy of the classifer is ', metrics.accuracy_score(ytest,predicted))

#Checking the prediction made
print(xtest)
print(predicted)

print('\n Confusion matrix\n', metrics.confusion_matrix(ytest,predicted))
print('\n The value of Recall' ,
metrics.recall_score(ytest,predicted))

# Simple Naive Bayes Text Classifier



# my code+++++++++++++++++++
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn import metrics

# Load dataset
data = pd.read_excel("/content/naivetext.xlsx")
print("Dataset Loaded Successfully!")
print("Shape of Dataset:", data.shape)

# Convert labels to numbers (pos = 1, neg = 0)
data['labelnum'] = data['label'].map({'pos': 1, 'neg': 0})

# Split input (X) and output (y)
X = data['message']
y = data['labelnum']

# Split data into training and testing
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
print("\nTraining Samples:", len(x_train))
print("Testing Samples:", len(x_test))

# Convert text into numeric features
vectorizer = CountVectorizer()
x_train_dtm = vectorizer.fit_transform(x_train)
x_test_dtm = vectorizer.transform(x_test)

print("\nWords (Tokens):")
print(vectorizer.get_feature_names_out())

# Train Naive Bayes model
model = MultinomialNB()
model.fit(x_train_dtm, y_train)

# Predict on test data
y_pred = model.predict(x_test_dtm)

# Show results
print("\nAccuracy:", metrics.accuracy_score(y_test, y_pred))
print("\nConfusion Matrix:\n", metrics.confusion_matrix(y_test, y_pred))
print("\nRecall:", metrics.recall_score(y_test, y_pred))

# Check few predictions
print("\nSample Predictions:")
for msg, pred in zip(x_test[:5], y_pred[:5]):
    print(f"Message: {msg} --> Predicted Label: {'pos' if pred == 1 else 'neg'}")

