medium.com 5 min read Original Source

How To Build a Sentiment Analysis Model from Scratch Using Python

Let’s be real! computers don’t have feelings, neither do they care about your heartbreak, your joy, or your late night dramatic tweets. So why would you expect them to respect your emotions? And yet, ironically these cold, feelingless machines manage to analyse sentiments — deciding whether that brutally honest movie review or that you guessed it “social media” rant is positive, negative, or just plain useless.

Interested in how do they do it?

In this article, let’s pull out our python toolkit and build a sentiment analysis model using Natural Language Toolkit (NLTK). By the end, i can promise that you’ll have a model that will judge you, i mean your text with precision and, more importantly, understanding of how these heartless machines pretend to “feel.”

Let’s teach our computers some fake empathy, shall we?

What We’ll Build

A sentiment analyzer that can:

  • Process movie reviews and classify them as positive or negative
  • Achieve reasonable accuracy using simple but powerful techniques
  • Make predictions on new, unseen text
  • Provide insights through detailed performance metrics

Prerequisites

Make sure you have Python installed along with these libraries:

#!pip install nltk
#!pip install matplotlib
#!pip install nltk
#!pip install matplotlib

Understanding the Data

We’ll use NLTK’s built-in Movie Reviews dataset, which contains thousands of movie reviews already labeled as positive or negative. This real world dataset will help us build a practical model that can handle actual user reviews.

1. Setting Up Our Environment

First, import the necessary libraries and download the resources. Don’t worry about the SSL context setup , it’s just there to ensure smooth downloads.

import nltk
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy as nltk_accuracy
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
import nltk
from nltk.corpus import movie_reviews
from nltk.classify import NaiveBayesClassifier
from nltk.classify.util import accuracy as nltk_accuracy
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
import ssl
ssl._create_default_https_context = ssl._create_unverified_context

2. Loading and Preparing the Data

Our dataset needs to be balanced and properly shuffled to ensure our model learns from both positive and negative examples equally. We’ll combine reviews from both categories and mix them up:

nltk.download('movie_reviews')
nltk.download('punkt')
nltk.download('stopwords')

positive_reviews = [(list(movie_reviews.words(fileids=[f])), 'pos') for f in movie_reviews.fileids('pos')]
negative_reviews = [(list(movie_reviews.words(fileids=[f])), 'neg') for f in movie_reviews.fileids('neg')]

# Combine positive and negative reviews
reviews = positive_reviews + negative_reviews

# Shuffle the reviews
import random
random.shuffle(reviews)
nltk.download('movie_reviews')
nltk.download('punkt')
nltk.download('stopwords')

positive_reviews = [(list(movie_reviews.words(fileids=[f])), 'pos') for f in movie_reviews.fileids('pos')]
negative_reviews = [(list(movie_reviews.words(fileids=[f])), 'neg') for f in movie_reviews.fileids('neg')]

# Combine positive and negative reviews
reviews = positive_reviews + negative_reviews

# Shuffle the reviews
import random
random.shuffle(reviews)

3. Feature Engineering

This is where the magic happens. We’ll transform our text data into a format that our machine learning model can understand. We use a technique called “bag-of-words” which, despite its simplicity, is surprisingly effective:

def extract_features(words):
    return dict([(word, True) for word in words])
def extract_features(words):
    return dict([(word, True) for word in words])

4. Data Preprocessing

Raw text data is messy. We need to clean it up by:

  • Removing stopwords (common words like “the”, “is”, “at”)
  • Converting everything to lowercase
  • Focusing only on alphabetic words

This helps our model focus on the words that matter most for sentiment:

# Define a function to preprocess the data
def preprocess_data(reviews):
    stop_words = set(stopwords.words('english'))
    processed_reviews = []

    for words, sentiment in reviews:
        # Remove stopwords and convert to lowercase
        words = [word.lower() for word in words if word.isalpha() and word.lower() not in stop_words]
        processed_reviews.append((words, sentiment))

    return processed_reviews

# Preprocess the data
processed_reviews = preprocess_data(reviews)

# Split the data into training and testing sets
split_ratio = 0.8
split = int(len(processed_reviews) * split_ratio)
train_data, test_data = processed_reviews[:split], processed_reviews[split:]
# Define a function to preprocess the data
def preprocess_data(reviews):
    stop_words = set(stopwords.words('english'))
    processed_reviews = []

    for words, sentiment in reviews:
        # Remove stopwords and convert to lowercase
        words = [word.lower() for word in words if word.isalpha() and word.lower() not in stop_words]
        processed_reviews.append((words, sentiment))

    return processed_reviews

# Preprocess the data
processed_reviews = preprocess_data(reviews)

# Split the data into training and testing sets
split_ratio = 0.8
split = int(len(processed_reviews) * split_ratio)
train_data, test_data = processed_reviews[:split], processed_reviews[split:]

5. Training Our Model

Now comes the exciting part, training our Naive Bayes Classifier. This algorithm is perfect for text classification because it’s:

  • Fast to train
  • Effective with natural language
  • Good at handling multiple classes

# Extract features from the training data
training_features = [(extract_features(words), sentiment) for words, sentiment in train_data]

# Train the Naive Bayes Classifier
classifier = NaiveBayesClassifier.train(training_features)
# Extract features from the training data
training_features = [(extract_features(words), sentiment) for words, sentiment in train_data]

# Train the Naive Bayes Classifier
classifier = NaiveBayesClassifier.train(training_features)

6. Evaluating Performance

A model is only as good as its metrics show. We’ll look at several key performance indicators:

  • Accuracy: How often is our model correct?
  • Precision: When it predicts positive, how often is it right?
  • Recall: How many actual positive reviews does it catch?
  • F1 Score: The balanced measure between precision and recall

# Test the classifier on the testing data
test_features = [(extract_features(words), sentiment) for words, sentiment in test_data]
accuracy = nltk_accuracy(classifier, test_features)

print(f'Accuracy: {accuracy:.2%}')
Accuracy: 68.50%
# Test the classifier on the testing data
test_features = [(extract_features(words), sentiment) for words, sentiment in test_data]
accuracy = nltk_accuracy(classifier, test_features)

print(f'Accuracy: {accuracy:.2%}')
Accuracy: 68.50%

Bonus Step:

  • The accuracy of 68.50% suggests that the classifier is correctly predicting the sentiment for approximately 68.50% of the test examples. While accuracy is a common metric for evaluating classifiers, it may not provide a complete picture, especially in the case of imbalanced datasets.
  • If the dataset contains significantly more positive or negative examples, the classifier might become biased towards the majority class, and accuracy alone may not be sufficient. In such cases, it’s beneficial to consider additional metrics like precision, recall, and F1 score, especially in sentiment analysis where achieving a balance between positive and negative predictions is crucial.
  • Let’s calculate these metrics using the confusion matrix, which provides a detailed breakdown of true positives, true negatives, false positives, and false negatives. Here’s a modified version of the code to display the confusion matrix and these metrics:

<button data-code="from nltk.metrics import ConfusionMatrix

# Test the classifier on the testing data
test_features = [(extract_features(words), sentiment) for words, sentiment in test_data]
test_labels = [sentiment for _, sentiment in test_data]

# Get predictions
predicted_labels = [classifier.classify(features) for features, _ in test_features]

# Calculate and print confusion matrix
cm = ConfusionMatrix(test_labels, predicted_labels)
print("Confusion Matrix:")
print(cm)

# Calculate and print additional metrics
precision = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['neg', 'pos'])
recall = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['pos', 'neg'])
f1_score = 2 * (precision * recall) / (precision + recall)

print(f'Precision: {precision:.2%}')
print(f'Recall: {recall:.2%}')
print(f'F1 Score: {f1_score:.2%}')
Confusion Matrix:
| n p |
| e o |
| g s |
—-+———+
neg | 122 |
pos | 4|
—-+———+
(row = reference; col = test)

Precision: 61.88%
Recall: 98.02%
F1 Score: 75.86%” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

from nltk.metrics import ConfusionMatrix

# Test the classifier on the testing data
test_features = [(extract_features(words), sentiment) for words, sentiment in test_data]
test_labels = [sentiment for _, sentiment in test_data]

# Get predictions
predicted_labels = [classifier.classify(features) for features, _ in test_features]

# Calculate and print confusion matrix
cm = ConfusionMatrix(test_labels, predicted_labels)
print("Confusion Matrix:")
print(cm)

# Calculate and print additional metrics
precision = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['neg', 'pos'])
recall = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['pos', 'neg'])
f1_score = 2 * (precision * recall) / (precision + recall)

print(f'Precision: {precision:.2%}')
print(f'Recall: {recall:.2%}')
print(f'F1 Score: {f1_score:.2%}')
Confusion Matrix:
    |   n   p |
    |   e   o |
    |   g   s |
----+---------+
neg | <76>122 |
pos |   4<198>|
----+---------+
(row = reference; col = test)

Precision: 61.88%
Recall: 98.02%
F1 Score: 75.86%
from nltk.metrics import ConfusionMatrix

# Test the classifier on the testing data
test_features = [(extract_features(words), sentiment) for words, sentiment in test_data]
test_labels = [sentiment for _, sentiment in test_data]

# Get predictions
predicted_labels = [classifier.classify(features) for features, _ in test_features]

# Calculate and print confusion matrix
cm = ConfusionMatrix(test_labels, predicted_labels)
print("Confusion Matrix:")
print(cm)

# Calculate and print additional metrics
precision = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['neg', 'pos'])
recall = cm['pos', 'pos'] / (cm['pos', 'pos'] + cm['pos', 'neg'])
f1_score = 2 * (precision * recall) / (precision + recall)

print(f'Precision: {precision:.2%}')
print(f'Recall: {recall:.2%}')
print(f'F1 Score: {f1_score:.2%}')
Confusion Matrix:
    |   n   p |
    |   e   o |
    |   g   s |
----+---------+
neg | <76>122 |
pos |   4<198>|
----+---------+
(row = reference; col = test)

Precision: 61.88%
Recall: 98.02%
F1 Score: 75.86%

Metrics

  • Precision: 61.88% (TP / (TP + FP))
  • Measures how many predicted positive instances are actually positive.
  • Recall (Sensitivity): 98.02% (TP / (TP + FN))
  • Measures how well the model identifies actual positives.
  • F1 Score: 75.86%
  • The harmonic mean of precision and recall, balancing both metrics.

Interpretation

  • The classifier achieves high recall (98.02%), meaning it correctly identifies most positive sentiments.
  • However, precision is lower (61.88%), indicating a notable number of false positives.
  • The F1 score (75.86%) reflects a trade-off between precision and recall.

If your goal is to reduce false positives, you may need to adjust the model or consider a different approach to improve precision.

Note : The more data you provide, the more accurate your model will generally become — but this is not always the case. Data quality, feature selection, and model choice also play a crucial role in performance.

Making It Real: Testing Our Model

Let’s put our model to the test with some real-world examples:

# Examples without labels
examples = [
    "This movie is fantastic! I loved every moment of it.",
    "The cinematography and acting were outstanding. A must-watch!",
    "The plot was confusing, and the characters were poorly developed.",
    "I regret watching this movie. It was a waste of time.",
    "I regret watching this. It was a waste of money."
]

# Function to predict sentiment
def predict_sentiment(text):
    words = word_tokenize(text)
    features = extract_features(words)
    sentiment = classifier.classify(features)
    return sentiment

# Make predictions and display results
predictions = []
for example in examples:
    prediction = predict_sentiment(example)
    predictions.append(prediction)
    print(f'Example Prediction: {prediction}')
Example Prediction: pos
Example Prediction: pos
Example Prediction: neg
Example Prediction: neg
Example Prediction: neg
# Examples without labels
examples = [
    "This movie is fantastic! I loved every moment of it.",
    "The cinematography and acting were outstanding. A must-watch!",
    "The plot was confusing, and the characters were poorly developed.",
    "I regret watching this movie. It was a waste of time.",
    "I regret watching this. It was a waste of money."
]

# Function to predict sentiment
def predict_sentiment(text):
    words = word_tokenize(text)
    features = extract_features(words)
    sentiment = classifier.classify(features)
    return sentiment

# Make predictions and display results
predictions = []
for example in examples:
    prediction = predict_sentiment(example)
    predictions.append(prediction)
    print(f'Example Prediction: {prediction}')
Example Prediction: pos
Example Prediction: pos
Example Prediction: neg
Example Prediction: neg
Example Prediction: neg

Visualising Our Results

A picture is worth a thousand words. Let’s create a visual representation of our model’s predictions:

import matplotlib.pyplot as plt

# Visualize sentiment distribution
sentiment_counts = {'pos': 0, 'neg': 0}
for prediction in predictions:
    sentiment_counts[prediction] += 1

labels = list(sentiment_counts.keys())
counts = list(sentiment_counts.values())

plt.bar(labels, counts, color=['green', 'red'])
plt.xlabel('Sentiment')
plt.ylabel('Count')
plt.title('Predicted Sentiment Distribution for Examples')
plt.show()
import matplotlib.pyplot as plt

# Visualize sentiment distribution
sentiment_counts = {'pos': 0, 'neg': 0}
for prediction in predictions:
    sentiment_counts[prediction] += 1

labels = list(sentiment_counts.keys())
counts = list(sentiment_counts.values())

plt.bar(labels, counts, color=['green', 'red'])
plt.xlabel('Sentiment')
plt.ylabel('Count')
plt.title('Predicted Sentiment Distribution for Examples')
plt.show()

Key Takeaways

Our sentiment analysis model achieved a 68.50% accuracy rate, which is quite respectable for a straightforward implementation. The high recall (98.02%) shows it’s particularly good at identifying positive reviews, though the lower precision (61.88%) suggests it sometimes sees positivity where there isn’t any.

Where to Go From Here

Here are some suggestions for further improvement:

  • Experiment with different feature extraction methods
  • Try more advanced preprocessing techniques
  • Use deep learning approaches
  • Collect and train on more diverse data

Conclusion

While there’s always room for improvement, this implementation provides a solid foundation for more advanced natural language processing projects.

Remember: The beauty of machine learning isn’t just in the accuracy numbers , it’s in understanding how and why these models work, and how we can make them better.

Happy coding! If you found this tutorial helpful, feel free to share it and experiment with the code. Your feedback and questions are always welcome in the comments below.