Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

🔖 Checkpoint: Edit /workspaces/claude-code-flow/ml_foundation/evaluation/evaluator.py

rUv12fa8a0a4446
diff --git a/.claude/checkpoints/1754320218.json b/.claude/checkpoints/1754320218.json
new file mode 100644
index 0000000000..dd4e077863
--- /dev/null
+++ b/.claude/checkpoints/1754320218.json
@@ -0,0 +1 @@
+{"branch": "checkpoint/pre-edit-20250804-151018", "file": "/workspaces/claude-code-flow/validation_report.md", "timestamp": "2025-08-04T15:10:18Z", "type": "pre-edit", "original_branch": "alpha-85"}
diff --git a/.claude/checkpoints/1754320219.json b/.claude/checkpoints/1754320219.json
new file mode 100644
index 0000000000..71dff41ad9
--- /dev/null
+++ b/.claude/checkpoints/1754320219.json
@@ -0,0 +1 @@
+{"tag": "checkpoint-20250804-151019", "file": "/workspaces/claude-code-flow/ml_foundation/pipelines/data_pipeline.py", "timestamp": "2025-08-04T15:10:19Z", "type": "post-edit", "branch": "alpha-85", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/task-metrics.json | 6 +- claude-flow-wiki | 0 ml_foundation/pipelines/data_pipeline.py | 490 +++++++++++++++++++++++++++++++ 4 files changed, 494 insertions(+), 4 deletions(-) "}
diff --git a/.claude/checkpoints/1754320220.json b/.claude/checkpoints/1754320220.json
new file mode 100644
index 0000000000..cc7758a06e
--- /dev/null
+++ b/.claude/checkpoints/1754320220.json
@@ -0,0 +1 @@
+{"tag": "checkpoint-20250804-151020", "file": "/workspaces/claude-code-flow/validation_report.md", "timestamp": "2025-08-04T15:10:20Z", "type": "post-edit", "branch": "alpha-85", "diff_summary": " .claude-flow/metrics/performance.json | 2 +- .claude-flow/metrics/task-metrics.json | 6 +- claude-flow-wiki | 0 validation_report.md | 393 +++++++++++++++++++++++++++++++++ 4 files changed, 397 insertions(+), 4 deletions(-) "}
diff --git a/examples/automation-examples.md b/examples/automation-examples.md
new file mode 100644
index 0000000000..d8bb1b2065
--- /dev/null
+++ b/examples/automation-examples.md
@@ -0,0 +1,717 @@
+# Claude Flow Automation Examples
+
+This document provides practical examples of using Claude Flow's automation features.
+
+## Quick Start Examples
+
+### 1. Basic MLE-STAR Workflow
+
+```bash
+# Simple ML engineering workflow
+claude-flow automation mle-star \
+ --dataset data/house_prices.csv \
+ --target price \
+ --claude \
+ --name "house-price-prediction"
+```
+
+This will:
+1. Search web for house price prediction approaches
+2. Analyze your dataset characteristics
+3. Build foundation models based on research
+4. Perform ablation analysis to identify high-impact components
+5. Refine the most impactful components
+6. Create intelligent ensemble models
+7. Validate with comprehensive testing
+8. Prepare for production deployment
+
+### 2. Custom Dataset with Advanced Options
+
+```bash
+# Advanced ML workflow with custom configuration
+claude-flow automation mle-star \
+ --dataset sales_data.csv \
+ --target quarterly_revenue \
+ --output models/sales-forecast/ \
+ --name "q4-sales-forecast" \
+ --search-iterations 5 \
+ --refinement-iterations 8 \
+ --max-agents 8 \
+ --claude \
+ --non-interactive
+```
+
+### 3. CI/CD Integration
+
+```bash
+# Use in CI/CD pipeline
+export DATASET_PATH="data/production_data.csv"
+export TARGET_COLUMN="conversion_rate"
+export BUILD_ID="build-$(date +%Y%m%d-%H%M%S)"
+
+claude-flow automation mle-star \
+ --dataset "$DATASET_PATH" \
+ --target "$TARGET_COLUMN" \
+ --name "$BUILD_ID-model" \
+ --output "artifacts/models/" \
+ --claude \
+ --non-interactive \
+ --timeout 14400000 # 4 hours
+```
+
+## Custom Workflow Examples
+
+### Example 1: Web Application Development
+
+Create `web-app-workflow.json`:
+
+```json
+{
+ "name": "Full-Stack Web Application",
+ "version": "1.0.0",
+ "description": "Complete web application development workflow",
+ "variables": {
+ "app_name": "my-web-app",
+ "database": "postgresql",
+ "framework": "react"
+ },
+ "agents": [
+ {
+ "id": "architect",
+ "type": "architect",
+ "name": "System Architect",
+ "config": {
+ "capabilities": ["system_design", "architecture_planning", "technology_selection"],
+ "focus": "scalable_web_applications"
+ }
+ },
+ {
+ "id": "backend_dev",
+ "type": "coder",
+ "name": "Backend Developer",
+ "config": {
+ "capabilities": ["api_development", "database_design", "server_configuration"],
+ "languages": ["python", "javascript", "sql"],
+ "frameworks": ["fastapi", "express", "django"]
+ }
+ },
+ {
+ "id": "frontend_dev",
+ "type": "coder",
+ "name": "Frontend Developer",
+ "config": {
+ "capabilities": ["ui_development", "responsive_design", "state_management"],
+ "languages": ["javascript", "typescript", "css"],
+ "frameworks": ["react", "vue", "angular"]
+ }
+ },
+ {
+ "id": "tester",
+ "type": "tester",
+ "name": "QA Engineer",
+ "config": {
+ "capabilities": ["unit_testing", "integration_testing", "e2e_testing"],
+ "tools": ["jest", "cypress", "playwright"]
+ }
+ }
+ ],
+ "tasks": [
+ {
+ "id": "system_design",
+ "name": "System Architecture Design",
+ "type": "planning",
+ "description": "Design overall system architecture and technology stack",
+ "assignTo": "architect",
+ "timeout": 1800,
+ "input": {
+ "requirements": "Build scalable web application with ${framework} frontend and ${database} database"
+ },
+ "output": {
+ "architecture_diagram": "object",
+ "technology_stack": "object",
+ "deployment_plan": "object"
+ }
+ },
+ {
+ "id": "database_setup",
+ "name": "Database Design and Setup",
+ "type": "implementation",
+ "description": "Create database schema and setup scripts",
+ "assignTo": "backend_dev",
+ "depends": ["system_design"],
+ "timeout": 1200,
+ "input": {
+ "architecture": "${system_design.output.architecture_diagram}",
+ "database_type": "${database}"
+ }
+ },
+ {
+ "id": "api_development",
+ "name": "REST API Development",
+ "type": "implementation",
+ "description": "Develop REST API endpoints and business logic",
+ "assignTo": "backend_dev",
+ "depends": ["database_setup"],
+ "timeout": 2400,
+ "input": {
+ "database_schema": "${database_setup.output}",
+ "api_requirements": "${system_design.output.api_specification}"
+ }
+ },
+ {
+ "id": "frontend_development",
+ "name": "Frontend Application Development",
+ "type": "implementation",
+ "description": "Build responsive frontend application",
+ "assignTo": "frontend_dev",
+ "depends": ["api_development"],
+ "timeout": 2400,
+ "input": {
+ "api_endpoints": "${api_development.output}",
+ "ui_framework": "${framework}"
+ }
+ },
+ {
+ "id": "testing_suite",
+ "name": "Comprehensive Testing Suite",
+ "type": "testing",
+ "description": "Create unit, integration, and e2e tests",
+ "assignTo": "tester",
+ "depends": ["frontend_development"],
+ "timeout": 1800,
+ "input": {
+ "application_code": "${frontend_development.output}",
+ "api_code": "${api_development.output}"
+ }
+ },
+ {
+ "id": "deployment_prep",
+ "name": "Production Deployment Preparation",
+ "type": "deployment",
+ "description": "Prepare application for production deployment",
+ "assignTo": "architect",
+ "depends": ["testing_suite"],
+ "timeout": 900,
+ "input": {
+ "tested_application": "${testing_suite.output}",
+ "deployment_plan": "${system_design.output.deployment_plan}"
+ }
+ }
+ ],
+ "settings": {
+ "maxConcurrency": 2,
+ "timeout": 14400,
+ "failurePolicy": "continue",
+ "quality_threshold": 0.9
+ }
+}
+```
+
+Execute the workflow:
+
+```bash
+claude-flow automation run-workflow web-app-workflow.json \
+ --claude \
+ --variables '{"app_name": "ecommerce-platform", "database": "postgresql", "framework": "react"}' \
+ --non-interactive
+```
+
+### Example 2: Data Science Research Project
+
+Create `research-workflow.json`:
+
+```json
+{
+ "name": "Data Science Research Project",
+ "version": "1.0.0",
+ "description": "Comprehensive data science research workflow",
+ "variables": {
+ "research_topic": "customer_churn_prediction",
+ "data_source": "customer_database",
+ "output_format": "research_paper"
+ },
+ "agents": [
+ {
+ "id": "literature_researcher",
+ "type": "researcher",
+ "name": "Literature Review Specialist",
+ "config": {
+ "capabilities": ["academic_search", "paper_analysis", "trend_identification"],
+ "search_databases": ["arxiv", "google_scholar", "pubmed"]
+ }
+ },
+ {
+ "id": "data_analyst",
+ "type": "analyst",
+ "name": "Data Analysis Expert",
+ "config": {
+ "capabilities": ["statistical_analysis", "data_visualization", "pattern_recognition"],
+ "tools": ["python", "r", "sql", "tableau"]
+ }
+ },
+ {
+ "id": "ml_engineer",
+ "type": "coder",
+ "name": "ML Model Developer",
+ "config": {
+ "capabilities": ["model_development", "feature_engineering", "hyperparameter_tuning"],
+ "frameworks": ["scikit-learn", "tensorflow", "pytorch", "xgboost"]
+ }
+ },
+ {
+ "id": "research_writer",
+ "type": "coordinator",
+ "name": "Research Documentation Specialist",
+ "config": {
+ "capabilities": ["technical_writing", "research_synthesis", "visualization"]
+ }
+ }
+ ],
+ "tasks": [
+ {
+ "id": "literature_review",
+ "name": "Comprehensive Literature Review",
+ "type": "research",
+ "description": "Review existing research on customer churn prediction methods",
+ "assignTo": "literature_researcher",
+ "timeout": 2400,
+ "input": {
+ "topic": "${research_topic}",
+ "focus_areas": ["machine_learning", "customer_analytics", "predictive_modeling"]
+ }
+ },
+ {
+ "id": "data_exploration",
+ "name": "Exploratory Data Analysis",
+ "type": "analysis",
+ "description": "Perform comprehensive EDA on customer data",
+ "assignTo": "data_analyst",
+ "depends": ["literature_review"],
+ "timeout": 1800,
+ "input": {
+ "data_source": "${data_source}",
+ "research_insights": "${literature_review.output}"
+ }
+ },
+ {
+ "id": "feature_engineering",
+ "name": "Advanced Feature Engineering",
+ "type": "implementation",
+ "description": "Create and select optimal features based on research and EDA",
+ "assignTo": "ml_engineer",
+ "depends": ["data_exploration"],
+ "timeout": 1800
+ },
+ {
+ "id": "model_development",
+ "name": "ML Model Development and Validation",
+ "type": "implementation",
+ "description": "Develop and validate multiple ML models",
+ "assignTo": "ml_engineer",
+ "depends": ["feature_engineering"],
+ "timeout": 3600
+ },
+ {
+ "id": "research_synthesis",
+ "name": "Research Paper Generation",
+ "type": "documentation",
+ "description": "Synthesize findings into comprehensive research paper",
+ "assignTo": "research_writer",
+ "depends": ["model_development"],
+ "timeout": 2400,
+ "input": {
+ "literature_review": "${literature_review.output}",
+ "data_analysis": "${data_exploration.output}",
+ "model_results": "${model_development.output}",
+ "output_format": "${output_format}"
+ }
+ }
+ ],
+ "settings": {
+ "maxConcurrency": 3,
+ "timeout": 18000,
+ "failurePolicy": "continue"
+ }
+}
+```
+
+### Example 3: DevOps Infrastructure Setup
+
+Create `devops-workflow.json`:
+
+```json
+{
+ "name": "DevOps Infrastructure Setup",
+ "version": "1.0.0",
+ "description": "Complete DevOps infrastructure deployment workflow",
+ "variables": {
+ "cloud_provider": "aws",
+ "environment": "production",
+ "app_name": "microservices-app"
+ },
+ "agents": [
+ {
+ "id": "infrastructure_architect",
+ "type": "architect",
+ "name": "Infrastructure Architect",
+ "config": {
+ "capabilities": ["cloud_architecture", "security_design", "cost_optimization"],
+ "cloud_platforms": ["aws", "azure", "gcp"]
+ }
+ },
+ {
+ "id": "devops_engineer",
+ "type": "coder",
+ "name": "DevOps Engineer",
+ "config": {
+ "capabilities": ["infrastructure_as_code", "ci_cd_pipelines", "container_orchestration"],
+ "tools": ["terraform", "ansible", "kubernetes", "docker"]
+ }
+ },
+ {
+ "id": "security_specialist",
+ "type": "tester",
+ "name": "Security Specialist",
+ "config": {
+ "capabilities": ["security_testing", "compliance_checking", "vulnerability_assessment"],
+ "tools": ["nessus", "owasp_zap", "sonarqube"]
+ }
+ }
+ ],
+ "tasks": [
+ {
+ "id": "infrastructure_design",
+ "name": "Infrastructure Architecture Design",
+ "type": "planning",
+ "description": "Design scalable and secure cloud infrastructure",
+ "assignTo": "infrastructure_architect",
+ "timeout": 1800,
+ "input": {
+ "cloud_provider": "${cloud_provider}",
+ "environment": "${environment}",
+ "requirements": "High availability, auto-scaling, security"
+ }
+ },
+ {
+ "id": "terraform_implementation",
+ "name": "Infrastructure as Code Implementation",
+ "type": "implementation",
+ "description": "Implement infrastructure using Terraform",
+ "assignTo": "devops_engineer",
+ "depends": ["infrastructure_design"],
+ "timeout": 2400
+ },
+ {
+ "id": "ci_cd_setup",
+ "name": "CI/CD Pipeline Setup",
+ "type": "implementation",
+ "description": "Create comprehensive CI/CD pipelines",
+ "assignTo": "devops_engineer",
+ "depends": ["terraform_implementation"],
+ "timeout": 1800
+ },
+ {
+ "id": "security_hardening",
+ "name": "Security Hardening and Testing",
+ "type": "testing",
+ "description": "Implement security measures and conduct testing",
+ "assignTo": "security_specialist",
+ "depends": ["ci_cd_setup"],
+ "timeout": 2400
+ },
+ {
+ "id": "monitoring_setup",
+ "name": "Monitoring and Alerting Setup",
+ "type": "implementation",
+ "description": "Setup comprehensive monitoring and alerting",
+ "assignTo": "devops_engineer",
+ "depends": ["security_hardening"],
+ "timeout": 1200
+ }
+ ],
+ "settings": {
+ "maxConcurrency": 2,
+ "timeout": 14400,
+ "failurePolicy": "fail-fast"
+ }
+}
+```
+
+## Advanced Usage Patterns
+
+### 1. Multi-Environment Deployment
+
+```bash
+# Development environment
+claude-flow automation run-workflow devops-workflow.json \
+ --variables '{"cloud_provider": "aws", "environment": "development"}' \
+ --claude
+
+# Production environment
+claude-flow automation run-workflow devops-workflow.json \
+ --variables '{"cloud_provider": "aws", "environment": "production"}' \
+ --claude \
+ --non-interactive
+```
+
+### 2. Conditional Execution
+
+Add conditions to tasks:
+
+```json
+{
+ "id": "deploy_to_production",
+ "condition": "${test_results.success} && ${security_scan.score} > 0.8",
+ "description": "Deploy only if tests pass and security score is high"
+}
+```
+
+### 3. Dynamic Agent Scaling
+
+Adjust agents based on workload:
+
+```bash
+# Light workload
+claude-flow automation mle-star --max-agents 3 --claude
+
+# Heavy workload
+claude-flow automation mle-star --max-agents 12 --claude
+```
+
+## Integration Examples
+
+### 1. GitHub Actions Integration
+
+`.github/workflows/ml-pipeline.yml`:
+
+```yaml
+name: ML Pipeline
+on:
+ push:
+ branches: [main]
+ schedule:
+ - cron: '0 2 * * *' # Daily at 2 AM
+
+jobs:
+ ml-training:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v3
+ with:
+ node-version: '20'
+
+ - name: Install Claude Flow
+ run: npm install -g claude-flow@alpha
+
+ - name: Run MLE-STAR Pipeline
+ run: |
+ claude-flow automation mle-star \
+ --dataset data/training_data.csv \
+ --target conversion_rate \
+ --name "github-action-${{ github.run_id }}" \
+ --output artifacts/models/ \
+ --non-interactive \
+ --timeout 7200000
+
+ - name: Upload Model Artifacts
+ uses: actions/upload-artifact@v3
+ with:
+ name: ml-models
+ path: artifacts/models/
+```
+
+### 2. Docker Integration
+
+`Dockerfile`:
+
+```dockerfile
+FROM node:20-alpine
+
+RUN npm install -g claude-flow@alpha
+
+WORKDIR /app
+COPY . .
+
+CMD ["claude-flow", "automation", "mle-star", \
+ "--dataset", "/data/dataset.csv", \
+ "--non-interactive", \
+ "--output", "/models/"]
+```
+
+### 3. Kubernetes Job
+
+`ml-job.yaml`:
+
+```yaml
+apiVersion: batch/v1
+kind: Job
+metadata:
+ name: ml-training-job
+spec:
+ template:
+ spec:
+ containers:
+ - name: ml-trainer
+ image: claude-flow:latest
+ command: ["claude-flow", "automation", "mle-star"]
+ args:
+ - "--dataset"
+ - "/data/dataset.csv"
+ - "--non-interactive"
+ - "--timeout"
+ - "14400000"
+ volumeMounts:
+ - name: data-volume
+ mountPath: /data
+ - name: models-volume
+ mountPath: /models
+ restartPolicy: Never
+ volumes:
+ - name: data-volume
+ persistentVolumeClaim:
+ claimName: training-data-pvc
+ - name: models-volume
+ persistentVolumeClaim:
+ claimName: models-pvc
+```
+
+## Troubleshooting Examples
+
+### 1. Debug Mode
+
+```bash
+# Enable verbose logging
+claude-flow automation mle-star \
+ --dataset data/debug.csv \
+ --verbose \
+ --claude \
+ --timeout 1800000
+```
+
+### 2. Workflow Validation
+
+```bash
+# Test workflow syntax without execution
+claude-flow automation run-workflow my-workflow.json \
+ --output-format json \
+ --timeout 5000 # Short timeout for validation
+```
+
+### 3. Step-by-Step Execution
+
+Break complex workflows into smaller pieces for debugging:
+
+```json
+{
+ "name": "Debug Workflow - Step 1",
+ "tasks": [
+ {
+ "id": "data_analysis_only",
+ "name": "Just Data Analysis",
+ "description": "Test data analysis step in isolation"
+ }
+ ]
+}
+```
+
+## Performance Optimization Examples
+
+### 1. Parallel Task Execution
+
+```json
+{
+ "tasks": [
+ {
+ "id": "task_a",
+ "description": "Independent task A"
+ },
+ {
+ "id": "task_b",
+ "description": "Independent task B"
+ },
+ {
+ "id": "task_c",
+ "depends": ["task_a", "task_b"],
+ "description": "Task C depends on A and B"
+ }
+ ],
+ "settings": {
+ "maxConcurrency": 3 // Run A and B in parallel
+ }
+}
+```
+
+### 2. Resource-Aware Configuration
+
+```json
+{
+ "settings": {
+ "maxConcurrency": 2, // Conservative for limited resources
+ "timeout": 7200, // 2 hours
+ "quality_threshold": 0.85
+ },
+ "agents": [
+ {
+ "config": {
+ "resource_requirements": {
+ "memory": "4GB",
+ "cpu_cores": 2
+ }
+ }
+ }
+ ]
+}
+```
+
+## Best Practices Examples
+
+### 1. Environment-Specific Configurations
+
+```bash
+# Development
+claude-flow automation run-workflow workflow.json \
+ --variables '{"timeout": 1800, "quality_threshold": 0.7}'
+
+# Production
+claude-flow automation run-workflow workflow.json \
+ --variables '{"timeout": 7200, "quality_threshold": 0.95}'
+```
+
+### 2. Error Recovery Patterns
+
+```json
+{
+ "tasks": [
+ {
+ "id": "critical_task",
+ "retries": 3,
+ "timeout": 3600,
+ "fallback_task": "manual_intervention"
+ }
+ ],
+ "settings": {
+ "failurePolicy": "continue",
+ "enable_monitoring": true
+ }
+}
+```
+
+### 3. Monitoring and Alerting
+
+```json
+{
+ "settings": {
+ "enable_monitoring": true,
+ "alert_conditions": {
+ "execution_time": "> 2 hours",
+ "failure_rate": "> 10%",
+ "resource_usage": "> 80%"
+ }
+ }
+}
+```
+
+These examples demonstrate the full power and flexibility of Claude Flow's automation system. Start with simple examples and gradually build more complex workflows as you become familiar with the system.
\ No newline at end of file
diff --git a/ml_foundation/evaluation/evaluator.py b/ml_foundation/evaluation/evaluator.py
new file mode 100644
index 0000000000..d2089c1195
--- /dev/null
+++ b/ml_foundation/evaluation/evaluator.py
@@ -0,0 +1,614 @@
+"""Model evaluation framework for MLE-STAR."""
+
+from abc import ABC, abstractmethod
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any, Dict, List, Optional, Tuple, Union, Callable
+import numpy as np
+from ..models.base import MLESTARModel, ModelMetrics
+
+
+@dataclass
+class EvalConfig:
+ """Configuration for model evaluation."""
+ # Metrics to compute
+ regression_metrics: List[str] = field(default_factory=lambda: [
+ "mse", "rmse", "mae", "r2", "explained_variance"
+ ])
+ classification_metrics: List[str] = field(default_factory=lambda: [
+ "accuracy", "precision", "recall", "f1", "auc_roc", "confusion_matrix"
+ ])
+
+ # Cross-validation settings
+ cv_folds: int = 5
+ cv_scoring: str = "accuracy"
+ cv_random_state: int = 42
+
+ # Evaluation settings
+ test_size: float = 0.2
+ validation_size: float = 0.2
+ stratify: bool = True
+
+ # Reporting settings
+ generate_plots: bool = True
+ save_predictions: bool = True
+ detailed_report: bool = True
+
+ # Performance settings
+ parallel_evaluation: bool = True
+ n_jobs: int = -1
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert config to dictionary."""
+ return {
+ "regression_metrics": self.regression_metrics,
+ "classification_metrics": self.classification_metrics,
+ "cv_folds": self.cv_folds,
+ "cv_scoring": self.cv_scoring,
+ "cv_random_state": self.cv_random_state,
+ "test_size": self.test_size,
+ "validation_size": self.validation_size,
+ "stratify": self.stratify,
+ "generate_plots": self.generate_plots,
+ "save_predictions": self.save_predictions,
+ "detailed_report": self.detailed_report,
+ "parallel_evaluation": self.parallel_evaluation,
+ "n_jobs": self.n_jobs
+ }
+
+
+@dataclass
+class EvaluationResult:
+ """Results from model evaluation."""
+ model_id: str
+ evaluation_id: str
+ timestamp: datetime
+
+ # Core metrics
+ metrics: Dict[str, float] = field(default_factory=dict)
+ cross_validation_scores: Dict[str, List[float]] = field(default_factory=dict)
+
+ # Predictions and errors
+ predictions: Optional[np.ndarray] = None
+ prediction_errors: Optional[np.ndarray] = None
+ feature_importance: Optional[Dict[str, float]] = None
+
+ # Performance data
+ evaluation_time: float = 0.0
+ memory_usage: float = 0.0
+
+ # Additional results
+ confusion_matrix: Optional[np.ndarray] = None
+ classification_report: Optional[Dict[str, Any]] = None
+ residuals: Optional[np.ndarray] = None
+
+ # Model comparison data
+ baseline_comparison: Optional[Dict[str, float]] = None
+ statistical_tests: Optional[Dict[str, Any]] = None
+
+ def to_dict(self) -> Dict[str, Any]:
+ """Convert evaluation result to dictionary."""
+ return {
+ "model_id": self.model_id,
+ "evaluation_id": self.evaluation_id,
+ "timestamp": self.timestamp.isoformat(),
+ "metrics": self.metrics,
+ "cross_validation_scores": self.cross_validation_scores,
+ "predictions": self.predictions.tolist() if self.predictions is not None else None,
+ "prediction_errors": self.prediction_errors.tolist() if self.prediction_errors is not None else None,
+ "feature_importance": self.feature_importance,
+ "evaluation_time": self.evaluation_time,
+ "memory_usage": self.memory_usage,
+ "confusion_matrix": self.confusion_matrix.tolist() if self.confusion_matrix is not None else None,
+ "classification_report": self.classification_report,
+ "residuals": self.residuals.tolist() if self.residuals is not None else None,
+ "baseline_comparison": self.baseline_comparison,
+ "statistical_tests": self.statistical_tests
+ }
+
+
+class MetricsCalculator:
+ """Calculates various ML evaluation metrics."""
+
+ @staticmethod
+ def regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> Dict[str, float]:
+ """Calculate regression metrics."""
+ from sklearn.metrics import (
+ mean_squared_error, mean_absolute_error, r2_score,
+ explained_variance_score
+ )
+
+ metrics = {}
+
+ try:
+ metrics["mse"] = mean_squared_error(y_true, y_pred)
+ metrics["rmse"] = np.sqrt(metrics["mse"])
+ metrics["mae"] = mean_absolute_error(y_true, y_pred)
+ metrics["r2"] = r2_score(y_true, y_pred)
+ metrics["explained_variance"] = explained_variance_score(y_true, y_pred)
+
+ # Additional regression metrics
+ residuals = y_true - y_pred
+ metrics["mean_residual"] = np.mean(residuals)
+ metrics["std_residual"] = np.std(residuals)
+ metrics["max_error"] = np.max(np.abs(residuals))
+
+ except Exception as e:
+ print(f"Error calculating regression metrics: {e}")
+
+ return metrics
+
+ @staticmethod
+ def classification_metrics(y_true: np.ndarray, y_pred: np.ndarray,
+ y_pred_proba: Optional[np.ndarray] = None) -> Dict[str, Any]:
+ """Calculate classification metrics."""
+ from sklearn.metrics import (
+ accuracy_score, precision_score, recall_score, f1_score,
+ confusion_matrix, classification_report, roc_auc_score
+ )
+
+ metrics = {}
+
+ try:
+ metrics["accuracy"] = accuracy_score(y_true, y_pred)
+ metrics["precision"] = precision_score(y_true, y_pred, average='weighted', zero_division=0)
+ metrics["recall"] = recall_score(y_true, y_pred, average='weighted', zero_division=0)
+ metrics["f1"] = f1_score(y_true, y_pred, average='weighted', zero_division=0)
+
+ # Confusion matrix
+ cm = confusion_matrix(y_true, y_pred)
+ metrics["confusion_matrix"] = cm
+
+ # Detailed classification report
+ metrics["classification_report"] = classification_report(
+ y_true, y_pred, output_dict=True, zero_division=0
+ )
+
+ # ROC AUC if probabilities provided
+ if y_pred_proba is not None:
+ try:
+ if y_pred_proba.shape[1] == 2: # Binary classification
+ metrics["auc_roc"] = roc_auc_score(y_true, y_pred_proba[:, 1])
+ else: # Multi-class
+ metrics["auc_roc"] = roc_auc_score(y_true, y_pred_proba, multi_class='ovr')
+ except Exception:
+ pass
+
+ except Exception as e:
+ print(f"Error calculating classification metrics: {e}")
+
+ return metrics
+
+ @staticmethod
+ def clustering_metrics(X: np.ndarray, labels: np.ndarray,
+ true_labels: Optional[np.ndarray] = None) -> Dict[str, float]:
+ """Calculate clustering metrics."""
+ from sklearn.metrics import (
+ silhouette_score, calinski_harabasz_score, davies_bouldin_score
+ )
+
+ metrics = {}
+
+ try:
+ # Internal metrics (don't require true labels)
+ if len(np.unique(labels)) > 1: # Need at least 2 clusters
+ metrics["silhouette"] = silhouette_score(X, labels)
+ metrics["calinski_harabasz"] = calinski_harabasz_score(X, labels)
+ metrics["davies_bouldin"] = davies_bouldin_score(X, labels)
+
+ # External metrics (require true labels)
+ if true_labels is not None:
+ from sklearn.metrics import (
+ adjusted_rand_score, normalized_mutual_info_score,
+ homogeneity_score, completeness_score, v_measure_score
+ )
+
+ metrics["adjusted_rand"] = adjusted_rand_score(true_labels, labels)
+ metrics["normalized_mutual_info"] = normalized_mutual_info_score(true_labels, labels)
+ metrics["homogeneity"] = homogeneity_score(true_labels, labels)
+ metrics["completeness"] = completeness_score(true_labels, labels)
+ metrics["v_measure"] = v_measure_score(true_labels, labels)
+
+ except Exception as e:
+ print(f"Error calculating clustering metrics: {e}")
+
+ return metrics
+
+
+class CrossValidator:
+ """Handles cross-validation for model evaluation."""
+
+ def __init__(self, config: EvalConfig):
+ """Initialize cross validator."""
+ self.config = config
+
+ def cross_validate(self, model: MLESTARModel, X: np.ndarray,
+ y: np.ndarray) -> Dict[str, List[float]]:
+ """Perform cross-validation on model."""
+ from sklearn.model_selection import cross_val_score, StratifiedKFold, KFold
+
+ results = {}
+
+ try:
+ # Choose cross-validation strategy
+ if self.config.stratify and len(np.unique(y)) > 1:
+ cv = StratifiedKFold(
+ n_splits=self.config.cv_folds,
+ shuffle=True,
+ random_state=self.config.cv_random_state
+ )
+ else:
+ cv = KFold(
+ n_splits=self.config.cv_folds,
+ shuffle=True,
+ random_state=self.config.cv_random_state
+ )
+
+ # Custom scoring function for MLE-STAR models
+ def mle_star_scorer(estimator, X_test, y_test):
+ predictions = estimator.predict(X_test)
+ metrics = estimator.evaluate(X_test, y_test)
+ return metrics.validation_accuracy
+
+ # Perform cross-validation
+ scores = cross_val_score(
+ model, X, y,
+ cv=cv,
+ scoring=mle_star_scorer,
+ n_jobs=self.config.n_jobs if self.config.parallel_evaluation else 1
+ )
+
+ results[self.config.cv_scoring] = scores.tolist()
+ results["mean_score"] = [np.mean(scores)]
+ results["std_score"] = [np.std(scores)]
+
+ except Exception as e:
+ print(f"Error in cross-validation: {e}")
+ results["error"] = [str(e)]
+
+ return results
+
+ def learning_curve(self, model: MLESTARModel, X: np.ndarray,
+ y: np.ndarray) -> Dict[str, Any]:
+ """Generate learning curves for the model."""
+ from sklearn.model_selection import learning_curve
+
+ try:
+ train_sizes, train_scores, val_scores = learning_curve(
+ model, X, y,
+ cv=self.config.cv_folds,
+ n_jobs=self.config.n_jobs if self.config.parallel_evaluation else 1,
+ train_sizes=np.linspace(0.1, 1.0, 10),
+ random_state=self.config.cv_random_state
+ )
+
+ return {
+ "train_sizes": train_sizes.tolist(),
+ "train_scores_mean": np.mean(train_scores, axis=1).tolist(),
+ "train_scores_std": np.std(train_scores, axis=1).tolist(),
+ "val_scores_mean": np.mean(val_scores, axis=1).tolist(),
+ "val_scores_std": np.std(val_scores, axis=1).tolist()
+ }
+
+ except Exception as e:
+ print(f"Error generating learning curve: {e}")
+ return {"error": str(e)}
+
+
+class ReportGenerator:
+ """Generates comprehensive evaluation reports."""
+
+ def __init__(self, config: EvalConfig):
+ """Initialize report generator."""
+ self.config = config
+
+ def generate_report(self, evaluation_result: EvaluationResult) -> str:
+ """Generate a comprehensive evaluation report."""
+ report = [
+ "Model Evaluation Report",
+ "=" * 50,
+ f"Model ID: {evaluation_result.model_id}",
+ f"Evaluation ID: {evaluation_result.evaluation_id}",
+ f"Timestamp: {evaluation_result.timestamp.isoformat()}",
+ f"Evaluation Time: {evaluation_result.evaluation_time:.2f} seconds",
+ f"Memory Usage: {evaluation_result.memory_usage:.2f} MB",
+ "",
+ "Performance Metrics",
+ "-" * 20
+ ]
+
+ # Add metrics
+ for metric_name, value in evaluation_result.metrics.items():
+ if isinstance(value, float):
+ report.append(f"{metric_name}: {value:.4f}")
+ else:
+ report.append(f"{metric_name}: {value}")
+
+ # Add cross-validation results
+ if evaluation_result.cross_validation_scores:
+ report.append("\nCross-Validation Results")
+ report.append("-" * 25)
+ for cv_metric, scores in evaluation_result.cross_validation_scores.items():
+ if scores and isinstance(scores[0], (int, float)):
+ mean_score = np.mean(scores)
+ std_score = np.std(scores)
+ report.append(f"{cv_metric}: {mean_score:.4f} (±{std_score:.4f})")
+
+ # Add feature importance if available
+ if evaluation_result.feature_importance:
+ report.append("\nFeature Importance")
+ report.append("-" * 18)
+ sorted_features = sorted(
+ evaluation_result.feature_importance.items(),
+ key=lambda x: x[1], reverse=True
+ )
+ for feature, importance in sorted_features[:10]: # Top 10
+ report.append(f"{feature}: {importance:.4f}")
+
+ # Add baseline comparison if available
+ if evaluation_result.baseline_comparison:
+ report.append("\nBaseline Comparison")
+ report.append("-" * 19)
+ for metric, improvement in evaluation_result.baseline_comparison.items():
+ report.append(f"{metric} improvement: {improvement:.4f}")
+
+ return "\n".join(report)
+
+ def save_report(self, evaluation_result: EvaluationResult,
+ filepath: str) -> bool:
+ """Save evaluation report to file."""
+ try:
+ report = self.generate_report(evaluation_result)
+ with open(filepath, 'w') as f:
+ f.write(report)
+ return True
+ except Exception as e:
+ print(f"Error saving report: {e}")
+ return False
+
+
+class ModelComparator:
+ """Compares multiple models and their performance."""
+
+ def __init__(self):
+ """Initialize model comparator."""
+ self.evaluation_results: List[EvaluationResult] = []
+
+ def add_evaluation(self, result: EvaluationResult):
+ """Add an evaluation result for comparison."""
+ self.evaluation_results.append(result)
+
+ def compare_models(self, metric: str = "accuracy") -> Dict[str, Any]:
+ """Compare models based on specified metric."""
+ if not self.evaluation_results:
+ return {"error": "No evaluation results to compare"}
+
+ comparison = {
+ "metric": metric,
+ "models": [],
+ "best_model": None,
+ "rankings": []
+ }
+
+ # Collect metric values for all models
+ model_scores = []
+ for result in self.evaluation_results:
+ if metric in result.metrics:
+ score = result.metrics[metric]
+ model_scores.append({
+ "model_id": result.model_id,
+ "score": score,
+ "evaluation_id": result.evaluation_id
+ })
+
+ if not model_scores:
+ return {"error": f"Metric '{metric}' not found in any evaluation"}
+
+ # Sort by score (descending for most metrics)
+ model_scores.sort(key=lambda x: x["score"], reverse=True)
+
+ comparison["models"] = model_scores
+ comparison["best_model"] = model_scores[0]
+ comparison["rankings"] = [
+ {"rank": i+1, **model}
+ for i, model in enumerate(model_scores)
+ ]
+
+ return comparison
+
+ def statistical_comparison(self, metric: str = "accuracy") -> Dict[str, Any]:
+ """Perform statistical comparison between models."""
+ from scipy import stats
+
+ if len(self.evaluation_results) < 2:
+ return {"error": "Need at least 2 models for statistical comparison"}
+
+ # Collect cross-validation scores
+ cv_scores = {}
+ for result in self.evaluation_results:
+ if metric in result.cross_validation_scores:
+ cv_scores[result.model_id] = result.cross_validation_scores[metric]
+
+ if len(cv_scores) < 2:
+ return {"error": f"Need CV scores for at least 2 models"}
+
+ comparisons = {}
+ model_ids = list(cv_scores.keys())
+
+ # Pairwise t-tests
+ for i in range(len(model_ids)):
+ for j in range(i+1, len(model_ids)):
+ model1, model2 = model_ids[i], model_ids[j]
+ scores1, scores2 = cv_scores[model1], cv_scores[model2]
+
+ # Paired t-test
+ t_stat, p_value = stats.ttest_rel(scores1, scores2)
+
+ comparison_key = f"{model1}_vs_{model2}"
+ comparisons[comparison_key] = {
+ "t_statistic": t_stat,
+ "p_value": p_value,
+ "significant": p_value < 0.05,
+ "mean_diff": np.mean(scores1) - np.mean(scores2)
+ }
+
+ return {
+ "metric": metric,
+ "pairwise_comparisons": comparisons,
+ "summary": {
+ "total_comparisons": len(comparisons),
+ "significant_differences": sum(
+ 1 for comp in comparisons.values()
+ if comp["significant"]
+ )
+ }
+ }
+
+
+class ModelEvaluator:
+ """Main evaluator for MLE-STAR models."""
+
+ def __init__(self, config: Optional[EvalConfig] = None):
+ """Initialize model evaluator."""
+ self.config = config or EvalConfig()
+ self.metrics_calculator = MetricsCalculator()
+ self.cross_validator = CrossValidator(self.config)
+ self.report_generator = ReportGenerator(self.config)
+ self.model_comparator = ModelComparator()
+
+ def evaluate_model(self, model: MLESTARModel, X_test: np.ndarray,
+ y_test: np.ndarray, X_train: Optional[np.ndarray] = None,
+ y_train: Optional[np.ndarray] = None) -> EvaluationResult:
+ """Comprehensive model evaluation."""
+ import time
+ import uuid
+ import psutil
+ import os
+
+ start_time = time.time()
+ start_memory = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024
+
+ # Create evaluation result
+ result = EvaluationResult(
+ model_id=model.model_id,
+ evaluation_id=str(uuid.uuid4()).split('-')[0],
+ timestamp=datetime.now()
+ )
+
+ try:
+ # Get predictions
+ predictions = model.predict(X_test)
+ result.predictions = predictions
+
+ # Calculate prediction errors
+ if y_test is not None:
+ result.prediction_errors = y_test - predictions
+ result.residuals = result.prediction_errors
+
+ # Determine task type and calculate appropriate metrics
+ task_type = self._determine_task_type(model, y_test)
+
+ if task_type == "regression":
+ metrics = self.metrics_calculator.regression_metrics(y_test, predictions)
+ result.metrics.update(metrics)
+ elif task_type == "classification":
+ # Get prediction probabilities if available
+ try:
+ pred_proba = getattr(model, 'predict_proba', lambda x: None)(X_test)
+ except:
+ pred_proba = None
+
+ metrics = self.metrics_calculator.classification_metrics(
+ y_test, predictions, pred_proba
+ )
+ result.metrics.update(metrics)
+
+ # Store confusion matrix separately
+ if "confusion_matrix" in metrics:
+ result.confusion_matrix = metrics.pop("confusion_matrix")
+ if "classification_report" in metrics:
+ result.classification_report = metrics.pop("classification_report")
+
+ # Cross-validation if training data provided
+ if X_train is not None and y_train is not None:
+ cv_scores = self.cross_validator.cross_validate(model, X_train, y_train)
+ result.cross_validation_scores = cv_scores
+
+ # Feature importance if available
+ try:
+ if hasattr(model, 'feature_importances_'):
+ importances = model.feature_importances_
+ feature_names = [f"feature_{i}" for i in range(len(importances))]
+ result.feature_importance = dict(zip(feature_names, importances))
+ except:
+ pass
+
+ except Exception as e:
+ result.metrics["evaluation_error"] = str(e)
+
+ # Record performance metrics
+ end_time = time.time()
+ end_memory = psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024
+
+ result.evaluation_time = end_time - start_time
+ result.memory_usage = end_memory - start_memory
+
+ return result
+
+ def _determine_task_type(self, model: MLESTARModel, y: Optional[np.ndarray]) -> str:
+ """Determine the type of ML task based on model and target data."""
+ if hasattr(model, 'config') and hasattr(model.config, 'model_type'):
+ if model.config.model_type in ["supervised"]:
+ if y is not None:
+ # Check if targets are continuous or discrete
+ unique_values = len(np.unique(y))
+ total_values = len(y)
+
+ # If unique values / total values ratio is low, likely classification
+ if unique_values / total_values < 0.1 or unique_values < 20:
+ return "classification"
+ else:
+ return "regression"
+ elif model.config.model_type == "unsupervised":
+ return "clustering"
+ elif model.config.model_type == "reinforcement":
+ return "reinforcement"
+
+ # Default to regression
+ return "regression"
+
+ def batch_evaluate(self, models: List[MLESTARModel], X_test: np.ndarray,
+ y_test: np.ndarray) -> List[EvaluationResult]:
+ """Evaluate multiple models in batch."""
+ results = []
+
+ for model in models:
+ result = self.evaluate_model(model, X_test, y_test)
+ results.append(result)
+ self.model_comparator.add_evaluation(result)
+
+ return results
+
+ def generate_comparison_report(self, metric: str = "accuracy") -> Dict[str, Any]:
+ """Generate a comparison report for all evaluated models."""
+ return self.model_comparator.compare_models(metric)
+
+ def save_evaluation_results(self, results: List[EvaluationResult],
+ directory: str = "./evaluation_results"):
+ """Save evaluation results to disk."""
+ import os
+ import json
+
+ os.makedirs(directory, exist_ok=True)
+
+ for result in results:
+ filename = f"evaluation_{result.model_id}_{result.evaluation_id}.json"
+ filepath = os.path.join(directory, filename)
+
+ with open(filepath, 'w') as f:
+ json.dump(result.to_dict(), f, indent=2)
+
+ # Save detailed report
+ report_filename = f"report_{result.model_id}_{result.evaluation_id}.txt"
+ report_filepath = os.path.join(directory, report_filename)
+ self.report_generator.save_report(result, report_filepath)
\ No newline at end of file