Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
396 lines
11 KiB
Python
396 lines
11 KiB
Python
"""
|
|
Trend analysis module for evaluation history
|
|
"""
|
|
|
|
from typing import List, Dict, Any, Optional, Tuple
|
|
from datetime import datetime, timedelta
|
|
import statistics
|
|
|
|
from .history import HistoryManager
|
|
|
|
|
|
class TrendAnalyzer:
|
|
"""趋势分析器"""
|
|
|
|
def __init__(self, history_manager: HistoryManager):
|
|
"""
|
|
初始化趋势分析器
|
|
|
|
Args:
|
|
history_manager: 历史管理器
|
|
"""
|
|
self.history = history_manager
|
|
|
|
def compare_with_baseline(
|
|
self,
|
|
knowledge_base_id: str,
|
|
current_metrics: Dict[str, float],
|
|
baseline_evaluation_id: Optional[str] = None
|
|
) -> Dict[str, Dict[str, Any]]:
|
|
"""
|
|
与基线对比
|
|
|
|
Args:
|
|
knowledge_base_id: 知识库ID
|
|
current_metrics: 当前指标值
|
|
baseline_evaluation_id: 基线评估ID(可选,不指定则使用最新的历史记录)
|
|
|
|
Returns:
|
|
对比结果字典,每个指标包含 {current, baseline, change, change_pct, status}
|
|
"""
|
|
# 获取基线指标
|
|
if baseline_evaluation_id:
|
|
baseline_records = self.history.get_history_by_evaluation(baseline_evaluation_id)
|
|
baseline_metrics = {
|
|
record.metric_name: record.metric_value
|
|
for record in baseline_records
|
|
}
|
|
else:
|
|
baseline_metrics = self.history.get_latest_metrics(knowledge_base_id)
|
|
|
|
# 对比每个指标
|
|
comparison = {}
|
|
for metric_name, current_value in current_metrics.items():
|
|
baseline_value = baseline_metrics.get(metric_name)
|
|
|
|
if baseline_value is not None:
|
|
change = current_value - baseline_value
|
|
change_pct = (change / baseline_value * 100) if baseline_value != 0 else 0
|
|
|
|
# 判断状态
|
|
if abs(change_pct) < 1:
|
|
status = 'stable'
|
|
elif change_pct > 0:
|
|
status = 'improved'
|
|
else:
|
|
status = 'degraded'
|
|
|
|
comparison[metric_name] = {
|
|
'current': current_value,
|
|
'baseline': baseline_value,
|
|
'change': change,
|
|
'change_pct': change_pct,
|
|
'status': status
|
|
}
|
|
else:
|
|
comparison[metric_name] = {
|
|
'current': current_value,
|
|
'baseline': None,
|
|
'change': None,
|
|
'change_pct': None,
|
|
'status': 'new'
|
|
}
|
|
|
|
return comparison
|
|
|
|
def analyze_trend(
|
|
self,
|
|
knowledge_base_id: str,
|
|
metric_name: str,
|
|
days: int = 30
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
分析指标趋势
|
|
|
|
Args:
|
|
knowledge_base_id: 知识库ID
|
|
metric_name: 指标名称
|
|
days: 分析天数
|
|
|
|
Returns:
|
|
趋势分析结果
|
|
"""
|
|
trend_data = self.history.get_metric_trend(
|
|
knowledge_base_id, metric_name, days
|
|
)
|
|
|
|
if not trend_data:
|
|
return {
|
|
'metric': metric_name,
|
|
'status': 'no_data',
|
|
'message': '没有历史数据'
|
|
}
|
|
|
|
values = [item['value'] for item in trend_data]
|
|
|
|
# 计算统计信息
|
|
mean_value = statistics.mean(values)
|
|
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
|
min_value = min(values)
|
|
max_value = max(values)
|
|
|
|
# 计算趋势方向
|
|
trend_direction = self._calculate_trend_direction(values)
|
|
|
|
# 检测异常值
|
|
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
|
|
|
return {
|
|
'metric': metric_name,
|
|
'period_days': days,
|
|
'data_points': len(trend_data),
|
|
'statistics': {
|
|
'mean': mean_value,
|
|
'std_dev': std_dev,
|
|
'min': min_value,
|
|
'max': max_value,
|
|
'latest': values[-1],
|
|
'earliest': values[0]
|
|
},
|
|
'trend': {
|
|
'direction': trend_direction,
|
|
'change': values[-1] - values[0],
|
|
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
|
},
|
|
'anomalies': anomalies,
|
|
'data': trend_data
|
|
}
|
|
|
|
def analyze_all_trends(
|
|
self,
|
|
knowledge_base_id: str,
|
|
days: int = 30
|
|
) -> Dict[str, Dict[str, Any]]:
|
|
"""
|
|
分析所有指标的趋势
|
|
|
|
Args:
|
|
knowledge_base_id: 知识库ID
|
|
days: 分析天数
|
|
|
|
Returns:
|
|
所有指标的趋势分析结果
|
|
"""
|
|
trends = self.history.get_all_metrics_trend(knowledge_base_id, days)
|
|
|
|
results = {}
|
|
for metric_name, trend_data in trends.items():
|
|
if not trend_data:
|
|
continue
|
|
|
|
values = [item['value'] for item in trend_data]
|
|
|
|
mean_value = statistics.mean(values)
|
|
std_dev = statistics.stdev(values) if len(values) > 1 else 0
|
|
|
|
trend_direction = self._calculate_trend_direction(values)
|
|
anomalies = self._detect_anomalies(trend_data, mean_value, std_dev)
|
|
|
|
results[metric_name] = {
|
|
'period_days': days,
|
|
'data_points': len(trend_data),
|
|
'statistics': {
|
|
'mean': mean_value,
|
|
'std_dev': std_dev,
|
|
'min': min(values),
|
|
'max': max(values),
|
|
'latest': values[-1],
|
|
'earliest': values[0]
|
|
},
|
|
'trend': {
|
|
'direction': trend_direction,
|
|
'change': values[-1] - values[0],
|
|
'change_pct': ((values[-1] - values[0]) / values[0] * 100) if values[0] != 0 else 0
|
|
},
|
|
'anomalies': anomalies
|
|
}
|
|
|
|
return results
|
|
|
|
def detect_regression(
|
|
self,
|
|
knowledge_base_id: str,
|
|
current_metrics: Dict[str, float],
|
|
threshold_pct: float = 5.0
|
|
) -> List[Dict[str, Any]]:
|
|
"""
|
|
检测性能回归
|
|
|
|
Args:
|
|
knowledge_base_id: 知识库ID
|
|
current_metrics: 当前指标值
|
|
threshold_pct: 回归阈值百分比(默认5%)
|
|
|
|
Returns:
|
|
回归问题列表
|
|
"""
|
|
comparison = self.compare_with_baseline(
|
|
knowledge_base_id, current_metrics
|
|
)
|
|
|
|
regressions = []
|
|
for metric_name, comp in comparison.items():
|
|
if comp['status'] == 'degraded' and comp['change_pct'] is not None:
|
|
if abs(comp['change_pct']) >= threshold_pct:
|
|
regressions.append({
|
|
'metric': metric_name,
|
|
'current': comp['current'],
|
|
'baseline': comp['baseline'],
|
|
'change_pct': comp['change_pct'],
|
|
'severity': self._calculate_severity(comp['change_pct'])
|
|
})
|
|
|
|
# 按严重程度排序
|
|
regressions.sort(key=lambda x: abs(x['change_pct']), reverse=True)
|
|
|
|
return regressions
|
|
|
|
def generate_trend_summary(
|
|
self,
|
|
knowledge_base_id: str,
|
|
days: int = 30
|
|
) -> Dict[str, Any]:
|
|
"""
|
|
生成趋势摘要
|
|
|
|
Args:
|
|
knowledge_base_id: 知识库ID
|
|
days: 分析天数
|
|
|
|
Returns:
|
|
趋势摘要
|
|
"""
|
|
trends = self.analyze_all_trends(knowledge_base_id, days)
|
|
|
|
if not trends:
|
|
return {
|
|
'status': 'no_data',
|
|
'message': '没有历史数据'
|
|
}
|
|
|
|
# 统计各种趋势
|
|
improving_count = 0
|
|
stable_count = 0
|
|
degrading_count = 0
|
|
total_anomalies = 0
|
|
|
|
for metric_name, trend in trends.items():
|
|
direction = trend['trend']['direction']
|
|
if direction == 'improving':
|
|
improving_count += 1
|
|
elif direction == 'stable':
|
|
stable_count += 1
|
|
elif direction == 'degrading':
|
|
degrading_count += 1
|
|
|
|
total_anomalies += len(trend['anomalies'])
|
|
|
|
# 整体状态
|
|
if degrading_count > improving_count:
|
|
overall_status = 'degrading'
|
|
elif improving_count > degrading_count:
|
|
overall_status = 'improving'
|
|
else:
|
|
overall_status = 'stable'
|
|
|
|
return {
|
|
'period_days': days,
|
|
'total_metrics': len(trends),
|
|
'overall_status': overall_status,
|
|
'metrics_improving': improving_count,
|
|
'metrics_stable': stable_count,
|
|
'metrics_degrading': degrading_count,
|
|
'total_anomalies': total_anomalies,
|
|
'details': trends
|
|
}
|
|
|
|
def _calculate_trend_direction(
|
|
self,
|
|
values: List[float]
|
|
) -> str:
|
|
"""
|
|
计算趋势方向
|
|
|
|
使用简单线性回归的斜率判断趋势
|
|
|
|
Args:
|
|
values: 值列表
|
|
|
|
Returns:
|
|
趋势方向: 'improving', 'stable', 'degrading'
|
|
"""
|
|
if len(values) < 2:
|
|
return 'stable'
|
|
|
|
# 计算线性回归斜率
|
|
n = len(values)
|
|
x = list(range(n))
|
|
x_mean = statistics.mean(x)
|
|
y_mean = statistics.mean(values)
|
|
|
|
numerator = sum((x[i] - x_mean) * (values[i] - y_mean) for i in range(n))
|
|
denominator = sum((x[i] - x_mean) ** 2 for i in range(n))
|
|
|
|
if denominator == 0:
|
|
return 'stable'
|
|
|
|
slope = numerator / denominator
|
|
|
|
# 判断趋势
|
|
if abs(slope) < 0.001: # 斜率接近0
|
|
return 'stable'
|
|
elif slope > 0:
|
|
return 'improving'
|
|
else:
|
|
return 'degrading'
|
|
|
|
def _detect_anomalies(
|
|
self,
|
|
trend_data: List[Dict[str, Any]],
|
|
mean: float,
|
|
std_dev: float,
|
|
threshold: float = 2.0
|
|
) -> List[Dict[str, Any]]:
|
|
"""
|
|
检测异常值
|
|
|
|
使用标准差方法检测异常值
|
|
|
|
Args:
|
|
trend_data: 趋势数据
|
|
mean: 平均值
|
|
std_dev: 标准差
|
|
threshold: 异常阈值(标准差倍数)
|
|
|
|
Returns:
|
|
异常值列表
|
|
"""
|
|
if std_dev == 0:
|
|
return []
|
|
|
|
anomalies = []
|
|
for item in trend_data:
|
|
value = item['value']
|
|
z_score = abs((value - mean) / std_dev)
|
|
|
|
if z_score > threshold:
|
|
anomalies.append({
|
|
'timestamp': item['timestamp'],
|
|
'value': value,
|
|
'z_score': z_score,
|
|
'evaluation_id': item['evaluation_id']
|
|
})
|
|
|
|
return anomalies
|
|
|
|
def _calculate_severity(self, change_pct: float) -> str:
|
|
"""
|
|
计算回归严重程度
|
|
|
|
Args:
|
|
change_pct: 变化百分比
|
|
|
|
Returns:
|
|
严重程度: 'critical', 'high', 'medium', 'low'
|
|
"""
|
|
abs_change = abs(change_pct)
|
|
|
|
if abs_change >= 20:
|
|
return 'critical'
|
|
elif abs_change >= 10:
|
|
return 'high'
|
|
elif abs_change >= 5:
|
|
return 'medium'
|
|
else:
|
|
return 'low'
|