A production-ready machine learning API that predicts student performance (Pass/Fail) based on study hours, attendance, and previous scores. Built with Flask, scikit-learn, and deployed on Render with both REST API and web interface.
π Live API: https://student-ml-api-4z9d.onrender.com
- Overview
- Features
- Quick Start
- API Documentation
- Web Interface
- Project Structure
- Model Details
- Local Development
- Deployment
- Testing
- Future Enhancements
- Contributing
- License
This project demonstrates a complete machine learning workflow from data exploration to production deployment. The API predicts whether a student will pass or fail based on three key factors: hours studied, attendance percentage, and previous exam scores.
Tech Stack:
- Machine Learning: scikit-learn (Random Forest Classifier)
- Backend: Flask (Python web framework)
- Deployment: Render (cloud platform)
- Model Serialization: joblib
Use Cases:
- Learning end-to-end ML deployment
- Portfolio demonstration for data science roles
- Template for productionizing classification models
- Reference implementation for Flask-based ML APIs
- β Dual Interface β REST API + Web form for predictions
- β Optimized Model β Random Forest with 200 estimators, 75% accuracy
- β Robust API β Input validation and error handling
- β Production Ready β Deployed and accessible via HTTPS
- β Clean Architecture β Separation of concerns (model, API, templates)
- β Complete ML Pipeline β Data exploration to deployment
- β Reproducible β Pinned dependencies and random state
Using cURL (JSON API):
# Make a prediction via REST API
curl -X POST https://student-ml-api-4z9d.onrender.com/predict \
-H "Content-Type: application/json" \
-d '{
"hours_studied": 7,
"attendance": 85,
"previous_score": 72
}'
# Expected response: {"result": 1} (1 = Pass, 0 = Fail)Using the Web Interface: Simply visit https://student-ml-api-4z9d.onrender.com and fill out the form!
# Clone the repository
git clone https://github.com/TechGenDM/student-ml-api.git
cd student-ml-api
# Create virtual environment
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt
# Start the server
python app.pyThe application will be available at http://127.0.0.1:8000
Production: https://student-ml-api-9qkf.onrender.com
Local: http://127.0.0.1:8000
Returns the web interface for predictions.
Response: HTML form
Generate predictions via JSON API.
Request:
{
"hours_studied": 7,
"attendance": 85,
"previous_score": 72
}Response (Success - 200):
{
"result": 1
}result: Integer (0 = Fail, 1 = Pass)
Response (Error - 400):
{
"error": "hours_studied is missing"
}Required Fields:
hours_studied(float): Hours spent studying (e.g., 1-10)attendance(float): Attendance percentage (e.g., 50-100)previous_score(float): Previous exam score (e.g., 30-90)
Status Codes:
200β Success400β Invalid input (missing fields or invalid JSON)
Form-based prediction endpoint (used by web interface).
Form Data:
hours_studiedattendanceprevious_score
Response: HTML page with prediction result
The application includes a user-friendly web form for non-technical users:
- Navigate to the home page (
/) - Enter the three required values:
- Hours Studied
- Attendance (%)
- Previous Score
- Click "Predict"
- View the result (Pass/Fail) on the page
Perfect for demonstrations, non-technical stakeholders, or quick manual tests!
student-ml-api/
βββ app.py # Flask application & API endpoints
βββ student_model.pkl # Serialized trained Random Forest model
βββ ML_End_to_End.ipynb # Complete ML training pipeline
βββ requirements.txt # Python dependencies
βββ students.csv # Training dataset (20 samples)
βββ templates/
β βββ index.html # Web form interface
βββ README.md # Project documentation
-
app.pyβ Main Flask application with three routes:/- Serves the web form/predict- JSON API endpoint/predict-form- Form submission handler
-
ML_End_to_End.ipynbβ Complete ML workflow:- Data exploration and statistics
- Train/test split (80/20)
- Model comparison (Logistic Regression vs Random Forest)
- Hyperparameter tuning (n_estimators=200, max_depth=5)
- Evaluation metrics (accuracy, precision, recall, F1-score)
- Model serialization with joblib
-
student_model.pklβ Trained Random Forest classifier ready for inference -
templates/index.htmlβ Clean HTML form for web-based predictions
Algorithm: Random Forest Classifier
Hyperparameters:
n_estimators: 200 (number of decision trees)max_depth: 5 (maximum tree depth)min_samples_split: 4 (minimum samples to split node)random_state: 42 (reproducibility)
Features:
- Hours Studied (1-10)
- Attendance Percentage (50-96)
- Previous Score (30-90)
Target:
- 0 = Fail
- 1 = Pass
Performance:
- Accuracy: 75% on test set
- Precision: 100% (no false positives)
- Recall: 50% (misses some pass cases)
- F1-Score: 0.67
Training Data:
- 20 samples total
- 16 training, 4 test samples
- Balanced classes (55% pass rate)
Model Comparison: Both Logistic Regression and Random Forest achieved 75% accuracy. Random Forest was selected for its ability to capture non-linear relationships and better generalization potential with more data.
- Python 3.8 or higher
- pip package manager
- Virtual environment tool (venv recommended)
-
Clone and navigate:
git clone https://github.com/TechGenDM/student-ml-api.git cd student-ml-api -
Create virtual environment:
python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate
-
Install dependencies:
pip install -r requirements.txt
Dependencies:
flaskβ Web frameworknumpyβ Numerical computingjoblibβ Model serializationscikit-learnβ Machine learning library
-
Verify model file exists:
ls student_model.pkl # Should exist in root directory -
Start the server:
python app.py
Server starts on port 8000 with debug mode enabled.
-
Test the API:
# Test web interface open http://127.0.0.1:8000 # or visit in browser # Test JSON API curl -X POST http://127.0.0.1:8000/predict \ -H "Content-Type: application/json" \ -d '{"hours_studied": 8, "attendance": 90, "previous_score": 75}'
- Open
ML_End_to_End.ipynbin Jupyter Notebook - Modify hyperparameters or add more data
- Run all cells to retrain
- The last cell exports the new model:
joblib.dump(rf, "student_model.pkl") - Restart
app.pyto load the updated model
The API is deployed on Render with automatic deployments from the main branch.
Deployment URL: https://student-ml-api-9qkf.onrender.com
-
Fork this repository to your GitHub account
-
Create a Render account at render.com
-
Create a new Web Service:
- Connect your forked repository
- Runtime: Python 3
- Build command:
pip install -r requirements.txt - Start command:
python app.py
-
Environment variables (optional):
PORT: Automatically set by Render- Add any custom variables if needed
-
Deploy and access via the provided Render URL
- β
requirements.txtwith all dependencies - β
student_model.pklin repository root - β
app.pyconfigured for0.0.0.0host - β
templates/folder withindex.html - β Error handling for all endpoints
β οΈ Consider disabling debug mode in production (currently enabled)
Test Web Interface:
# Open in browser
http://127.0.0.1:8000
# Enter values like:
# Hours Studied: 8
# Attendance: 85
# Previous Score: 70Test JSON API with valid data:
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" \
-d '{"hours_studied": 7, "attendance": 85, "previous_score": 72}'
# Expected: {"result": 1}Test with missing fields (should return 400):
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" \
-d '{"hours_studied": 7}'
# Expected: {"error": "attendance is missing"}Test with invalid JSON (should return 400):
curl -X POST http://127.0.0.1:8000/predict \
-H "Content-Type: application/json" \
-d 'not json'
# Expected: {"error": "Request body must be JSON"}- β Model loads successfully on startup
- β Valid predictions return 0 or 1
- β Missing fields return appropriate error messages
- β Invalid JSON returns 400 error
- β Non-numeric values are rejected
- β Web form renders correctly
- β Form submission returns result page
Create test_app.py:
import pytest
from app import app
@pytest.fixture
def client():
with app.test_client() as client:
yield client
def test_home_page(client):
rv = client.get('/')
assert rv.status_code == 200
def test_valid_prediction(client):
rv = client.post('/predict', json={
'hours_studied': 7,
'attendance': 85,
'previous_score': 72
})
assert rv.status_code == 200
assert 'result' in rv.json
def test_missing_field(client):
rv = client.post('/predict', json={'hours_studied': 7})
assert rv.status_code == 400
assert 'error' in rv.json- Collect more training data (currently only 20 samples)
- Add feature engineering (interaction terms, polynomial features)
- Experiment with other algorithms (XGBoost, Neural Networks)
- Implement cross-validation for better evaluation
- Add confidence scores to predictions
- Authentication β API keys or JWT tokens
- Rate Limiting β Prevent abuse with throttling
- Batch Predictions β Process multiple students at once
- Input Validation β Use Pydantic for robust schema validation
- Swagger/OpenAPI β Interactive API documentation
- CORS Support β Allow frontend applications to consume API
- Model Versioning β Track and serve multiple model versions
- Monitoring β Log predictions and track model drift
- A/B Testing β Compare model performance in production
- CI/CD Pipeline β Automated testing with GitHub Actions
- Docker Support β Containerize for easier deployment
- Database Integration β Store predictions and feedback
- Model Retraining β Automated pipeline for retraining with new data
- Improve web interface styling (Bootstrap, Tailwind CSS)
- Add data visualization (feature importance, prediction confidence)
- Provide explanations for predictions (SHAP values, LIME)
- Mobile-responsive design
- Multi-language support
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/AmazingFeature) - Make your changes
- Add tests if applicable
- Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Improve model accuracy
- Add more comprehensive tests
- Enhance documentation
- Optimize API performance
- Add new features from the enhancement list
This project is licensed under the MIT License - see the LICENSE file for details.
- Repository: github.com/TechGenDM/student-ml-api
- Live API: student-ml-api-9qkf.onrender.com
- ML Notebook: See
ML_End_to_End.ipynbfor training details
For questions, feedback, or collaboration opportunities, please open an issue on GitHub or reach out via LinkedIn.
Built with β€οΈ by TechGenDM
From Jupyter notebooks to production β one commit at a time