Skip to content

About

This is the machine learning program that follows a complete mlops workflow and frames.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

23 Commits

Folders and files

Repository files navigation

🎬 Movie Review Sentiment Analysis β€” MLOps End-to-End

A production-ready sentiment analysis system for movie reviews that demonstrates comprehensive MLOps practices from data ingestion to model serving and monitoring. Built with industry-standard tools including DVC for pipeline orchestration, Flask for model serving, and optional Prometheus/Grafana monitoring integration.

Python MLOps DVC Flask

✨ Features

πŸ—οΈ Production MLOps Architecture: Complete workflow from data versioning through model deployment with industry best practices

πŸ“Š Cookiecutter Data Science Structure: Organized project layout with clear separation of data, source code, models, and documentation

πŸ”„ Reproducible ML Pipelines: DVC-orchestrated workflows with configurable parameters and automatic dependency tracking

πŸ“¦ Model Packaging & Distribution: pip-installable package structure with proper dependency management and version control

πŸš€ API-Ready Model Serving: Flask-based REST API for real-time sentiment prediction with JSON input/output

πŸ“ˆ Comprehensive Monitoring: Optional Prometheus metrics and Grafana dashboards for production model observability

πŸ—‚οΈ Project structure

.
β”œβ”€β”€ .dvc/                 # DVC configuration and cache management
β”œβ”€β”€ .github/workflows/    # CI/CD automation with GitHub Actions
β”œβ”€β”€ docs/                 # Sphinx documentation framework
β”œβ”€β”€ flask_app/            # Production Flask API for model serving
β”œβ”€β”€ models/               # Serialized model artifacts and weights
β”œβ”€β”€ notebooks/            # Jupyter notebooks for EDA and experiments
β”œβ”€β”€ references/           # Data dictionaries and project documentation
β”œβ”€β”€ reports/              # Generated analysis reports and visualizations
β”œβ”€β”€ src/                  # Source code package (data, features, models, viz)
β”œβ”€β”€ tests/                # Unit tests and integration tests
β”œβ”€β”€ dvc.yaml              # ML pipeline definition and stages
β”œβ”€β”€ dvc.lock              # Locked pipeline versions for reproducibility
β”œβ”€β”€ params.yaml           # Centralized hyperparameters and configuration
β”œβ”€β”€ Makefile              # Development workflow automation
└── requirements.txt      # Python dependencies

πŸš€ Quickstart

Prerequisites

  • Python 3.8 or higher
  • Git and DVC for version control and pipeline management

1) Clone & setup environment

git clone https://github.com/AbdullahRasheed45/Movie_sentiment_analysis_MLOPS.git
cd Movie_sentiment_analysis_MLOPS

# Create virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate

# Install dependencies and package
pip install -r requirements.txt
pip install -e .             # Install src/ as editable package

2) Configure pipeline parameters

# Edit params.yaml for your specific requirements
data:
  raw_data_path: "data/raw/movie_reviews.csv"
  test_size: 0.2
  random_state: 42

model:
  algorithm: "logistic_regression"
  max_features: 10000
  ngram_range: [1, 2]

training:
  epochs: 100
  batch_size: 32
  learning_rate: 0.001

3) Execute ML pipeline

# Initialize DVC (if not already done)
dvc init

# Run complete pipeline from data to model
dvc repro

# Check pipeline status
dvc dag

4) Validate environment & run tests

# Sanity check Python environment
python test_environment.py

# Run comprehensive test suite
pytest tests/ -v

# Check code quality
make lint

5) Start model serving API

# Launch Flask API server
cd flask_app/
python app.py

# Test API endpoint
curl -X POST http://127.0.0.1:5000/predict \
  -H "Content-Type: application/json" \
  -d '{"text": "This movie was absolutely fantastic!"}'

🧠 MLOps pipeline architecture

Stage 1: Data Ingestion

# src/data/make_dataset.py
def load_movie_reviews():
    """Download and preprocess raw movie review data"""
    # - Fetch data from external sources
    # - Handle missing values and duplicates
    # - Store in data/raw/ for immutable reference

Stage 2: Feature Engineering

# src/features/build_features.py  
def create_text_features(df):
    """Transform raw text into ML-ready features"""
    # - Text preprocessing (tokenization, stopwords)
    # - TF-IDF vectorization with n-grams
    # - Feature selection and dimensionality reduction

Stage 3: Model Training

# src/models/train_model.py
def train_sentiment_model(X_train, y_train):
    """Train and validate sentiment classification model"""
    # - Cross-validation with stratified splits
    # - Hyperparameter optimization
    # - Model serialization to models/

Stage 4: Model Evaluation

# src/models/evaluate_model.py
def evaluate_performance(model, X_test, y_test):
    """Generate comprehensive model evaluation metrics"""
    # - Classification reports and confusion matrices
    # - ROC curves and precision-recall analysis
    # - Save results to reports/

Stage 5: Model Packaging

# Automated model versioning and deployment preparation
# - Model artifact packaging with metadata
# - API-ready prediction interface
# - Performance benchmarking

βš™οΈ Configuration management

Centralized Parameters (params.yaml):

# Data processing configuration
preprocessing:
  text_cleaning: true
  lowercase: true
  remove_punctuation: true
  min_word_length: 2
  max_vocab_size: 50000

# Model hyperparameters
model_params:
  classifier_type: "logistic_regression"
  regularization: "l2"
  C: 1.0
  max_iter: 1000
  
# Training configuration  
training_config:
  validation_split: 0.2
  stratify: true
  cross_validation_folds: 5
  
# Evaluation metrics
metrics:
  primary: "f1_score"
  track: ["accuracy", "precision", "recall", "auc"]

DVC Pipeline (dvc.yaml):

stages:
  prepare_data:
    cmd: python src/data/make_dataset.py
    deps: [data/external/]
    outs: [data/raw/movie_reviews.csv]
    
  build_features:
    cmd: python src/features/build_features.py
    deps: [data/raw/, src/features/]
    outs: [data/processed/]
    
  train_model:
    cmd: python src/models/train_model.py
    deps: [data/processed/, src/models/, params.yaml]
    outs: [models/sentiment_model.pkl]
    metrics: [reports/training_metrics.json]

πŸ”§ Development workflow automation

Makefile Commands:

# Data operations
make data          # Download and prepare datasets
make features      # Generate ML features from raw data

# Model operations  
make train         # Train models with current parameters
make evaluate      # Generate model performance reports
make predict       # Run batch predictions on test data

# Quality assurance
make test          # Run full test suite
make lint          # Code quality checks and formatting
make clean         # Clean temporary files and caches

# Deployment
make serve         # Start Flask API server
make docker        # Build Docker container for deployment

Automated Testing Pipeline:

# tests/test_data_processing.py
def test_data_loading():
    """Verify data loading and preprocessing pipeline"""
    
def test_feature_engineering():
    """Validate feature creation and transformation"""
    
def test_model_training():
    """Ensure model training completes successfully"""
    
def test_api_endpoints():
    """Integration tests for Flask API"""

πŸš€ Model serving & deployment

Flask API Structure:

# flask_app/app.py
@app.route('/predict', methods=['POST'])
def predict_sentiment():
    """Real-time sentiment prediction endpoint"""
    data = request.get_json()
    text = data['text']
    
    # Preprocessing and feature extraction
    processed_text = preprocess_text(text)
    features = vectorizer.transform([processed_text])
    
    # Model prediction
    prediction = model.predict_proba(features)[0]
    
    return jsonify({
        'sentiment': 'positive' if prediction[1] > 0.5 else 'negative',
        'confidence': float(max(prediction)),
        'probabilities': {
            'negative': float(prediction[0]),
            'positive': float(prediction[1])
        }
    })

API Usage Examples:

# Single prediction
curl -X POST http://localhost:5000/predict \
  -H "Content-Type: application/json" \
  -d '{"text": "The cinematography was breathtaking and the acting superb!"}'

# Batch predictions
curl -X POST http://localhost:5000/predict_batch \
  -H "Content-Type: application/json" \
  -d '{"texts": ["Great movie!", "Terrible plot.", "Average film."]}'

# Model info and health check
curl http://localhost:5000/info
curl http://localhost:5000/health

πŸ“Š Monitoring & observability

Prometheus Metrics Integration:

# flask_app/monitoring.py
from prometheus_client import Counter, Histogram, generate_latest

# Track API usage metrics
prediction_counter = Counter('sentiment_predictions_total', 
                           'Total predictions made')
prediction_latency = Histogram('sentiment_prediction_duration_seconds',
                              'Time spent on predictions')

@app.route('/metrics')
def metrics():
    """Prometheus metrics endpoint"""
    return generate_latest()

Grafana Dashboard Panels:

  • Request Volume: Predictions per minute/hour
  • Response Latency: P50, P95, P99 prediction times
  • Model Performance: Confidence distribution, prediction accuracy
  • System Health: Memory usage, CPU utilization, error rates
  • Data Drift: Feature distribution changes over time

πŸ“ˆ Experiment tracking & versioning

DVC Data Versioning:

# Track dataset changes
dvc add data/raw/movie_reviews.csv
git add data/raw/movie_reviews.csv.dvc
git commit -m "Add movie reviews dataset v1.0"

# Update datasets
dvc checkout data/raw/movie_reviews.csv.dvc
dvc push  # Sync to remote storage

# Compare experiments
dvc plots diff experiment1 experiment2
dvc metrics diff HEAD~1

Model Registry & Comparison:

# Track model versions and performance
model_metrics = {
    'version': '1.2.0',
    'accuracy': 0.892,
    'f1_score': 0.885,
    'training_time': '00:12:34',
    'model_size_mb': 15.7,
    'parameters': params
}

# Automated model comparison and selection
best_model = compare_models(current_model, previous_models)

πŸ”’ Production considerations

Security & Privacy:

# Input validation and sanitization
def validate_input(text):
    if len(text) > MAX_TEXT_LENGTH:
        raise ValidationError("Text too long")
    
    # Remove potential security threats
    clean_text = sanitize_text(text)
    return clean_text

# Rate limiting and abuse prevention
@limiter.limit("100 per minute")
@app.route('/predict', methods=['POST'])
def predict_sentiment():
    # Prediction logic with rate limiting
    pass

Scalability & Performance:

  • Model Caching: In-memory model loading for faster predictions
  • Batch Processing: Efficient handling of multiple predictions
  • Load Balancing: Multiple Flask workers with Gunicorn
  • Container Deployment: Docker support for cloud deployment

πŸ§ͺ Quality assurance pipeline

Continuous Integration:

# .github/workflows/ci.yml
name: MLOps Pipeline
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Setup Python
        uses: actions/setup-python@v2
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        run: pytest tests/ --cov=src/
      - name: Run DVC pipeline
        run: dvc repro
      - name: Validate model performance
        run: python src/models/validate_model.py

Model Validation & Testing:

# Automated model quality checks
def validate_model_performance(model, test_data):
    """Ensure model meets production quality standards"""
    metrics = evaluate_model(model, test_data)
    
    assert metrics['accuracy'] > 0.85, "Model accuracy below threshold"
    assert metrics['f1_score'] > 0.80, "Model F1 score insufficient" 
    assert metrics['precision'] > 0.82, "Model precision too low"
    
    return metrics

πŸ› Troubleshooting guide

Pipeline Issues:

  • DVC Pipeline Fails β†’ Check dvc doctor, verify file paths in params.yaml
  • Import Errors β†’ Ensure pip install -e . completed successfully
  • Memory Issues β†’ Reduce batch size or feature dimensions in params.yaml

API Issues:

  • Flask Won't Start β†’ Verify model artifacts exist in models/ directory
  • Slow Predictions β†’ Enable model caching or reduce feature complexity
  • JSON Errors β†’ Validate request format matches API schema

Data Issues:

  • Missing Data β†’ Run dvc pull to sync from remote storage
  • Data Drift β†’ Update preprocessing pipeline and retrain model
  • Large Files β†’ Configure DVC remote storage (S3, GCS, Azure)

πŸ“š References & attribution

This project follows the Cookiecutter Data Science template for reproducible, production-ready ML projects. The MLOps practices implemented here are based on industry best practices from organizations like Google, Netflix, and Uber.

Key Technologies:

  • DVC: Data version control and ML pipeline orchestration
  • Flask: Lightweight web framework for model serving
  • Prometheus/Grafana: Production monitoring and observability
  • pytest: Testing framework with coverage reporting
  • GitHub Actions: Continuous integration and deployment

πŸ“œ License

MIT License - see LICENSE file for complete terms.

πŸ“ž Connect & Support

πŸš€ Ready to Build Production MLOps Systems?

Portfolio LinkedIn Email GitHub

Let's build scalable, production-ready ML systems together!


Built with ❀️ following MLOps best practices. Perfect for learning production ML workflows and building enterprise-grade machine learning systems.

About

This is the machine learning program that follows a complete mlops workflow and frames.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages