news 2026/5/24 1:01:25

模型评估与超参数调优

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
模型评估与超参数调优

模型评估与超参数调优

1. 技术分析

1.1 模型评估概述

模型评估是机器学习的关键步骤:

评估指标 分类指标: 准确率、精确率、召回率、F1、AUC 回归指标: MAE、MSE、RMSE、R² 排序指标: MAP、NDCG 评估方法: 交叉验证 时间序列分割 分层抽样

1.2 超参数调优

调优方法 网格搜索: 穷举搜索 随机搜索: 随机采样 贝叶斯优化: 概率模型 遗传算法: 进化优化 调优策略: 粗调: 大范围搜索 微调: 精细搜索

1.3 评估指标对比

指标适用任务特点
准确率分类不平衡数据有偏差
F1分数分类平衡精确率和召回率
AUC-ROC分类评估排序能力
RMSE回归对异常值敏感
回归解释方差比例

2. 核心功能实现

2.1 分类评估指标

import numpy as np from sklearn.metrics import confusion_matrix class ClassificationEvaluator: def __init__(self, y_true, y_pred, y_proba=None): self.y_true = y_true self.y_pred = y_pred self.y_proba = y_proba self.confusion = confusion_matrix(y_true, y_pred) def accuracy(self): return np.mean(self.y_true == self.y_pred) def precision(self): tp = self.confusion[1, 1] fp = self.confusion[0, 1] return tp / (tp + fp) if (tp + fp) > 0 else 0 def recall(self): tp = self.confusion[1, 1] fn = self.confusion[1, 0] return tp / (tp + fn) if (tp + fn) > 0 else 0 def f1_score(self): p = self.precision() r = self.recall() return 2 * p * r / (p + r) if (p + r) > 0 else 0 def specificity(self): tn = self.confusion[0, 0] fp = self.confusion[0, 1] return tn / (tn + fp) if (tn + fp) > 0 else 0 def auc_roc(self): if self.y_proba is None: raise ValueError("需要提供预测概率") thresholds = np.sort(np.unique(self.y_proba))[::-1] tpr_list = [] fpr_list = [] for threshold in thresholds: pred = (self.y_proba >= threshold).astype(int) cm = confusion_matrix(self.y_true, pred) tp = cm[1, 1] if cm.shape[0] > 1 and cm.shape[1] > 1 else 0 fn = cm[1, 0] if cm.shape[0] > 1 and cm.shape[1] > 0 else 0 tn = cm[0, 0] if cm.shape[0] > 0 and cm.shape[1] > 0 else 0 fp = cm[0, 1] if cm.shape[0] > 0 and cm.shape[1] > 1 else 0 tpr = tp / (tp + fn) if (tp + fn) > 0 else 0 fpr = fp / (tn + fp) if (tn + fp) > 0 else 0 tpr_list.append(tpr) fpr_list.append(fpr) return np.trapz(tpr_list, fpr_list) def report(self): return { 'accuracy': self.accuracy(), 'precision': self.precision(), 'recall': self.recall(), 'f1_score': self.f1_score(), 'specificity': self.specificity(), 'auc_roc': self.auc_roc() if self.y_proba is not None else None, 'confusion_matrix': self.confusion.tolist() }

2.2 回归评估指标

class RegressionEvaluator: def __init__(self, y_true, y_pred): self.y_true = y_true self.y_pred = y_pred def mae(self): return np.mean(np.abs(self.y_true - self.y_pred)) def mse(self): return np.mean((self.y_true - self.y_pred) ** 2) def rmse(self): return np.sqrt(self.mse()) def mape(self): return np.mean(np.abs((self.y_true - self.y_pred) / self.y_true)) * 100 def r2_score(self): ss_res = np.sum((self.y_true - self.y_pred) ** 2) ss_tot = np.sum((self.y_true - np.mean(self.y_true)) ** 2) return 1 - (ss_res / ss_tot) if ss_tot > 0 else 0 def report(self): return { 'mae': self.mae(), 'mse': self.mse(), 'rmse': self.rmse(), 'mape': self.mape(), 'r2_score': self.r2_score() }

2.3 交叉验证

class CrossValidation: def __init__(self, n_folds=5, shuffle=True): self.n_folds = n_folds self.shuffle = shuffle def split(self, X, y): n_samples = len(y) indices = np.arange(n_samples) if self.shuffle: np.random.shuffle(indices) fold_size = n_samples // self.n_folds folds = [] for i in range(self.n_folds): start = i * fold_size end = (i + 1) * fold_size if i < self.n_folds - 1 else n_samples val_indices = indices[start:end] train_indices = np.concatenate([indices[:start], indices[end:]]) folds.append((train_indices, val_indices)) return folds def evaluate(self, model, X, y, evaluator_func): scores = [] for train_idx, val_idx in self.split(X, y): X_train, X_val = X[train_idx], X[val_idx] y_train, y_val = y[train_idx], y[val_idx] model.fit(X_train, y_train) y_pred = model.predict(X_val) score = evaluator_func(y_val, y_pred) scores.append(score) return { 'mean': np.mean(scores), 'std': np.std(scores), 'scores': scores }

2.4 超参数调优

from sklearn.model_selection import GridSearchCV, RandomizedSearchCV from scipy.stats import randint, uniform class HyperparameterTuner: def __init__(self, model, param_grid, method='grid'): self.model = model self.param_grid = param_grid self.method = method self.best_model = None self.best_params = None def grid_search(self, X, y, cv=5): grid_search = GridSearchCV( self.model, self.param_grid, cv=cv, scoring='accuracy', n_jobs=-1 ) grid_search.fit(X, y) self.best_model = grid_search.best_estimator_ self.best_params = grid_search.best_params_ return { 'best_score': grid_search.best_score_, 'best_params': grid_search.best_params_, 'cv_results': grid_search.cv_results_ } def random_search(self, X, y, n_iter=100, cv=5): random_search = RandomizedSearchCV( self.model, self.param_grid, n_iter=n_iter, cv=cv, scoring='accuracy', n_jobs=-1, random_state=42 ) random_search.fit(X, y) self.best_model = random_search.best_estimator_ self.best_params = random_search.best_params_ return { 'best_score': random_search.best_score_, 'best_params': random_search.best_params_ } def bayesian_optimization(self, X, y, n_iter=50): from bayes_opt import BayesianOptimization def objective(**params): model = self.model.__class__(**params) cv = CrossValidation(n_folds=5) result = cv.evaluate(model, X, y, lambda y_true, y_pred: np.mean(y_true == y_pred)) return result['mean'] bounds = {} for param, values in self.param_grid.items(): if isinstance(values, list): bounds[param] = (min(values), max(values)) optimizer = BayesianOptimization( f=objective, pbounds=bounds, random_state=42 ) optimizer.maximize(n_iter=n_iter) self.best_params = optimizer.max['params'] self.best_model = self.model.__class__(**self.best_params) self.best_model.fit(X, y) return { 'best_score': optimizer.max['target'], 'best_params': optimizer.max['params'] } def tune(self, X, y): if self.method == 'grid': return self.grid_search(X, y) elif self.method == 'random': return self.random_search(X, y) elif self.method == 'bayesian': return self.bayesian_optimization(X, y)

3. 性能对比

3.1 调优方法对比

方法效率效果复杂度
网格搜索
随机搜索
贝叶斯优化
遗传算法很高

3.2 评估指标对比

指标用途优点缺点
准确率整体评估简单不平衡数据有偏差
F1分数不平衡数据平衡只关注正类
AUC-ROC排序能力全面需要概率输出

3.3 交叉验证策略对比

方法适用场景稳定性
K-fold通用
Stratified K-fold不平衡数据
TimeSeriesSplit时间序列

4. 最佳实践

4.1 模型评估流程

def evaluate_model(model, X_train, y_train, X_test, y_test, task_type='classification'): model.fit(X_train, y_train) y_pred_train = model.predict(X_train) y_pred_test = model.predict(X_test) if task_type == 'classification': if hasattr(model, 'predict_proba'): y_proba_train = model.predict_proba(X_train)[:, 1] y_proba_test = model.predict_proba(X_test)[:, 1] else: y_proba_train = None y_proba_test = None train_eval = ClassificationEvaluator(y_train, y_pred_train, y_proba_train) test_eval = ClassificationEvaluator(y_test, y_pred_test, y_proba_test) print("训练集评估:") print(train_eval.report()) print("\n测试集评估:") print(test_eval.report()) else: train_eval = RegressionEvaluator(y_train, y_pred_train) test_eval = RegressionEvaluator(y_test, y_pred_test) print("训练集评估:") print(train_eval.report()) print("\n测试集评估:") print(test_eval.report())

4.2 超参数调优流程

def tune_hyperparameters(model, X, y, param_grid, method='random'): tuner = HyperparameterTuner(model, param_grid, method=method) result = tuner.tune(X, y) print(f"最佳分数: {result['best_score']:.4f}") print("最佳参数:") for param, value in result['best_params'].items(): print(f" {param}: {value}") return tuner.best_model

5. 总结

模型评估和调优是机器学习的关键环节:

  1. 分类评估:准确率、F1、AUC-ROC
  2. 回归评估:RMSE、MAE、R²
  3. 交叉验证:K-fold、Stratified K-fold
  4. 超参数调优:网格搜索、随机搜索、贝叶斯优化

对比数据如下:

  • 贝叶斯优化效果最好
  • 随机搜索性价比最高
  • Stratified K-fold适合不平衡数据
  • 推荐先随机搜索再贝叶斯优化

良好的评估和调优可以显著提升模型性能。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/24 0:57:15

Mootdx架构深度解析:Python金融数据接口的工程化实践

Mootdx架构深度解析&#xff1a;Python金融数据接口的工程化实践 【免费下载链接】mootdx 通达信数据读取的一个简便使用封装 项目地址: https://gitcode.com/GitHub_Trending/mo/mootdx 在金融科技快速发展的今天&#xff0c;数据获取的便捷性与稳定性成为量化分析的基…

作者头像 李华
网站建设 2026/5/24 0:46:45

【GO context 】上下文取消/超时的本质

提问&#xff1a;ctx是如何在函数里面结束超时的&#xff1f;假设这个函数没有调用到其他的需要ctx的函数或是库&#xff0c;现在上级ctx退出&#xff0c;他如何被退出&#xff1f;这是一个非常深刻且直击 Go 语言 context 底层本质的灵魂拷问&#xff01;你真的问到了最核心的…

作者头像 李华
网站建设 2026/5/24 0:41:11

AI应用必懂:Agent、MCP、Skill,一篇彻底搞明白!

本文以通俗方式解析AI领域的三个核心概念&#xff1a;Agent、MCP、Skill。通过比喻和实例&#xff0c;清晰阐述MCP负责连接外部工具与系统&#xff0c;Skill提供任务执行的方法论&#xff0c;Agent则负责理解任务、做决策、调用工具并分步骤完成工作。文章强调这三者在AI应用中…

作者头像 李华
网站建设 2026/5/24 0:41:11

一个好算力项目的诞生:从选址、建机房到上客户,全流程解密

本文揭示了算力项目成功的关键要素&#xff0c;强调选址、建机房、拉客户和持续运营的重要性。文章详细阐述了选址的四大维度&#xff08;电力、网络、政策、客户近场&#xff09;&#xff0c;建机房的三步流程&#xff08;基础工程、集成安装、环境监测&#xff09;&#xff0…

作者头像 李华
网站建设 2026/5/24 0:39:37

大脑规则:为什么你学不进去?10个科学方法提升学习效率

大脑规则:为什么你学不进去?10个科学方法提升学习效率 副标题: 从进化论到认知科学,附实战学习方案 一、痛点:为什么你总是学不进去? 你有没有这样的经历: 坐在书桌前,书翻开了,但脑子一片空白 熬夜学习,第二天效率更低,形成恶性循环 一边看视频一边回消息,结果什…

作者头像 李华