Build sentiment analysis from scratch with a Naive Bayes classifier without sklearn or NLTK. Train on a small hardcoded dataset of positive and negative sentences and implement Laplace smoothing for words not in the training set.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a minimal Python Naive Bayes classifier for sentiment analysis with Laplace smoothing, no external libraries, and a small hardcoded dataset.
Below is a minimal working example of a Naive Bayes sentiment classifier built from scratch in Python. It uses a small hardcoded dataset of positive and negative sentences, includes basic tokenization/cleanup, and applies Laplace smoothing so words unseen in training still receive a nonzero probability.
python
import math
import re
from collections import defaultdict, Counter
class NaiveBayesSentiment:
def __init__(self, alpha=1.0):
self.alpha = alpha
self.vocab = set()
self.class_word_counts = {'pos': Counter(), 'neg': Counter()}
self.class_doc_counts = {'pos': 0, 'neg': 0}
self.total_words_in_class = {'pos': 0, 'neg': 0}
self.class_priors = {'pos': 0.0, 'neg': 0.0}
def preprocess(self, text):
# Lowercase, remove punctuation, and split on whitespace
text = text.lower()
text = re.sub(r'[^a-z0-9\s]', '', text)
tokens = text.split()
return tokens
def fit(self, data):
"""
data is a list of (sentence, label) tuples where label is 'pos' or 'neg'.
"""
# Count documents for priors
for sentence, label in data:
self.class_doc_counts[label] += 1
tokens = self.preprocess(sentence)
self.vocab.update(tokens)
# Count words per class
self.class_word_counts[label].update(tokens)
# Compute total words in each class
self.total_words_in_class['pos'] = sum(self.class_word_counts['pos'].values())
self.total_words_in_class['neg'] = sum(self.class_word_counts['neg'].values())
# Compute class priors
total_docs = sum(self.class_doc_counts.values())
self.class_priors['pos'] = self.class_doc_counts['pos'] / total_docs
self.class_priors['neg'] = self.class_doc_counts['neg'] / total_docs
def predict(self, sentence):
tokens = self.preprocess(sentence)
vocab_size = len(self.vocab)
# Compute log-probabilities for numerical stability
log_prob_pos = math.log(self.class_priors['pos'])
log_prob_neg = math.log(self.class_priors['neg'])
for token in tokens:
# Laplace smoothing
token_count_pos = self.class_word_counts['pos'].get(token, 0)
token_count_neg = self.class_word_counts['neg'].get(token, 0)
# P(word|pos)
prob_token_pos = (token_count_pos + self.alpha) / (self.total_words_in_class['pos'] + self.alpha * vocab_size)
# P(word|neg)
prob_token_neg = (token_count_neg + self.alpha) / (self.total_words_in_class['neg'] + self.alpha * vocab_size)
# Add log probabilities
log_prob_pos += math.log(prob_token_pos)
log_prob_neg += math.log(prob_token_neg)
return 'pos' if log_prob_pos > log_prob_neg else 'neg'
if __name__ == "__main__":
# Small hardcoded dataset
training_data = [
("I love this phone, it is amazing!", "pos"),
("This movie is fantastic and exciting", "pos"),
("What a great day, I am so happy", "pos"),
("Terrible experience, I hate this", "neg"),
("This is the worst, completely awful", "neg"),
("I am disappointed and sad", "neg"),
]
# Train classifier
nb = NaiveBayesSentiment(alpha=1.0)
nb.fit(training_data)
# Test predictions
test_sentences = [
"I am so excited and happy",
"This is awful and terrible",
"What a fantastic performance",
"I hate every single thing about this"
]
for sent in test_sentences:
print(f"Sentence: {sent}")
print(f"Predicted sentiment: {nb.predict(sent)}")
print("-" * 40)
How it works:
Preprocessing: Lowercases text, removes punctuation, and splits on whitespace.
Training (fit): Counts word frequencies per class, builds vocabulary, computes total words per class, and calculates class priors.
Prediction: Uses log probabilities to avoid underflow. Each token’s conditional probability is computed with Laplace smoothing:
[
P(w \mid c) = \frac{\text{count}(w, c) + \alpha}{\text{total words in } c + \alpha \times \text{vocab size}}
]
The class with the higher log-probability is returned.