Practical 09 - Text Classification with Scikit-Learn
Program to classify the product review into positive and negative.
# Program to classify the product review into positive, negative 
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
# Sample text data and labels
documents = [
    "This is a positive review.",
    "Great product, highly recommend.",
    "Terrible experience, very disappointed.",
    "Not satisfied with the service.",
    "Excellent quality and fast delivery."
]
labels = ["positive", "positive", "negative", "negative", "positive"]
# Convert text to numerical features (word counts)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)
# Create and train the MultinomialNB model
model = MultinomialNB()
model.fit(X, labels)
# Predict the class of a new document
new_document = ["This product is amazing!",
                "I am very disappointed with this movie."]
new_X = vectorizer.transform(new_document)
prediction = model.predict(new_X)
print(f"The new document is classified as: {prediction}")
Output:-
Program to classify the email as SPAM and HAM (NOT SPAM)
##simple use of scikit learn for for text classification (spam vs ham)
##Spam unwanted, promotional, scammy, or junk messages.
##Ham the opposite of spam normal, legitimate, non-spam messages.
# Import libraries
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# Example dataset
texts = [
    "Win a free iPhone now",                # spam
    "Lowest prices, buy now!!!",            # spam
    "Hi, how are you?",                     # ham
    "Are we meeting tomorrow?",             # ham
    "Get cheap loans instantly",            # spam
    "Happy birthday my friend"              # ham
]
labels = ["spam", "spam", "ham", "ham", "spam", "ham"]
# Convert text -> numbers (Bag of Words)
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(texts)
# Train a Naive Bayes classifier
model = MultinomialNB()
model.fit(X, labels)
# Test with new examples
test_texts = ["congratualtions!! you won a prize",
              "Let's go for lunch today"]
X_test = vectorizer.transform(test_texts)
predictions = model.predict(X_test)
print("Predictions:", predictions)
Output:-