Sebuah aplikasi web machine learning yang dibangun dengan Flask & Docker untuk memprediksi harga rumah berdasarkan berbagai fitur menggunakan model Random Forest.
- π¨ Web App: Antarmuka pengguna yang modern dan responsif dengan Bootstrap 5
- π RESTful API: Endpoint API lengkap untuk prediksi, health check, dan informasi model
- π€ ML Model: Model Random Forest Regressor dengan akurasi tinggi
- π³ Dockerized: Mudah di-deploy menggunakan Docker dan Docker Compose
- π Real-time Prediction: Prediksi langsung dengan confidence score
- π‘οΈ Input Validation: Validasi input yang komprehensif di frontend dan backend
- π± Responsive Design: Tampilan yang optimal di semua device
- π§ͺ Testing: Unit tests dengan pytest
- π Monitoring: Health check dan monitoring endpoint
- Python 3.11+
- Flask 2.3.3 - Web framework
- scikit-learn - Machine learning library
- pandas & numpy - Data processing
- gunicorn - WSGI server
- HTML5 & CSS3
- Bootstrap 5 - UI framework
- JavaScript ES6+ - Interactive features
- Font Awesome - Icons
- Docker & Docker Compose - Containerization
- Nginx - Reverse proxy (optional)
- pytest - Testing framework
- Docker 20.10+
- Docker Compose 2.0+
- Python 3.11+
- Flask 2.3.3+
- pip atau conda
git clone https://github.com/AbyanDimas/flask-prediction-app
cd flask-prediction-app# Create virtual environment
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# Install dependencies
pip install --upgrade pip
pip install -r requirements.txt
# Run development server
export FLASK_APP=app.py # Windows: set FLASK_APP=app.py
export FLASK_ENV=development # Windows: set FLASK_ENV=development
flask run
# Or run directly
python app.pyβ‘οΈ Akses aplikasi di http://localhost:5000
# Build and run
docker-compose up --build
# Run in background
docker-compose up -d --build
# View logs
docker-compose logs -fβ‘οΈ Akses aplikasi di http://localhost:5000
# Production mode dengan Nginx
docker-compose --profile production up --build
# Or dengan environment variables
FLASK_ENV=production SECRET_KEY=your-secret-key docker-compose up --buildβ‘οΈ Akses aplikasi di http://localhost:80
- Akses aplikasi di browser:
http://localhost:5000 - Isi form prediksi dengan detail rumah:
- Area (sq ft): Luas rumah dalam kaki persegi (500-10,000)
- Bedrooms: Jumlah kamar tidur (1-6+)
- Bathrooms: Jumlah kamar mandi (1-4+)
- Age (years): Umur rumah dalam tahun (0-200)
- Location Score: Skor lokasi 1-10 (kualitas lingkungan)
- Klik "Predict House Price" untuk mendapatkan estimasi harga
- Lihat hasil dengan confidence score dan breakdown harga
GET /api/healthResponse:
{
"status": "healthy",
"model_loaded": true,
"timestamp": "2024-01-15T10:30:00"
}POST /api/predict
Content-Type: application/jsonRequest Body:
{
"area": 2000,
"bedrooms": 3,
"bathrooms": 2.5,
"age": 10,
"location_score": 7.5
}Response:
{
"success": true,
"prediction": 485000.50,
"confidence": 0.85,
"formatted_price": "$485,001",
"features_used": {
"area": 2000,
"bedrooms": 3,
"bathrooms": 2.5,
"age": 10,
"location_score": 7.5
}
}GET /api/model-infoResponse:
{
"model_type": "Random Forest Regressor",
"features": ["area", "bedrooms", "bathrooms", "age", "location_score"],
"version": "1.0.0",
"last_trained": "2024-01-15T08:00:00"
}# Health check
curl -X GET http://localhost:5000/api/health
# Prediksi harga
curl -X POST http://localhost:5000/api/predict \
-H "Content-Type: application/json" \
-d '{
"area": 2500,
"bedrooms": 4,
"bathrooms": 3,
"age": 5,
"location_score": 8.0
}'import requests
import json
# Prediksi harga rumah
url = "http://localhost:5000/api/predict"
data = {
"area": 2500,
"bedrooms": 4,
"bathrooms": 3,
"age": 5,
"location_score": 8.0
}
response = requests.post(url, json=data)
result = response.json()
print(f"Predicted Price: {result['formatted_price']}")
print(f"Confidence: {result['confidence']:.1%}")// Fetch API
fetch('/api/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
area: 2500,
bedrooms: 4,
bathrooms: 3,
age: 5,
location_score: 8.0
})
})
.then(response => response.json())
.then(data => {
console.log('Predicted Price:', data.formatted_price);
console.log('Confidence:', (data.confidence * 100).toFixed(1) + '%');
});Buat file .env untuk konfigurasi development:
# Flask Configuration
FLASK_APP=app.py
FLASK_ENV=development
FLASK_DEBUG=True
FLASK_HOST=127.0.0.1
FLASK_PORT=5000
# Security
SECRET_KEY=dev-secret-key-change-in-production
# Application Settings
APP_NAME=House Price Predictor
APP_VERSION=1.0.0Untuk production, set environment variables melalui Docker atau system:
export FLASK_ENV=production
export FLASK_DEBUG=False
export SECRET_KEY=your-super-secret-production-keyflask-prediction-app/
βββ app/
β βββ __init__.py # Flask app factory
β βββ routes.py # API routes dan web routes
β βββ models/
β β βββ __init__.py
β β βββ predictor.py # ML model dan training logic
β βββ utils/
β β βββ __init__.py
β β βββ validators.py # Input validation functions
β β βββ helpers.py # Helper utilities
β βββ static/
β β βββ css/
β β β βββ style.css # Custom CSS styles
β β βββ js/
β β βββ main.js # Frontend JavaScript
β βββ templates/
β βββ base.html # Base template
β βββ index.html # Home page
β βββ result.html # Prediction result page
βββ tests/
β βββ __init__.py
β βββ test_app.py # Unit tests
βββ data/ # Data files (optional)
βββ .env # Environment variables
βββ .dockerignore # Docker ignore file
βββ Dockerfile # Docker image definition
βββ docker-compose.yml # Docker Compose configuration
βββ requirements.txt # Python dependencies
βββ app.py # Application entry point
βββ README.md # Documentation
- Flask App Factory: Modular Flask application setup
- ML Model: Random Forest Regressor dengan synthetic data generation
- API Layer: RESTful endpoints untuk prediksi dan monitoring
- Web Interface: Bootstrap-based UI dengan JavaScript interactivity
- Validation: Comprehensive input validation di frontend dan backend
- Docker: Multi-stage build dengan production optimizations
- User Input β Web form atau API request
- Validation β Input validation dan sanitization
- Feature Processing β Data transformation untuk model
- ML Prediction β Random Forest model inference
- Response β Formatted hasil dengan confidence score
| Feature | Type | Range | Description |
|---|---|---|---|
area |
float | 500-10,000 | Luas rumah dalam sq ft |
bedrooms |
int | 1-10 | Jumlah kamar tidur |
bathrooms |
float | 1-10 | Jumlah kamar mandi |
age |
int | 0-200 | Umur rumah dalam tahun |
location_score |
float | 1-10 | Skor kualitas lokasi |
- Algorithm: Random Forest Regressor
- Features: 5 numerical features
- Training Data: 1000 synthetic samples
- Accuracy: ~85% (pada synthetic data)
- Response Time: <100ms average
Confidence score dihitung berdasarkan:
- Model RΒ² score
- Feature value reasonableness
- Similarity dengan training data patterns
Tests are organized using pytest.
pytestCode should adhere to PEP 8. Use flake8 and black for code style and formatting.
flake8 app
black appAplikasi ini dilengkapi dengan model Random Forest yang telah dilatih sebelumnya, tetapi Anda dapat melatih model baru menggunakan kelas HousePricePredictor yang ditemukan di app/models/predictor.py.
Enjoy using the House Price Predictor App! π
Aplikasi ini dirancang untuk tujuan pendidikan. Aplikasi ini menunjukkan cara mengintegrasikan model pembelajaran mesin ke dalam aplikasi web dan menerapkannya dengan Docker. Jangan ragu untuk mengubah dan memperluas kemampuannya!