This project implements a Simple RNN for sentiment analysis on the IMDB movie reviews dataset using PyTorch, while still utilizing TensorFlow's IMDB dataset for data loading and preprocessing.
simplernn.ipynb- Main training notebook with PyTorch RNN implementationprediction.ipynb- Notebook for making predictions with the trained modelembedding.ipynb- Demonstrates word embeddings using both TensorFlow preprocessing and PyTorch embeddingsmain.py- Streamlit web application for interactive sentiment analysisrequirements.txt- Python dependencies
- Before (TensorFlow): Used
keras.SequentialwithEmbedding,SimpleRNN, andDenselayers - After (PyTorch): Custom
SimpleRNNClassifierclass inheriting fromnn.Module
- Dataset: Still uses TensorFlow's
imdb.load_data()for consistency - Preprocessing: Uses TensorFlow's
sequence.pad_sequences() - Tensors: Converts to PyTorch
LongTensorandFloatTensor - DataLoaders: Uses PyTorch's
DataLoaderfor efficient batching
- Before: Used
model.fit()with callbacks - After: Manual training loop with proper gradient handling
- Early Stopping: Implemented manually with patience mechanism
- Device Support: Automatic GPU/CPU detection
- Before: Saved as
.h5file usingmodel.save() - After: Saves state dictionary as
.pthfile usingtorch.save()
pip install -r requirements.txt# Install dependencies
pip install -r requirements.txt
# Train the model with default parameters
python train_model.py
# Or with custom parameters
python train_model.py --epochs 15 --batch_size 64 --lr 0.0005- Install dependencies:
pip install -r requirements.txt - Run
simplernn.ipynbto train the model - Run
prediction.ipynbto test predictions - Run
embedding.ipynbto understand embeddings
# Make sure the model is trained first
streamlit run main.pypython comparison.pyRun the simplernn.ipynb notebook to train the PyTorch RNN model:
- Loads IMDB dataset using TensorFlow
- Preprocesses data and creates PyTorch DataLoaders
- Trains the model with early stopping
- Saves the trained model as
simple_rnn_imdb_pytorch.pth
Use the prediction.ipynb notebook to test the trained model:
- Loads the trained PyTorch model
- Provides helper functions for text preprocessing
- Demonstrates prediction on sample reviews
Run the Streamlit app for interactive predictions:
streamlit run main.pyThe embedding.ipynb notebook shows:
- How word embeddings work
- Comparison between TensorFlow preprocessing and PyTorch embeddings
- Visualization of embedding layers
class SimpleRNNClassifier(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim):
super(SimpleRNNClassifier, self).__init__()
self.embedding = nn.Embedding(vocab_size, embedding_dim)
self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
self.fc = nn.Linear(hidden_dim, output_dim)
self.sigmoid = nn.Sigmoid()- Vocabulary Size: 10,000 words
- Embedding Dimension: 128
- Hidden Dimension: 128
- Sequence Length: 500 tokens
- Output: Binary classification (positive/negative)
- ✅ Early stopping with patience
- ✅ Validation split (20%)
- ✅ GPU/CPU automatic detection
- ✅ Progress bars with tqdm
- ✅ Training history visualization
- ✅ Model checkpointing
- ✅ Text preprocessing pipeline
- ✅ Confidence scoring
- ✅ Batch prediction support
- ✅ Interactive web interface
- ✅ TensorFlow IMDB dataset integration
- ✅ PyTorch tensor conversion
- ✅ Efficient DataLoader usage
- ✅ Proper train/validation/test splits
The model achieves similar performance to the original TensorFlow implementation:
- Training Accuracy: ~85-90%
- Validation Accuracy: ~80-85%
- Training Time: ~10-15 minutes (depending on hardware)
- More Control: Manual training loop allows for better debugging and customization
- Flexibility: Easier to modify model architecture and training process
- Research-Friendly: Better suited for experimentation and research
- Dynamic Graphs: More intuitive debugging with dynamic computational graphs
- Modern Ecosystem: Access to latest PyTorch features and community tools
This implementation demonstrates a hybrid approach:
- Data: Uses TensorFlow's well-established IMDB dataset
- Preprocessing: Leverages TensorFlow's robust preprocessing utilities
- Model & Training: Uses PyTorch for modern deep learning practices
- Deployment: Streamlit for easy web deployment
This approach combines the best of both frameworks while maintaining compatibility with existing TensorFlow datasets.