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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
| import pandas as pd import numpy as np from sklearn.model_selection import train_test_split, cross_val_score, GridSearchCV, RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor, GradientBoostingClassifier, GradientBoostingRegressor from sklearn.linear_model import LogisticRegression, LinearRegression, Ridge, Lasso from sklearn.svm import SVC, SVR from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score import joblib from typing import Dict, Any, Tuple, List import logging
class ModelTrainer: def __init__(self, config: Config): self.config = config self.logger = logging.getLogger(__name__) self.models = {} self.best_model = None self.task_type = None def prepare_data(self, df: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: """准备训练数据""" X = df.drop(self.config.data.target_column, axis=1) y = df[self.config.data.target_column] if y.dtype == 'object' or y.nunique() < 20: self.task_type = 'classification' else: self.task_type = 'regression' X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=self.config.data.test_size, random_state=self.config.data.random_state, stratify=y if self.task_type == 'classification' else None ) self.logger.info(f"数据分割完成。训练集: {X_train.shape}, 测试集: {X_test.shape}") self.logger.info(f"任务类型: {self.task_type}") return X_train, X_test, y_train, y_test def get_model_candidates(self) -> Dict[str, Any]: """获取候选模型""" if self.task_type == 'classification': models = { 'random_forest': RandomForestClassifier(random_state=42), 'gradient_boosting': GradientBoostingClassifier(random_state=42), 'logistic_regression': LogisticRegression(random_state=42, max_iter=1000), 'svm': SVC(random_state=42, probability=True) } else: models = { 'random_forest': RandomForestRegressor(random_state=42), 'gradient_boosting': GradientBoostingRegressor(random_state=42), 'linear_regression': LinearRegression(), 'ridge': Ridge(random_state=42), 'lasso': Lasso(random_state=42), 'svr': SVR() } return models def get_hyperparameter_grids(self) -> Dict[str, Dict[str, List]]: """获取超参数搜索空间""" if self.task_type == 'classification': param_grids = { 'random_forest': { 'n_estimators': [50, 100, 200], 'max_depth': [5, 10, 15, None], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] }, 'gradient_boosting': { 'n_estimators': [50, 100, 200], 'learning_rate': [0.01, 0.1, 0.2], 'max_depth': [3, 5, 7], 'subsample': [0.8, 0.9, 1.0] }, 'logistic_regression': { 'C': [0.1, 1, 10, 100], 'penalty': ['l1', 'l2'], 'solver': ['liblinear', 'saga'] }, 'svm': { 'C': [0.1, 1, 10], 'kernel': ['rbf', 'linear'], 'gamma': ['scale', 'auto'] } } else: param_grids = { 'random_forest': { 'n_estimators': [50, 100, 200], 'max_depth': [5, 10, 15, None], 'min_samples_split': [2, 5, 10], 'min_samples_leaf': [1, 2, 4] }, 'gradient_boosting': { 'n_estimators': [50, 100, 200], 'learning_rate': [0.01, 0.1, 0.2], 'max_depth': [3, 5, 7], 'subsample': [0.8, 0.9, 1.0] }, 'ridge': { 'alpha': [0.1, 1, 10, 100] }, 'lasso': { 'alpha': [0.1, 1, 10, 100] }, 'svr': { 'C': [0.1, 1, 10], 'kernel': ['rbf', 'linear'], 'gamma': ['scale', 'auto'] } } return param_grids def train_single_model(self, model, X_train: np.ndarray, y_train: np.ndarray, param_grid: Dict = None, use_random_search: bool = False) -> Any: """训练单个模型""" if param_grid: if use_random_search: search = RandomizedSearchCV( model, param_grid, n_iter=20, cv=self.config.model.cv_folds, scoring=self.config.model.scoring_metric, random_state=42, n_jobs=-1 ) else: search = GridSearchCV( model, param_grid, cv=self.config.model.cv_folds, scoring=self.config.model.scoring_metric, n_jobs=-1 ) search.fit(X_train, y_train) return search.best_estimator_ else: model.fit(X_train, y_train) return model def evaluate_model(self, model, X_test: np.ndarray, y_test: np.ndarray) -> Dict[str, float]: """评估模型性能""" y_pred = model.predict(X_test) if self.task_type == 'classification': metrics = { 'accuracy': accuracy_score(y_test, y_pred), 'precision': precision_score(y_test, y_pred, average='weighted'), 'recall': recall_score(y_test, y_pred, average='weighted'), 'f1': f1_score(y_test, y_pred, average='weighted') } if len(np.unique(y_test)) == 2: y_pred_proba = model.predict_proba(X_test)[:, 1] metrics['auc'] = roc_auc_score(y_test, y_pred_proba) else: metrics = { 'mse': mean_squared_error(y_test, y_pred), 'mae': mean_absolute_error(y_test, y_pred), 'rmse': np.sqrt(mean_squared_error(y_test, y_pred)), 'r2': r2_score(y_test, y_pred) } return metrics def cross_validate_model(self, model, X: np.ndarray, y: np.ndarray) -> Dict[str, float]: """交叉验证""" cv_scores = cross_val_score( model, X, y, cv=self.config.model.cv_folds, scoring=self.config.model.scoring_metric ) return { 'cv_mean': cv_scores.mean(), 'cv_std': cv_scores.std(), 'cv_scores': cv_scores.tolist() } def train_all_models(self, df: pd.DataFrame) -> Dict[str, Dict[str, Any]]: """训练所有候选模型""" self.logger.info("开始训练所有候选模型...") X_train, X_test, y_train, y_test = self.prepare_data(df) model_candidates = self.get_model_candidates() param_grids = self.get_hyperparameter_grids() results = {} for model_name, model in model_candidates.items(): self.logger.info(f"训练模型: {model_name}") try: param_grid = param_grids.get(model_name) trained_model = self.train_single_model( model, X_train, y_train, param_grid, use_random_search=True ) test_metrics = self.evaluate_model(trained_model, X_test, y_test) cv_metrics = self.cross_validate_model(trained_model, X_train, y_train) results[model_name] = { 'model': trained_model, 'test_metrics': test_metrics, 'cv_metrics': cv_metrics, 'best_params': getattr(trained_model, 'get_params', lambda: {})() } self.logger.info(f"{model_name} 训练完成") except Exception as e: self.logger.error(f"训练 {model_name} 时出错: {e}") continue self.models = results self._select_best_model() return results def _select_best_model(self): """选择最佳模型""" if not self.models: return best_score = float('-inf') if self.task_type == 'classification' else float('inf') best_model_name = None for model_name, result in self.models.items(): if self.task_type == 'classification': score = result['test_metrics']['accuracy'] if score > best_score: best_score = score best_model_name = model_name else: score = result['test_metrics']['rmse'] if score < best_score: best_score = score best_model_name = model_name if best_model_name: self.best_model = { 'name': best_model_name, 'model': self.models[best_model_name]['model'], 'metrics': self.models[best_model_name]['test_metrics'] } self.logger.info(f"最佳模型: {best_model_name}, 分数: {best_score}") def save_model(self, model_path: str = None): """保存最佳模型""" if not self.best_model: raise ValueError("没有训练好的模型可以保存") if not model_path: model_path = f"models/best_model_{self.best_model['name']}.joblib" joblib.dump(self.best_model['model'], model_path) self.logger.info(f"模型已保存到: {model_path}") return model_path def load_model(self, model_path: str): """加载模型""" model = joblib.load(model_path) self.logger.info(f"模型已从 {model_path} 加载") return model def get_training_report(self) -> str: """生成训练报告""" if not self.models: return "没有训练结果可以报告" report_lines = [] report_lines.append("=" * 50) report_lines.append("模型训练报告") report_lines.append("=" * 50) report_lines.append(f"任务类型: {self.task_type}") report_lines.append(f"评估指标: {self.config.model.scoring_metric}") report_lines.append("") report_lines.append("📊 模型性能对比:") for model_name, result in self.models.items(): report_lines.append(f"\n🔸 {model_name}:") for metric, value in result['test_metrics'].items(): report_lines.append(f" - {metric}: {value:.4f}") report_lines.append(f" - CV平均分: {result['cv_metrics']['cv_mean']:.4f} (±{result['cv_metrics']['cv_std']:.4f})") if self.best_model: report_lines.append(f"\n🏆 最佳模型: {self.best_model['name']}") report_lines.append("最佳模型性能:") for metric, value in self.best_model['metrics'].items(): report_lines.append(f" - {metric}: {value:.4f}") return "\n".join(report_lines)
trainer = ModelTrainer(config) training_results = trainer.train_all_models(df_engineered)
training_report = trainer.get_training_report() print(training_report)
model_path = trainer.save_model()
|