Skip to content

API REFERENCE

SRIJA DE CHOWDHURY edited this page Dec 29, 2025 · 1 revision

🔌 API Reference

Complete API Documentation

API Version Python REST


📑 Table of Contents

🐍 Python API

🌐 REST API


🐍 Python API

📦 DepressionPredictor Class

Main class for all model operations.

class DepressionPredictor: 
    """
    Advanced Depression Predictor Model
    
    A deep learning model for predicting depression indicators
    based on demographic, behavioral, and symptom features.
    """

Constructor

__init__(model_path=None, config=None, preprocessor=None)
Parameter Type Default Description
model_path str | None None Path to pre-trained model file (. h5)
config str | dict | None None Configuration file path or dictionary
preprocessor Preprocessor | None None Custom preprocessor instance

Examples:

# Basic initialization
model = DepressionPredictor()

# Load pre-trained model
model = DepressionPredictor(model_path='models/best_model.h5')

# With config file
model = DepressionPredictor(config='config/production.yml')

# With custom preprocessor
from depression_predictor.preprocessing import CustomPreprocessor
preprocessor = CustomPreprocessor()
model = DepressionPredictor(preprocessor=preprocessor)

Returns: DepressionPredictor instance

Raises:

  • FileNotFoundError - If model_path doesn't exist
  • ValueError - If config is invalid

predict()

predict(data, return_proba=False, batch_size=32)

Make predictions on input data.

Parameter Type Default Description
data DataFrame | ndarray Required Input features
return_proba bool False Return probabilities instead of classes
batch_size int 32 Batch size for prediction

Returns:

  • If return_proba=False: np.ndarray of predictions (0 or 1)
  • If return_proba=True: np.ndarray of probabilities (0.0 to 1.0)

Example:

import pandas as pd

# Load data
data = pd.read_csv('data.csv')

# Get class predictions
predictions = model.predict(data)
# Output: array([0, 1, 0, 1, ... ])

# Get probabilities
probabilities = model.predict(data, return_proba=True)
# Output: array([0.23, 0.76, 0.12, 0.89, ...])

Raises:

  • ValueError - If data shape is invalid
  • TypeError - If data type is unsupported

predict_single()

predict_single(sample, explain=False)

Predict for a single sample with detailed results.

Parameter Type Default Description
sample dict Required Feature dictionary
explain bool False Include prediction explanation

Returns: dict with keys:

  • prediction: int (0 or 1)
  • probability: float (0.0 to 1.0)
  • confidence: str ('low', 'medium', 'high')
  • risk_level: str ('minimal', 'low', 'moderate', 'elevated', 'high')
  • timestamp: str (ISO format)
  • explanation: dict (if explain=True)

Example:

sample = {
    'age': 28,
    'gender': 'female',
    'sleep_hours': 5.5,
    'mood_score': 3,
    # ... other features
}

result = model.predict_single(sample, explain=True)

print(f"""
Prediction:  {result['prediction']}
Probability: {result['probability']:. 1%}
Confidence: {result['confidence']}
Risk Level: {result['risk_level']}
""")

# With explanation
if 'explanation' in result:
    print(f"Top Feature:  {result['explanation']['top_features'][0]}")

train()

train(X, y, validation_data=None, epochs=100, batch_size=32, 
      callbacks=None, verbose=1)

Train the model on provided data.

Parameter Type Default Description
X DataFrame | ndarray Required Training features
y Series | ndarray Required Training labels
validation_data tuple | None None (X_val, y_val) for validation
epochs int 100 Number of training epochs
batch_size int 32 Training batch size
callbacks list | None None Keras callbacks
verbose int 1 Verbosity mode (0, 1, 2)

Returns: History object containing training metrics

Example:

from sklearn.model_selection import train_test_split

# Split data
X_train, X_val, y_train, y_val = train_test_split(
    X, y, test_size=0.2, random_state=42
)

# Train model
history = model.train(
    X_train, y_train,
    validation_data=(X_val, y_val),
    epochs=100,
    batch_size=32
)

# Plot training history
import matplotlib.pyplot as plt
plt.plot(history.history['accuracy'], label='Training')
plt.plot(history.history['val_accuracy'], label='Validation')
plt.legend()
plt.show()

evaluate()

evaluate(X_test, y_test, return_predictions=False)

Evaluate model performance on test data.

Parameter Type Default Description
X_test DataFrame | ndarray Required Test features
y_test Series | ndarray Required True labels
return_predictions bool False Also return predictions

Returns: dict with metrics:

  • accuracy: float
  • precision: float
  • recall: float
  • f1_score: float
  • auc: float
  • confusion_matrix: ndarray
  • predictions: ndarray (if return_predictions=True)

Example:

results = model.evaluate(X_test, y_test, return_predictions=True)

print(f"""
Model Performance:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Accuracy:    {results['accuracy']:.2%}
Precision:  {results['precision']:.2%}
Recall:     {results['recall']:.2%}
F1 Score:   {results['f1_score']:.2%}
AUC:        {results['auc']:.3f}
""")

save()

save(filepath, save_weights_only=False, include_optimizer=True)

Save the model to disk.

Parameter Type Default Description
filepath str Required Path to save model (. h5 or .keras)
save_weights_only bool False Save only weights (not architecture)
include_optimizer bool True Include optimizer state

Example:

# Save complete model
model.save('models/my_model.h5')

# Save weights only
model.save('models/weights.h5', save_weights_only=True)

# Save without optimizer (smaller file)
model.save('models/inference_model.h5', include_optimizer=False)

load()

load(filepath, compile=True)

Load a model from disk.

Parameter Type Default Description
filepath str Required Path to saved model
compile bool True Compile the model after loading

Example:

model = DepressionPredictor()
model.load('models/best_model.h5')

📊 Data Loading

from depression_predictor.data import (
    load_dataset,
    load_sample_data,
    DataGenerator
)

load_dataset()

load_dataset(dataset_type='train', path=None)

Load training or testing dataset.

Parameters:

  • dataset_type: str - 'train' or 'test'
  • path: str | None - Custom dataset path

Returns: tuple - (X, y)

Example:

# Load training data
X_train, y_train = load_dataset('train')

# Load test data
X_test, y_test = load_dataset('test')

# Load custom dataset
X_custom, y_custom = load_dataset(path='data/custom.csv')

load_sample_data()

load_sample_data(n_samples=100, random_state=42)

Load sample data for testing.

Example:

# Get 100 sample rows
X_sample, y_sample = load_sample_data(n_samples=100)

🔧 Preprocessing

from depression_predictor.preprocessing import (
    Preprocessor,
    FeatureScaler,
    FeatureEncoder
)

Preprocessor Class

class Preprocessor:
    def fit(X, y=None)
    def transform(X)
    def fit_transform(X, y=None)
    def inverse_transform(X)

Example:

from depression_predictor.preprocessing import Preprocessor

# Create preprocessor
preprocessor = Preprocessor()

# Fit on training data
preprocessor.fit(X_train)

# Transform test data
X_test_processed = preprocessor.transform(X_test)

📊 Visualization

from depression_predictor.visualization import (
    plot_predictions,
    plot_feature_importance,
    plot_confusion_matrix,
    plot_roc_curve,
    plot_training_history
)

All visualization functions follow this pattern:

def plot_function(data, save_path=None, show=True, **kwargs)

Example:

# Plot and save
plot_confusion_matrix(
    y_true=y_test,
    y_pred=predictions,
    save_path='plots/confusion. png',
    show=True,
    figsize=(8, 6)
)

🌐 REST API

Base URL

http://localhost:5000/api/v1

🎯 Prediction Endpoints

POST /predict

Make a single prediction.

Request:

POST /api/v1/predict
Content-Type: application/json
{
  "age": 28,
  "gender": "female",
  "sleep_hours": 5.5,
  "activity_level": "low",
  "mood_score":  3,
  "energy_level": 2,
  "concentration": 4
  // ... other 43 features
}

Response: 200 OK

{
  "status": "success",
  "prediction": 1,
  "probability": 0.763,
  "confidence": "high",
  "risk_level":  "elevated",
  "timestamp": "2025-12-29T10:30:00Z",
  "model_version": "1.0.0",
  "processing_time_ms": 42
}

cURL Example:

curl -X POST http://localhost:5000/api/v1/predict \
  -H "Content-Type: application/json" \
  -d '{
    "age": 28,
    "gender": "female",
    "sleep_hours": 5.5,
    "mood_score": 3
  }'

Python Example:

import requests

url = "http://localhost:5000/api/v1/predict"
data = {
    "age": 28,
    "gender": "female",
    "sleep_hours": 5.5,
    "mood_score": 3
}

response = requests. post(url, json=data)
result = response.json()
print(f"Prediction: {result['prediction']}")

POST /batch-predict

Make batch predictions.

Request:

{
  "samples": [
    {"age": 28, "sleep_hours": 5.5, ... },
    {"age": 45, "sleep_hours": 7. 0, ...},
    {"age": 32, "sleep_hours": 6.0, ...}
  ],
  "return_probabilities": true
}

Response: 200 OK

{
  "status": "success",
  "total_samples": 3,
  "predictions": [
    {
      "id": 0,
      "prediction": 1,
      "probability": 0.763,
      "confidence":  "high"
    },
    {
      "id": 1,
      "prediction": 0,
      "probability": 0.234,
      "confidence":  "high"
    },
    {
      "id": 2,
      "prediction": 0,
      "probability": 0.412,
      "confidence": "medium"
    }
  ],
  "processing_time_ms": 145
}

🔍 Model Endpoints

GET /model/info

Get model information.

Response: 200 OK

{
  "model_name": "Advanced Depression Predictor",
  "version": "1.0.0",
  "architecture": "deep_neural_network",
  "performance":  {
    "accuracy": 0.892,
    "precision": 0.875,
    "recall": 0.853,
    "f1_score": 0.864,
    "auc": 0.920
  },
  "training_info": {
    "last_trained": "2025-12-01T00:00:00Z",
    "training_samples": 8000,
    "epochs_trained": 87
  },
  "features":  {
    "total":  50,
    "categories": ["demographic", "behavioral", "symptom", "clinical"]
  },
  "model_size_mb": 15.2,
  "total_parameters": 12789
}

GET /model/features

Get list of required features.

Response: 200 OK

{
  "total_features": 50,
  "features": [
    {
      "name": "age",
      "type": "numerical",
      "range": [18, 80],
      "required": true
    },
    {
      "name": "gender",
      "type": "categorical",
      "values": ["male", "female", "other"],
      "required": true
    }
    // ... other 48 features
  ]
}

💚 Health & Status

GET /health

Health check endpoint.

Response: 200 OK

{
  "status": "healthy",
  "version": "1.0.0",
  "uptime_seconds": 3600,
  "timestamp": "2025-12-29T10:30:00Z"
}

GET /status

Detailed status information.

Response: 200 OK

{
  "status": "operational",
  "services": {
    "model":  "loaded",
    "database": "connected",
    "cache": "active"
  },
  "metrics": {
    "total_predictions": 15234,
    "predictions_today": 892,
    "average_response_time_ms": 48
  },
  "system": {
    "cpu_usage": 35.2,
    "memory_usage":  1024,
    "disk_space_gb": 45.3
  }
}

⚠️ Error Handling

Error Response Format

{
  "status": "error",
  "error": {
    "code": "ERROR_CODE",
    "message":  "Human readable error message",
    "details": "Additional technical details"
  },
  "timestamp": "2025-12-29T10:30:00Z"
}

Error Codes

Code HTTP Status Description
INVALID_INPUT 400 Missing or invalid input features
MISSING_FEATURES 400 Required features not provided
INVALID_FORMAT 400 Invalid JSON or data format
MODEL_ERROR 500 Error during model prediction
SERVER_ERROR 500 Internal server error
NOT_FOUND 404 Endpoint not found
RATE_LIMIT_EXCEEDED 429 Too many requests

Example Error Response:

{
  "status": "error",
  "error": {
    "code": "MISSING_FEATURES",
    "message": "Required features are missing",
    "details": "Missing features: ['sleep_hours', 'mood_score']"
  },
  "timestamp": "2025-12-29T10:30:00Z"
}

🔐 Authentication

For production deployments, use API key authentication:

Request Header:

Authorization: Bearer YOUR_API_KEY

Example:

curl -X POST http://localhost:5000/api/v1/predict \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"age": 28, ... }'

📊 Rate Limiting

Plan Requests/Minute Requests/Day
Free 60 1,000
Basic 300 10,000
Pro 1,000 100,000

Rate Limit Headers:

X-RateLimit-Limit: 60
X-RateLimit-Remaining: 45
X-RateLimit-Reset: 1640781600

📚 Additional Resources

📖 Related Docs

🔗 Quick Links


Clone this wiki locally