BIproject / test_models.py
Asembris
added stacking model
428d4de
Raw History Blame Contribute Delete
13.1 kB
"""
Test script for both Classification and Regression models
Run this locally before pushing to Hugging Face
"""
import requests
import json
# Base URL - change this when testing locally vs HF Spaces
BASE_URL = "http://127.0.0.1:7860" # Local uvicorn
# BASE_URL = "https://shiverdeath-biproject.hf.space" # HF Spaces
def test_classification():
"""Test the RandomForest Classification model"""
print("\n" + "="*60)
print("Testing CLASSIFICATION Model (randomforest)")
print("="*60)
url = f"{BASE_URL}/predict/randomforest"
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": "winter",
"end_season": "winter",
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"volunteer_class_reduced": "D_LARGE",
"income_government": 23.879876,
"income_other_public_bodies": 17.300344,
"income_philanthropic_orgs": 15.320921,
"income_donations": 16.220201,
"income_trading_commercial": 19.731279,
"income_other_sources": 19.996591,
"income_bequests": 0.0,
"gross_income": 23.917578,
"gross_expenditure": 23.923207,
"other_assets": 22.73303,
"total_assets": 22.777331,
"net_assets_liabilities": 22.229597,
"total_liabilities": 21.913968,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… Classification Result: {result['predicted_class']}")
print(f" Confidence: {result.get('prediction_confidence', 'N/A')}")
except Exception as e:
print(f"❌ Error: {e}")
def test_regression():
"""Test the Regression model for Income: Other Sources"""
print("\n" + "="*60)
print("Testing REGRESSION Model (regression_other_sources)")
print("="*60)
url = f"{BASE_URL}/predict_regression/regression_other_sources"
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": "winter",
"end_season": "winter",
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"volunteer_class_reduced": "D_LARGE",
"number_employees_class_reduced": "D_LARGE",
"income_government": 23.8799,
"income_other_public_bodies": 17.3003,
"income_philanthropic_orgs": 15.3209,
"income_donations": 16.2202,
"income_trading_commercial": 19.7313,
"income_bequests": 0.0,
"gross_income": 23.9176,
"gross_expenditure": 23.9232,
"other_assets": 22.7339,
"total_assets": 22.7773,
"net_assets_liabilities": 22.2296,
"total_liabilities": 21.9140,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… Regression Result: {result['predicted_value']:.4f}")
print(f" Target: {result['target_name']}")
except Exception as e:
print(f"❌ Error: {e}")
def test_binary_classification():
"""Test the Binary Classification model for Donation Range"""
print("\n" + "="*60)
print("Testing BINARY CLASSIFICATION Model (donation_range)")
print("="*60)
url = f"{BASE_URL}/predict_binary/donation_range"
# Encoding reference:
# start_season/end_season: winter=0, spring=1, summer=2, autumn=3
# volunteer_class_reduced/number_employees_class_reduced: A_NONE=0, B_SMALL=1, C_MEDIUM=2, D_LARGE=3
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": 0, # winter=0
"end_season": 0, # winter=0
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"volunteer_class_reduced": 3, # D_LARGE=3
"number_employees_class_reduced": 3, # D_LARGE=3
"income_government": 23.8799,
"income_other_public_bodies": 17.3003,
"income_philanthropic_orgs": 15.3209,
"income_trading_commercial": 19.7313,
"income_other_sources": 19.9966,
"income_bequests": 0.0,
"gross_income": 23.9176,
"gross_expenditure": 23.9232,
"other_assets": 22.7339,
"total_assets": 22.7773,
"net_assets_liabilities": 22.2296,
"total_liabilities": 21.9140,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… Binary Classification Result: {result['predicted_class']}")
print(f" Confidence: {result.get('prediction_confidence', 'N/A')}")
if result.get('all_probabilities'):
print(f" Probabilities: {result['all_probabilities']}")
except Exception as e:
print(f"❌ Error: {e}")
def test_xgboost():
"""Test the XGBoost Regression model for Gross Income"""
print("\n" + "="*60)
print("Testing XGBOOST Model (xgboost_gross_income)")
print("="*60)
url = f"{BASE_URL}/predict_xgboost/xgboost_gross_income"
# XGBoost uses string categories (encoded automatically by API)
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": "winter",
"end_season": "winter",
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"volunteer_class_reduced": "D_LARGE",
"number_employees_class_reduced": "D_LARGE",
"income_government": 23.8799,
"income_other_public_bodies": 17.3003,
"income_philanthropic_orgs": 15.3209,
"income_donations": 16.2202,
"income_trading_commercial": 19.7313,
"income_other_sources": 19.9966,
"income_bequests": 0.0,
"gross_expenditure": 23.9232,
"other_assets": 22.7339,
"total_assets": 22.7773,
"net_assets_liabilities": 22.2296,
"total_liabilities": 21.9140,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… XGBoost Result: {result['predicted_value']:.4f}")
print(f" Target: {result['target_name']}")
# Convert log to actual value
import math
actual_value = math.exp(result['predicted_value'])
print(f" Estimated Actual: €{actual_value:,.2f}")
except Exception as e:
print(f"❌ Error: {e}")
def test_donations():
"""Test the XGBoost Donations model for Income: Donations"""
print("\n" + "="*60)
print("Testing XGBOOST DONATIONS Model (xgboost_donations)")
print("="*60)
url = f"{BASE_URL}/predict_donations/xgboost_donations"
# Seif model uses string categories with dynamic preprocessing
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": "winter",
"end_season": "winter",
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"volunteer_class_reduced": "D_LARGE",
"number_employees_class_reduced": "D_LARGE",
"income_government": 23.8799,
"income_other_public_bodies": 17.3003,
"income_philanthropic_orgs": 15.3209,
"income_trading_commercial": 19.7313,
"income_other_sources": 19.9966,
"income_bequests": 0.0,
"gross_income": 23.9176,
"gross_expenditure": 23.9232,
"other_assets": 22.7339,
"total_assets": 22.7773,
"net_assets_liabilities": 22.2296,
"total_liabilities": 21.9140,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… Donations Result: {result['predicted_value']:.4f}")
print(f" Target: {result['target_name']}")
import math
actual_value = math.exp(result['predicted_value'])
print(f" Estimated Actual: €{actual_value:,.2f}")
except Exception as e:
print(f"❌ Error: {e}")
def test_stacking():
"""Test the Stacking Ensemble model for Volunteer Classification"""
print("\n" + "="*60)
print("Testing STACKING Model (stacking_volunteer)")
print("="*60)
url = f"{BASE_URL}/predict_stacking/stacking_volunteer"
# Stacking uses label-encoded integers for categorical features
payload = {
"surplus_deficit": -137699000.0,
"cash_at_hand": 331570000.0,
"start_season": 3, # winter=3
"end_season": 3,
"gross_income_schools": 0,
"gross_expenditure_schools": 0,
"number_employees_class_reduced": 3, # D_LARGE=3
"income_government": 23.879876,
"income_other_public_bodies": 17.300344,
"income_philanthropic_orgs": 15.320921,
"income_donations": 16.220201,
"income_trading_commercial": 19.731279,
"income_other_sources": 19.996591,
"income_bequests": 0.0,
"gross_income": 23.917578,
"gross_expenditure": 23.923207,
"other_assets": 22.73389,
"total_assets": 22.777331,
"net_assets_liabilities": 22.229597,
"total_liabilities": 21.913968,
"arts_culture": 0,
"charity_sector_support": 0,
"community_development": 0,
"education_youth": 0,
"environment_animals": 0,
"health_welfare": 1,
"international_aid": 0,
"poverty_housing": 0,
"religion": 0
}
try:
response = requests.post(url, json=payload)
print(f"Status: {response.status_code}")
result = response.json()
print(json.dumps(result, indent=2))
if response.status_code == 200:
print(f"\nβœ… Stacking Result: {result['predicted_class']}")
print(f" Confidence: {result.get('prediction_confidence', 'N/A')}")
if result.get('all_probabilities'):
print(f" Probabilities: {result['all_probabilities']}")
except Exception as e:
print(f"❌ Error: {e}")
def test_api_health():
"""Test API health and list models"""
print("\n" + "="*60)
print("Testing API Health & Models")
print("="*60)
try:
# Root endpoint
response = requests.get(f"{BASE_URL}/")
print(f"Root: {response.json()}")
# Models endpoint
response = requests.get(f"{BASE_URL}/models")
print(f"Models: {response.json()}")
# Health
response = requests.get(f"{BASE_URL}/health")
print(f"Health: {response.json()}")
except Exception as e:
print(f"❌ Error connecting to API: {e}")
if __name__ == "__main__":
print("\nπŸ”¬ CHARITY PREDICTION API - TEST SUITE πŸ”¬")
test_api_health()
test_classification()
test_regression()
test_binary_classification()
test_xgboost()
test_donations()
test_stacking()
print("\n" + "="*60)
print("βœ… All tests completed!")
print("="*60)