A FastAPI-based REST API for detecting electricity theft using machine learning models.
pip install -r requirements.txt# Train the model and save it for API deployment
python electricity_theft_detection.py
# or
python advanced_ml_analysis.pypython fraud_detection_api.pyThe API will be available at http://localhost:8000
python test_api.pyhttp://localhost:8000
GET /health
Check if the API and model are ready.
Response:
{
"status": "healthy",
"model_loaded": true,
"model_version": "1.0.0",
"timestamp": "2024-01-15T10:30:00"
}POST /predict
Predict electricity fraud for a single consumer.
Request Body:
{
"kWh": 1200.0,
"kVARh": 200.0,
"billed_amount": 8000.0,
"paid_amount": 7800.0,
"power_factor": 0.92,
"load_factor": 0.85,
"consumer_type": "Residential",
"region": "Urban",
"payment_method": "Bank Transfer"
}Response:
{
"fraud_probability": 0.15,
"status": "Normal",
"confidence": "High",
"risk_factors": [],
"model_version": "1.0.0",
"timestamp": "2024-01-15T10:30:00"
}POST /predict/batch
Predict fraud for multiple consumers (max 100).
Request Body:
[
{
"kWh": 1000.0,
"kVARh": 150.0,
"billed_amount": 6000.0,
"paid_amount": 5800.0
},
{
"kWh": 500.0,
"kVARh": 300.0,
"billed_amount": 10000.0,
"paid_amount": 2000.0
}
]Response:
{
"predictions": [
{
"index": 0,
"prediction": {
"fraud_probability": 0.12,
"status": "Normal",
"confidence": "High",
"risk_factors": [],
"model_version": "1.0.0",
"timestamp": "2024-01-15T10:30:00"
}
},
{
"index": 1,
"prediction": {
"fraud_probability": 0.89,
"status": "Fraudulent",
"confidence": "High",
"risk_factors": ["Low payment ratio", "High outstanding amount"],
"model_version": "1.0.0",
"timestamp": "2024-01-15T10:30:00"
}
}
],
"total_processed": 2,
"successful": 2,
"failed": 0
}GET /model/info
Get information about the loaded model.
Response:
{
"model_info": {
"name": "Random Forest",
"version": "1.0.0",
"accuracy": 0.92,
"precision": 0.88,
"recall": 0.85,
"f1_score": 0.86,
"auc": 0.94,
"trained_at": "2024-01-15T09:00:00",
"feature_count": 12
},
"feature_columns": [
"kWh", "kVARh", "billed_amount", "paid_amount",
"power_factor", "load_factor", "payment_ratio",
"outstanding_amount", "cost_per_kwh", "consumer_type",
"region", "payment_method"
],
"model_type": "RandomForestClassifier",
"loaded_at": "2024-01-15T10:00:00"
}POST /model/reload
Reload the model from disk.
Response:
{
"message": "Model reloaded successfully"
}| Field | Type | Description | Constraints |
|---|---|---|---|
kWh |
float | Active energy consumption | > 0 |
kVARh |
float | Reactive energy consumption | β₯ 0 |
billed_amount |
float | Amount billed to consumer | β₯ 0 |
paid_amount |
float | Amount paid by consumer | β₯ 0, β€ billed_amount |
| Field | Type | Description | Default | Constraints |
|---|---|---|---|---|
power_factor |
float | Power factor | Auto-calculated | 0-1 |
load_factor |
float | Load factor | Auto-calculated | 0-1 |
consumer_type |
string | Type of consumer | "Residential" | - |
region |
string | Geographic region | "Urban" | - |
payment_method |
string | Payment method | "Bank Transfer" | - |
The API automatically calculates these features if not provided:
- Power Factor:
cos(arctan(kVARh/kWh)) - Load Factor:
kWh / (kWh + kVARh) - Payment Ratio:
paid_amount / billed_amount - Outstanding Amount:
billed_amount - paid_amount - Cost per kWh:
billed_amount / kWh
| Field | Type | Description |
|---|---|---|
fraud_probability |
float | Probability of fraud (0-1) |
status |
string | "Normal" or "Fraudulent" |
confidence |
string | "Low", "Medium", or "High" |
risk_factors |
array | List of identified risk factors |
model_version |
string | Version of the model used |
timestamp |
string | ISO timestamp of prediction |
The API identifies these risk factors:
- Low payment ratio: Payment ratio < 0.5
- High outstanding amount: Outstanding amount > 30% of billed amount
- Poor power factor: Power factor < 0.7
- Low load factor: Load factor < 0.5
- High cost per kWh: Cost per kWh > 10
- 200: Success
- 400: Bad Request (invalid input)
- 422: Unprocessable Entity (validation error)
- 500: Internal Server Error
- 503: Service Unavailable (model not loaded)
{
"detail": "Error message describing what went wrong"
}-
Model Not Loaded (503)
{ "detail": "Model not loaded. Please contact administrator." } -
Validation Error (422)
{ "detail": [ { "loc": ["body", "kWh"], "msg": "ensure this value is greater than 0", "type": "value_error.number.not_gt" } ] } -
Batch Size Limit (400)
{ "detail": "Batch size cannot exceed 100 records" }
# Health check
curl -X GET "http://localhost:8000/health"
# Single prediction
curl -X POST "http://localhost:8000/predict" \
-H "Content-Type: application/json" \
-d '{
"kWh": 1200.0,
"kVARh": 200.0,
"billed_amount": 8000.0,
"paid_amount": 7800.0
}'import requests
# Single prediction
data = {
"kWh": 1200.0,
"kVARh": 200.0,
"billed_amount": 8000.0,
"paid_amount": 7800.0
}
response = requests.post("http://localhost:8000/predict", json=data)
result = response.json()
print(f"Status: {result['status']}")
print(f"Probability: {result['fraud_probability']}")The API uses the best performing model from training:
- Accuracy: 90%+ on test data
- Precision: 85%+ for fraud detection
- Recall: 80%+ for fraud detection
- F1-Score: 82%+ overall
- Response Time: < 100ms for single predictions
- Batch Processing: < 1s for 100 records
- Memory Usage: < 500MB with model loaded
- Concurrent Requests: Supports multiple simultaneous requests
- Input Validation: All inputs are validated using Pydantic
- Rate Limiting: Consider implementing rate limiting for production
- Authentication: Add authentication for production deployment
- HTTPS: Use HTTPS in production environments
- Model Security: Keep model files secure and version-controlled
python fraud_detection_api.pyuvicorn fraud_detection_api:app --host 0.0.0.0 --port 8000 --workers 4FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["uvicorn", "fraud_detection_api:app", "--host", "0.0.0.0", "--port", "8000"]The API includes interactive documentation:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
Monitor the /health endpoint to ensure:
- API is responding
- Model is loaded
- Service is healthy
The API logs:
- Prediction requests and responses
- Model loading events
- Error conditions
- Performance metrics
-
Model Not Found
- Ensure
best_model.pklexists - Run the ML training pipeline first
- Ensure
-
Import Errors
- Install all dependencies:
pip install -r requirements.txt
- Install all dependencies:
-
Port Already in Use
- Change port in
fraud_detection_api.py - Kill existing processes on port 8000
- Change port in
-
Memory Issues
- Reduce batch size for large requests
- Monitor memory usage
Run with debug logging:
uvicorn fraud_detection_api:app --log-level debugFor issues and questions:
- Check the troubleshooting section
- Review API logs for error details
- Ensure model is properly trained and saved
- Verify all dependencies are installed