You are on page 1of 2

Name: Khemal Desai

Roll No: I008


Batch-A1

Bag of Words
Code:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

# Training data
train_data = ['This is a positive text', 'This text is negative', 'This is a neutral text']
train_labels = np.array([1, 0, 2]) # 1 for positive, 0 for negative, 2 for neutral

# Vectorize the training data using BAG of Words


vectorizer = CountVectorizer()
train_vectors = vectorizer.fit_transform(train_data)

# Train a Multinomial Naive Bayes classifier


clf = MultinomialNB()
clf.fit(train_vectors, train_labels)

# Test data
test_data = ['This is a positive test', 'This test is negative', 'This is a neutral test']

# Vectorize the test data using the same vectorizer as the training data
test_vectors = vectorizer.transform(test_data)

# Predict the labels for the test data


predicted_labels = clf.predict(test_vectors)

# Print the predicted labels for the test data


for i, predicted_label in enumerate(predicted_labels):
print(f'Test {i+1}: predicted label is {predicted_label}')

Output:

You might also like