A deep learning project that classifies movie reviews as positive or negative using a Long Short-Term Memory (LSTM) neural network built with TensorFlow/Keras, trained on the IMDB dataset of 50,000 labeled reviews.
This project demonstrates an end-to-end NLP pipeline:
- Text preprocessing and sequence padding
- Word embeddings learned from scratch
- An LSTM-based recurrent neural network for sequence classification
- Regularization via dropout to reduce overfitting
- Model evaluation, training curve visualization, and inference on custom text
- Modular, testable code structure (not a single notebook dump)
Input (word IDs, len=200)
│
Embedding Layer (10,000 vocab → 128-dim vectors)
│
SpatialDropout1D (0.2)
│
LSTM (64 units, dropout=0.2, recurrent_dropout=0.2)
│
Dense (64, ReLU)
│
Dropout (0.3)
│
Dense (1, Sigmoid) → Positive / Negative
sentiment-analysis-lstm/
├── main.py # Entry point — trains, evaluates, demos the model
├── app.py # Streamlit web demo
├── requirements.txt # Python dependencies
├── README.md # Project documentation
├── .gitignore
│
├── src/ # Source code (importable package)
│ ├── __init__.py
│ ├── config.py # Hyperparameters & file paths
│ ├── data_loader.py # Data loading, padding, text encoding
│ ├── model.py # LSTM architecture definition
│ ├── train.py # Training loop with early stopping
│ ├── evaluate.py # Evaluation + training curve plots
│ └── predict.py # Inference on custom text
│
├── tests/ # Unit tests (pytest)
│ └── test_model.py
│
├── notebooks/ # Exploratory analysis / experiments (optional)
│
├── data/
│ ├── raw/ # Original/unprocessed data (if using custom dataset)
│ └── processed/ # Cleaned/tokenized data
│
├── models/ # Saved trained models (.h5)
│
└── outputs/
├── plots/ # Training curve images
└── metrics/ # Saved evaluation metrics (JSON)
git clone https://github.com/<your-username>/sentiment-analysis-lstm.git
cd sentiment-analysis-lstm
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txtpython main.pyThis will:
- Download the IMDB dataset (built into Keras)
- Train the LSTM model for up to 10 epochs (with early stopping)
- Evaluate on the held-out test set
- Save the trained model to
models/, training curve plots tooutputs/plots/, and metrics tooutputs/metrics/ - Run predictions on a few sample sentences
Once you've trained a model at least once (step 2 above saves it to models/), launch the interactive web demo:
streamlit run app.pyThis opens a browser tab where you can type any review and get a live Positive/Negative prediction with a confidence score.
pytest tests/Test Accuracy: 0.87xx
'This movie was absolutely wonderful and touching' -> Positive (0.9123)
'Terrible plot, bad acting, complete waste of time' -> Negative (0.0512)
'It was an okay movie, nothing special but not bad either' -> Positive (0.6104)
| Metric | Score |
|---|---|
| Test Accuracy | ~87–89% |
| Test Loss | ~0.30 |
(exact numbers vary run to run due to random initialization)
- Word Embeddings – dense vector representations of words learned during training
- Recurrent Neural Networks (LSTM) – handling sequential/contextual dependencies in text
- Regularization – Dropout & SpatialDropout1D to prevent overfitting
- Binary Classification – sigmoid output + binary cross-entropy loss
- Early Stopping – halting training when validation loss stops improving
- Modular software design – separated config, data, model, training, and inference logic
- Unit testing – pytest tests validating model construction
- Python 3.x
- TensorFlow / Keras
- NumPy
- Matplotlib
- Pytest
- Streamlit
- Swap the built-in Embedding layer for pretrained GloVe or Word2Vec vectors
- Replace LSTM with Bidirectional LSTM or GRU for comparison
- Add an attention layer to visualize which words drove the prediction
- Deploy as a REST API (Flask/FastAPI) or simple web app (Streamlit)
- Extend to multi-class sentiment (e.g., 1–5 star ratings)
- Swap in a custom CSV dataset using
src/data_loader.pyas the integration point
MIT License — free to use and modify.