Spaces:
Running
Running
File size: 10,892 Bytes
09801ca | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 | """
π― Model Strategy Agent
Dynamically selects algorithms based on dataset characteristics:
- Data size (small vs large)
- Task type (classification vs regression)
- Feature types (numeric vs categorical)
- Class balance
- Dimensionality
No neural networks - traditional ML only.
"""
import numpy as np
from typing import Dict, List, Any, Tuple, Optional
from dataclasses import dataclass
import logging
from .base import BaseAgent, AgentResult, AgentStatus, Phase
logger = logging.getLogger(__name__)
@dataclass
class ModelCandidate:
"""A candidate model for training"""
name: str
model_class: str
priority: int # Higher = try first
params: Dict[str, Any]
reason: str
class ModelStrategyAgent(BaseAgent):
"""
Autonomous Model Strategy Agent
Analyzes data profile β Selects suitable algorithms β Prioritizes candidates
"""
name = "model_strategy"
description = "Dynamically selects ML algorithms based on data characteristics"
def __init__(self, memory=None):
super().__init__(memory)
self.candidates: List[ModelCandidate] = []
def execute(self, **kwargs) -> AgentResult:
"""Main execution: analyze data, select models"""
# Get data characteristics
X = self.read_state("features_engineered")
if X is None:
X = self.read_state("features")
y = self.read_state("target")
task_type = self.read_state("task_type")
if X is None or y is None:
return AgentResult(
status=AgentStatus.FAILED,
agent_name=self.name,
phase=self.current_phase,
errors=["No features found"]
)
# Analyze data profile
profile = self._analyze_data_profile(X, y, task_type)
self.logger.info(f"π Data profile: {profile['n_samples']} samples, {profile['n_features']} features")
# Select models based on phase
if self.is_fast_phase():
candidates = self._select_fast_models(profile, task_type)
else:
candidates = self._select_deep_models(profile, task_type)
self.candidates = candidates
# Store results
self.write_state("model_candidates", [c.__dict__ for c in candidates], self.name)
self.write_state("data_profile", profile, self.name)
return AgentResult(
status=AgentStatus.SUCCESS,
agent_name=self.name,
phase=self.current_phase,
data={
"n_candidates": len(candidates),
"models": [c.name for c in candidates]
},
metrics={
"candidates_selected": len(candidates)
}
)
# =========================================================================
# DATA PROFILING
# =========================================================================
def _analyze_data_profile(self, X: np.ndarray, y: np.ndarray, task_type: str) -> Dict[str, Any]:
"""Analyze data characteristics for model selection"""
n_samples, n_features = X.shape
profile = {
"n_samples": n_samples,
"n_features": n_features,
"task_type": task_type,
"is_small": n_samples < 1000,
"is_large": n_samples > 50000,
"is_high_dim": n_features > 100,
"samples_per_feature": n_samples / max(1, n_features)
}
# Class balance for classification
if task_type == "classification":
unique, counts = np.unique(y, return_counts=True)
profile["n_classes"] = len(unique)
profile["is_imbalanced"] = max(counts) / min(counts) > 3 if min(counts) > 0 else False
return profile
# =========================================================================
# FAST PHASE - Limited models
# =========================================================================
def _select_fast_models(self, profile: Dict, task_type: str) -> List[ModelCandidate]:
"""Select 3-4 fast models for quick evaluation"""
candidates = []
if task_type == "classification":
# Always include Random Forest (robust baseline)
candidates.append(ModelCandidate(
name="RandomForest",
model_class="sklearn.ensemble.RandomForestClassifier",
priority=100,
params={"n_estimators": 100, "max_depth": 10, "n_jobs": -1, "random_state": 42},
reason="Robust baseline for classification"
))
# XGBoost if available
candidates.append(ModelCandidate(
name="XGBoost",
model_class="xgboost.XGBClassifier",
priority=95,
params={"n_estimators": 100, "max_depth": 6, "learning_rate": 0.1, "n_jobs": -1, "random_state": 42},
reason="High performance gradient boosting"
))
# LightGBM for large datasets
if profile.get("is_large"):
candidates.append(ModelCandidate(
name="LightGBM",
model_class="lightgbm.LGBMClassifier",
priority=90,
params={"n_estimators": 100, "max_depth": 6, "learning_rate": 0.1, "n_jobs": -1, "random_state": 42},
reason="Fast for large datasets"
))
else:
# Logistic Regression for small datasets
candidates.append(ModelCandidate(
name="LogisticRegression",
model_class="sklearn.linear_model.LogisticRegression",
priority=80,
params={"max_iter": 1000, "random_state": 42},
reason="Simple baseline"
))
else: # Regression
candidates.append(ModelCandidate(
name="RandomForest",
model_class="sklearn.ensemble.RandomForestRegressor",
priority=100,
params={"n_estimators": 100, "max_depth": 10, "n_jobs": -1, "random_state": 42},
reason="Robust baseline for regression"
))
candidates.append(ModelCandidate(
name="XGBoost",
model_class="xgboost.XGBRegressor",
priority=95,
params={"n_estimators": 100, "max_depth": 6, "learning_rate": 0.1, "n_jobs": -1, "random_state": 42},
reason="High performance gradient boosting"
))
candidates.append(ModelCandidate(
name="Ridge",
model_class="sklearn.linear_model.Ridge",
priority=70,
params={"alpha": 1.0, "random_state": 42},
reason="Simple linear baseline"
))
self.logger.info(f" β
Fast mode: {len(candidates)} models selected")
return sorted(candidates, key=lambda x: x.priority, reverse=True)
# =========================================================================
# DEEP PHASE - Full model suite
# =========================================================================
def _select_deep_models(self, profile: Dict, task_type: str) -> List[ModelCandidate]:
"""Select comprehensive set of models for thorough evaluation"""
candidates = self._select_fast_models(profile, task_type)
if task_type == "classification":
# Add more models
candidates.extend([
ModelCandidate(
name="ExtraTrees",
model_class="sklearn.ensemble.ExtraTreesClassifier",
priority=85,
params={"n_estimators": 100, "max_depth": 15, "n_jobs": -1, "random_state": 42},
reason="Fast alternative to RF"
),
ModelCandidate(
name="CatBoost",
model_class="catboost.CatBoostClassifier",
priority=88,
params={"iterations": 100, "depth": 6, "learning_rate": 0.1, "random_state": 42, "verbose": False},
reason="Handles categoricals natively"
),
ModelCandidate(
name="HistGradientBoosting",
model_class="sklearn.ensemble.HistGradientBoostingClassifier",
priority=82,
params={"max_iter": 100, "max_depth": 6, "random_state": 42},
reason="Fast native sklearn boosting"
),
])
if not profile.get("is_high_dim"):
candidates.append(ModelCandidate(
name="SVC",
model_class="sklearn.svm.SVC",
priority=60,
params={"kernel": "rbf", "probability": True, "random_state": 42},
reason="Non-linear classification"
))
else: # Regression
candidates.extend([
ModelCandidate(
name="ExtraTrees",
model_class="sklearn.ensemble.ExtraTreesRegressor",
priority=85,
params={"n_estimators": 100, "max_depth": 15, "n_jobs": -1, "random_state": 42},
reason="Fast alternative to RF"
),
ModelCandidate(
name="LightGBM",
model_class="lightgbm.LGBMRegressor",
priority=90,
params={"n_estimators": 100, "max_depth": 6, "learning_rate": 0.1, "n_jobs": -1, "random_state": 42},
reason="Fast gradient boosting"
),
ModelCandidate(
name="CatBoost",
model_class="catboost.CatBoostRegressor",
priority=88,
params={"iterations": 100, "depth": 6, "learning_rate": 0.1, "random_state": 42, "verbose": False},
reason="Handles categoricals natively"
),
ModelCandidate(
name="ElasticNet",
model_class="sklearn.linear_model.ElasticNet",
priority=65,
params={"alpha": 1.0, "l1_ratio": 0.5, "random_state": 42},
reason="Regularized linear model"
),
])
self.logger.info(f" β
Deep mode: {len(candidates)} models selected")
return sorted(candidates, key=lambda x: x.priority, reverse=True)
|