Skip to content

About

Sebuah aplikasi web machine learning yang dibangun dengan Flask & Docker untuk memprediksi harga rumah berdasarkan berbagai fitur menggunakan model Random Forest.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

🏠 House Price Predictor

Python Flask Docker ML License

Sebuah aplikasi web machine learning yang dibangun dengan Flask & Docker untuk memprediksi harga rumah berdasarkan berbagai fitur menggunakan model Random Forest.

✨ Fitur Utama

  • 🎨 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

πŸ› οΈ Tech Stack

Backend

  • Python 3.11+
  • Flask 2.3.3 - Web framework
  • scikit-learn - Machine learning library
  • pandas & numpy - Data processing
  • gunicorn - WSGI server

Frontend

  • HTML5 & CSS3
  • Bootstrap 5 - UI framework
  • JavaScript ES6+ - Interactive features
  • Font Awesome - Icons

DevOps

  • Docker & Docker Compose - Containerization
  • Nginx - Reverse proxy (optional)
  • pytest - Testing framework

πŸ“‹ Requirements

Untuk Production

  • Docker 20.10+
  • Docker Compose 2.0+

Untuk Development

  • Python 3.11+
  • Flask 2.3.3+
  • pip atau conda

πŸš€ Quick Start

1️⃣ Clone Repository

git clone https://github.com/AbyanDimas/flask-prediction-app
cd flask-prediction-app

2️⃣ Pilih Metode Installation

🐍 Option A: Local Development

# 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

🐳 Option B: Docker (Recommended)

# 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

πŸ—οΈ Option C: Production dengan Docker

# 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

πŸ“š Usage Guide

🌐 Web Interface

  1. Akses aplikasi di browser: http://localhost:5000
  2. 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)
  3. Klik "Predict House Price" untuk mendapatkan estimasi harga
  4. Lihat hasil dengan confidence score dan breakdown harga

πŸ”Œ REST API Endpoints

Health Check

GET /api/health

Response:

{
  "status": "healthy",
  "model_loaded": true,
  "timestamp": "2024-01-15T10:30:00"
}

Prediksi Harga

POST /api/predict
Content-Type: application/json

Request 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
  }
}

Informasi Model

GET /api/model-info

Response:

{
  "model_type": "Random Forest Regressor",
  "features": ["area", "bedrooms", "bathrooms", "age", "location_score"],
  "version": "1.0.0",
  "last_trained": "2024-01-15T08:00:00"
}

πŸ’» Contoh Penggunaan API

cURL

# 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
  }'

Python

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%}")

JavaScript

// 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) + '%');
});

βš™οΈ Configuration

Environment Variables

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.0

Production Configuration

Untuk production, set environment variables melalui Docker atau system:

export FLASK_ENV=production
export FLASK_DEBUG=False
export SECRET_KEY=your-super-secret-production-key

πŸ—οΈ Architecture

Project Structure

flask-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

Component Overview

  • 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

Data Flow

  1. User Input β†’ Web form atau API request
  2. Validation β†’ Input validation dan sanitization
  3. Feature Processing β†’ Data transformation untuk model
  4. ML Prediction β†’ Random Forest model inference
  5. Response β†’ Formatted hasil dengan confidence score

πŸ” Model Details

Features Used

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

Model Performance

  • Algorithm: Random Forest Regressor
  • Features: 5 numerical features
  • Training Data: 1000 synthetic samples
  • Accuracy: ~85% (pada synthetic data)
  • Response Time: <100ms average

Confidence Score

Confidence score dihitung berdasarkan:

  • Model RΒ² score
  • Feature value reasonableness
  • Similarity dengan training data patterns

Development

Running Tests

Tests are organized using pytest.

pytest

Code Style

Code should adhere to PEP 8. Use flake8 and black for code style and formatting.

flake8 app
black app

Building the Model

Aplikasi 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!

About

Sebuah aplikasi web machine learning yang dibangun dengan Flask & Docker untuk memprediksi harga rumah berdasarkan berbagai fitur menggunakan model Random Forest.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages