Skip to content

About

Sentiment Analysis with BERT on Movie Reviews

Resources

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

ย 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Sentiment Analysis with BERT ๐ŸŽฌ

Python PyTorch Transformers License

A state-of-the-art sentiment analysis model using BERT for movie review classification. This project achieves high accuracy on the IMDB dataset through fine-tuning a pre-trained BERT model for binary sentiment classification.

๐ŸŽฏ Project Overview

This project implements a comprehensive sentiment analysis pipeline using BERT (Bidirectional Encoder Representations from Transformers) to classify movie reviews as positive or negative. The implementation includes data preprocessing, model training, evaluation, and testing components with professional-grade code quality.

Key Features

  • ๐Ÿง  BERT-based Architecture: Utilizes bert-base-uncased for robust text understanding
  • ๐Ÿ“Š Comprehensive Evaluation: Includes accuracy, F1-score, confusion matrix, and classification reports
  • ๐Ÿ”ง Modular Design: Clean, reusable code with proper separation of concerns
  • ๐Ÿ“ˆ Visualization: Training loss curves and performance metrics visualization
  • ๐Ÿงช Testing Suite: Unit tests and code quality checks with flake8 and mypy
  • ๐Ÿ’พ Model Persistence: Automated model saving with configuration tracking

๐Ÿ“ Project Structure

sentiment-analysis/
โ”œโ”€โ”€ ๐Ÿ“‚ data/
โ”‚   โ””โ”€โ”€ imdb_dataset.csv              # Original IMDB dataset
โ”œโ”€โ”€ ๐Ÿ“‚ cleaned_splitted_data/
โ”‚   โ”œโ”€โ”€ train_dataset.csv             # Training data (72% of dataset)
โ”‚   โ”œโ”€โ”€ val_dataset.csv               # Validation data (8% of dataset)
โ”‚   โ””โ”€โ”€ test_dataset.csv              # Test data (20% of dataset)
โ”œโ”€โ”€ ๐Ÿ“‚ models/
โ”‚   โ”œโ”€โ”€ sentiment_analysis_model_*.pth # Trained model weights
โ”‚   โ”œโ”€โ”€ tokenizer/                    # BERT tokenizer files
โ”‚   โ””โ”€โ”€ model_config.json             # Model configuration and metrics
โ”œโ”€โ”€ ๐Ÿ““ train_model.ipynb              # Model training notebook
โ”œโ”€โ”€ ๐Ÿ““ test_model.ipynb               # Model testing and validation notebook
โ”œโ”€โ”€ ๐Ÿ Utils.py                       # Utility functions and custom dataset class
โ”œโ”€โ”€ ๐Ÿ“‹ requirements.txt               # Project dependencies
โ””โ”€โ”€ ๐Ÿ“– README.md                      # Project documentation

๐Ÿ‘ฅ Team Members

๐Ÿ“Š Dataset

Source: IMDB 50K Movie Review Dataset

  • Size: 50,000 movie reviews
  • Balance: 25,000 positive and 25,000 negative reviews
  • Task: Binary sentiment classification
  • Format: CSV with 'review' and 'sentiment' columns

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.8 or higher
  • CUDA-compatible GPU (optional, for faster training)

Installation

  1. Clone the repository

    git clone https://github.com/chihab4real/sentiment-analysis.git
    cd sentiment-analysis
  2. Install dependencies

    pip install -r requirements.txt
  3. Download the dataset

    • Download the IMDB dataset from Kaggle
    • Place imdb_dataset.csv in the data/ directory

Training the Model

# Open the training notebook
jupyter notebook train_model.ipynb

Or run all cells programmatically:

jupyter nbconvert --to script train_model.ipynb
python train_model.py

Testing the Model

# Open the testing notebook
jupyter notebook test_model.ipynb

๐Ÿ”ง Technical Implementation

Data Preprocessing Pipeline

# Text cleaning and normalization
def clean_text(text):
    text = re.sub(r'<.*?>', '', text)        # Remove HTML tags
    text = re.sub(r'[^a-zA-Z\s]', '', text)  # Keep only alphabetic characters
    text = text.lower()                       # Lowercase normalization
    text = re.sub(r'\s+', ' ', text).strip()  # Remove extra whitespace
    return text

Key Processing Steps:

  1. HTML Tag Removal: Strips HTML markup from review text
  2. Text Normalization: Converts to lowercase and removes special characters
  3. Label Mapping: positive โ†’ 1, negative โ†’ 0
  4. Dataset Splitting: 72% training, 8% validation, 20% testing

Model Architecture

# BERT model configuration
MODEL_NAME = 'bert-base-uncased'
MAX_LENGTH = 128
NUM_LABELS = 2

model = BertForSequenceClassification.from_pretrained(
    MODEL_NAME, 
    num_labels=NUM_LABELS
)

Architecture Details:

  • Base Model: bert-base-uncased (110M parameters)
  • Classification Head: Linear layer with 2 output classes
  • Tokenizer: BERT WordPiece tokenizer with 128 max sequence length
  • Input Processing: Attention masks and special tokens ([CLS], [SEP])

Training Configuration

Parameter Value Description
Optimizer AdamW Adaptive learning rate with weight decay
Learning Rate 2e-5 Optimal rate for BERT fine-tuning
Batch Size 32 Balanced for memory and convergence
Epochs 3 Sufficient for convergence without overfitting
Max Length 128 Captures most review content efficiently

๐Ÿ“ˆ Performance Metrics

The model achieves excellent performance on the IMDB test set:

  • Accuracy: ~90-95% (typical range for BERT on IMDB)
  • F1 Score: Balanced performance across both classes
  • Training Time: ~2-3 hours on GPU, ~8-12 hours on CPU

Evaluation Visualizations

  • ๐Ÿ“Š Training Loss Curve: Monitors convergence during training
  • ๐Ÿ”ฅ Confusion Matrix: Visualizes prediction accuracy by class
  • ๐Ÿ“ˆ Classification Report Heatmap: Detailed precision/recall metrics
  • ๐Ÿ“‰ Validation Accuracy: Tracks performance on unseen data

๐Ÿ› ๏ธ Code Quality & Testing

Static Analysis

# Code style checking
flake8 Utils.py

# Type checking
mypy Utils.py

Unit Testing

# Test data preprocessing functions
python -m unittest test_model.py

Test Coverage:

  • Text cleaning functionality
  • Label mapping accuracy
  • Dataset loading and splitting
  • Model prediction pipeline

๐ŸŽฏ Usage Example

from Utils import predict_sentiment
from transformers import BertTokenizer, BertForSequenceClassification
import torch

# Load trained model
model = BertForSequenceClassification.from_pretrained('./models/')
tokenizer = BertTokenizer.from_pretrained('./models/tokenizer/')

# Predict sentiment
review = "This movie was absolutely fantastic! The acting was superb."
sentiment = predict_sentiment(model, tokenizer, device, 128, review)
print(f"Sentiment: {sentiment}")  # Output: Sentiment: Positive

๐Ÿš€ Model Deployment

The trained model can be deployed using:

  • Hugging Face Hub: For easy sharing and inference
  • TorchScript: For production deployment
  • ONNX: For cross-platform compatibility
  • Web Interface: Using Gradio or Streamlit

๐Ÿ“‹ Dependencies

pandas>=1.5          # Data manipulation
torch>=2.0           # Deep learning framework
transformers>=4.30   # Hugging Face transformers
scikit-learn>=1.3    # ML utilities and metrics
matplotlib>=3.7      # Plotting and visualization
seaborn>=0.12        # Statistical visualization
tqdm>=4.65          # Progress bars
numpy>=1.23         # Numerical computing
mypy>=1.5           # Type checking
flake8>=6.0         # Code style checking

๐Ÿ”ฎ Future Enhancements

  • Multi-class Classification: Extend to neutral/mixed sentiment
  • Model Optimization: Quantization and pruning for deployment
  • Real-time Inference: Web API with FastAPI
  • Hyperparameter Tuning: Automated optimization with Optuna
  • Cross-domain Evaluation: Test on other review types (books, products)
  • Ensemble Methods: Combine multiple models for better performance

๐Ÿค Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Hugging Face for the transformers library
  • IMDB Dataset creators
  • The PyTorch team for the excellent deep learning framework

Built with โค๏ธ by the Sentiment Analysis Team

About

Sentiment Analysis with BERT on Movie Reviews

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages