回归评估指标完整指南RMSE、MAE 与 WMAPE 的原理、公式、对比与实战
理解回归与预测任务中三大核心评估指标的数学本质、适用场景与选择策略
目录
一、概述:回归评估的基础
在回归和预测任务中,模型输出的是连续数值(如房价、温度、销量),而非离散类别。评估回归模型的核心思路是:比较预测值与真实值之间的误差,然后用一个标量指标汇总整体表现[1]。
yᵢ,预测值为 ŷᵢ,样本数为 n。误差 eᵢ = yᵢ - ŷᵢ。不同的汇总方式(取绝对值、取平方、归一化)产生了不同的评估指标,每种指标对误差的”惩罚方式”不同,因此适用的场景也不同。
1.1 三大指标速览
MAE
平均绝对误差。误差绝对值的平均。线性惩罚,直观易解释,对异常值鲁棒。RMSE
均方根误差。误差平方的平均再开根。二次惩罚,放大极端误差,对异常值敏感。WMAPE
加权平均绝对百分比误差。总绝对误差除以总真实值。无量纲百分比,按体量加权。二、MAE(平均绝对误差)
MAE(Mean Absolute Error)是所有样本误差绝对值的算术平均,是最直观的回归评估指标[2]。
2.1 直观理解
MAE 回答的问题是:“模型平均每次预测偏了多少?” 它的值与目标变量同单位,可以直接解释为”平均偏差 X 个单位”。例如,预测房价的 MAE = 5 万元,意味着模型平均每次偏离真实房价 5 万元[2]。
2.2 MAE 的核心特性
| 维度 | 说明 |
|---|---|
| 惩罚方式 | 线性惩罚(|e|),每个误差按其大小线性计入 |
| 单位 | 与目标变量相同(如元、℃、件) |
| 可解释性 | 极强——”平均偏差 X 个单位” |
| 异常值敏感性 | 低——一个 10 倍误差的样本只贡献 10 倍权重 |
| 最优误差分布 | 拉普拉斯分布(Laplacian)——中位数是最优估计 |
| 等价统计量 | MAE = E[|y – ŷ|],最小化 MAE 等价于预测中位数 |
三、RMSE(均方根误差)
RMSE(Root Mean Squared Error)先对误差取平方、求均值,再开根号,使得最终单位与目标变量一致[4]。
3.1 直观理解
RMSE 回答的问题是:“模型的大误差有多严重?” 由于先取平方再求均值,RMSE 对大误差施加了二次惩罚——一个误差为 10 的样本贡献 100,而误差为 1 的样本只贡献 1,两者比值为 100:1(而非 MAE 的 10:1)[4]。
3.2 RMSE 的核心特性
| 维度 | 说明 |
|---|---|
| 惩罚方式 | 二次惩罚(e²),大误差被平方放大 |
| 单位 | 与目标变量相同(开根号恢复单位) |
| 可解释性 | 中等——”有效误差幅度”,但不如 MAE 直观 |
| 异常值敏感性 | 高——一个极端误差会显著拉高整体 RMSE |
| 最优误差分布 | 正态分布(Gaussian)——均值是最优估计 |
| 等价统计量 | RMSE = √(E[(y-ŷ)²]),最小化 RMSE 等价于预测均值 |
| 恒等关系 | 恒有 RMSE ≥ MAE,等号仅当所有误差相等时成立 |
3.3 RMSE ≥ MAE 的数学证明
恒等不等式
由 Jensen 不等式(方差非负),对任意随机变量有:
E[|X|]² ≤ E[X²] 即 MAE² ≤ MSE = RMSE² ∴ RMSE ≥ MAE
等号成立当且仅当所有 |eᵢ| 相等(即所有样本的误差幅度完全一致)。
RMSE/MAE 比值是诊断异常值影响的有力工具:比值越接近 1,说明误差分布越均匀;比值远大于 1,说明存在少数极端误差[4]。
四、WMAPE(加权平均绝对百分比误差)
WMAPE(Weighted Mean Absolute Percentage Error)是 MAPE 的改进版,用总绝对误差除以总真实值,得到一个无量纲的百分比指标[5]。
4.1 与 MAPE 的关键区别
传统 MAPE 对每个样本计算百分比误差后取算术平均:
MAPE = (1/n) × Σ(|yᵢ - ŷᵢ| / |yᵢ|) × 100%
MAPE 的致命缺陷在于:当真实值 yᵢ 很小时(接近 0),单个样本的百分比误差会趋近无穷大,严重扭曲整体指标。WMAPE 通过改为”总误差 ÷ 总真实值”的汇总方式,从根本上避免了这个问题[5]。
❌ MAPE 的缺陷
样本 A:真实值=1,预测值=2 → 百分比误差=100%
样本 B:真实值=1000,预测值=1010 → 百分比误差=1%
MAPE = (100% + 1%)/2 = 50.5%
一个小体量样本的误差完全主导了整体指标。
✅ WMAPE 的改进
总绝对误差 = 1 + 10 = 11
总真实值 = 1 + 1000 = 1001
WMAPE = 11/1001 = 1.1%
大体量样本自动获得更高权重,结果更合理。
4.2 WMAPE 的核心特性
| 维度 | 说明 |
|---|---|
| 惩罚方式 | 线性惩罚(基于 |e|),但按真实值体量加权 |
| 单位 | 无量纲百分比(%),可跨数据集比较 |
| 可解释性 | 极强——”整体误差占总量的 X%” |
| 异常值敏感性 | 低——小体量异常样本不会主导指标 |
| 等价关系 | WMAPE = MAE / mean(|y|),即 MAE 除以真实值均值 |
| 零值问题 | 当 Σ|yᵢ| = 0 时无定义(需过滤或加平滑) |
| 对称性 | 不对称:高估和低估相同绝对值时 WMAPE 相同(但业务代价可能不同) |
五、三大指标对比
| 维度 | MAE | RMSE | WMAPE |
|---|---|---|---|
| 公式 | Σ|eᵢ|/n | √(Σeᵢ²/n) | Σ|eᵢ|/Σ|yᵢ| |
| 惩罚方式 | 线性 | 二次(平方) | 线性(加权) |
| 单位 | 与目标同单位 | 与目标同单位 | 百分比(无量纲) |
| 异常值敏感 | 低 | 高 | 低 |
| 可解释性 | 强(平均偏差) | 中(有效误差) | 强(误差占比) |
| 跨数据集可比 | 否(单位依赖) | 否(单位依赖) | 是(百分比) |
| 最优分布 | 拉普拉斯 | 正态分布 | — |
| 最小化等价 | 预测中位数 | 预测均值 | 加权中位数 |
5.1 数值示例
房价预测示例
5 套房屋的真实价格与预测价格如下:
样本 真实值 y 预测值 ŷ 误差 e |e| e² 1 100万 95万 5万 5 25 2 200万 210万 -10万 10 100 3 150万 145万 5万 5 25 4 80万 90万 -10万 10 100 5 300万 280万 20万 20 400 ───────────────────────────────────────────── 合计 830万 820万 — 50 650
MAE = 50/5 = 10 万元(平均偏差 10 万)
RMSE = √(650/5) = √130 ≈ 11.40 万元(受 e²=400 的样本 5 拉高)
WMAPE = 50/830 × 100% ≈ 6.02%(总误差占总真实值的 6%)
RMSE/MAE 比 = 11.40/10 = 1.14(接近 1,说明误差较均匀)
六、误差分布与最优指标
选择 MAE 还是 RMSE 不是主观偏好——而是由误差的统计分布决定。学术界对此有严格的理论依据[7]。
6.1 两种经典误差分布
正态分布误差
误差围绕 0 对称分布,大误差以指数速度衰减。多数样本误差较小,极端误差罕见。
最优指标:RMSE
最小化 RMSE 等价于最大似然估计,最优预测是条件均值。
典型场景:物理测量误差、传感器噪声、大多数自然现象。
拉普拉斯分布误差
误差分布尾部更重,极端值出现概率高于正态。少数样本可能产生较大误差。
最优指标:MAE
最小化 MAE 等价于最大似然估计,最优预测是条件中位数。
典型场景:销售预测、经济数据、含噪声的业务数据。
6.2 最大似然视角
为什么分布决定指标?
假设误差服从正态分布 N(0, σ²),其似然函数中取对数后的负项为 (e²)/(2σ²)。最大化似然等价于最小化 Σeᵢ²,即 MSE/RMSE。
假设误差服从拉普拉斯分布 L(0, b),其似然函数取对数后的负项为 |e|/b。最大化似然等价于最小化 Σ|eᵢ|,即 MAE。
因此,指标的选择本质上是对误差生成机制的假设。
七、异常值诊断
RMSE/MAE 比值是诊断数据中异常值影响程度的利器[4]。
| RMSE/MAE 比值 | 误差分布特征 | 诊断结论 | 建议 |
|---|---|---|---|
| ≈ 1.0 | 所有误差大小相近 | 均匀误差,无异常值 | MAE 和 RMSE 均可用 |
| 1.0 – 1.4 | 误差有一定变化 | 少量较大误差 | 两者差异不大,选任一 |
| 1.4 – 2.0 | 存在明显极端误差 | 少数异常值拉高 RMSE | 优先用 MAE;调查异常值 |
| > 2.0 | 严重极端值 | RMSE 被异常值严重扭曲 | 用 MAE;必须清洗数据 |
八、应用场景指南
⚡ 能源预测
推荐:RMSE
电力负荷预测中,极端偏差可能导致电网过载或停电。RMSE 的二次惩罚确保模型关注最坏情况。
🛒 零售销量预测
推荐:WMAPE
不同 SKU 销量差异巨大(畅销品 vs 滞销品)。WMAPE 按销量加权,避免小销量商品主导指标。
💰 金融风险预测
推荐:RMSE
极端预测偏差可能导致巨大损失。需要指标放大尾部风险,RMSE 的平方惩罚正符合需求。
📦 需求规划
推荐:MAE + WMAPE
需要知道”平均偏差多少件”(MAE)和”误差占总量百分比”(WMAPE)。两者搭配提供完整的业务视角。
8.1 选择决策流程
九、Python 代码示例
import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error # 真实值与预测值 y_true = np.array([100, 200, 150, 80, 300]) y_pred = np.array([95, 210, 145, 90, 280]) # ── MAE ── mae = mean_absolute_error(y_true, y_pred) print(f"MAE: {mae:.2f}") # MAE: 10.00 # ── RMSE ── rmse = np.sqrt(mean_squared_error(y_true, y_pred)) print(f"RMSE: {rmse:.2f}") # RMSE: 11.40 # ── WMAPE ── wmape = np.sum(np.abs(y_true - y_pred)) / np.sum(np.abs(y_true)) * 100 print(f"WMAPE: {wmape:.2f}%") # WMAPE: 6.02% # ── 诊断:RMSE/MAE 比值 ── ratio = rmse / mae print(f"RMSE/MAE ratio: {ratio:.2f}") # RMSE/MAE ratio: 1.14 (均匀误差,无明显异常值) # ── 对比:引入一个异常值后 ── y_true_out = np.array([100, 200, 150, 80, 300]) y_pred_out = np.array([95, 210, 145, 90, 100]) # 样本5偏差200 mae_out = mean_absolute_error(y_true_out, y_pred_out) rmse_out = np.sqrt(mean_squared_error(y_true_out, y_pred_out)) wmape_out = np.sum(np.abs(y_true_out - y_pred_out)) / np.sum(y_true_out) * 100 print(f"\n--- 含异常值 ---") print(f"MAE: {mae_out:.2f}") # MAE: 42.00 print(f"RMSE: {rmse_out:.2f}") # RMSE: 89.44 ← 被平方放大 print(f"WMAPE: {wmape_out:.2f}%") # WMAPE: 25.30% print(f"Ratio: {rmse_out/mae_out:.2f}") # Ratio: 2.13 ← 存在异常值! # ── 自定义 WMAPE 函数(处理零值)── def wmape(y_true, y_pred): """计算 WMAPE,处理总和为零的情况""" total_actual = np.sum(np.abs(y_true)) if total_actual == 0: return np.nan # 无法计算 return np.sum(np.abs(y_true - y_pred)) / total_actual * 100 # ── 交叉验证中同时计算多个指标 ── from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor(random_state=42) mae_scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_absolute_error") rmse_scores = cross_val_score(model, X, y, cv=5, scoring="neg_root_mean_squared_error") print(f"CV MAE: {-mae_scores.mean():.2f} ± {mae_scores.std():.2f}") print(f"CV RMSE: {-rmse_scores.mean():.2f} ± {rmse_scores.std():.2f}")
十、常见误区与最佳实践
| 误区 | 问题 | 纠正 |
|---|---|---|
| 只用 RMSE | 异常值严重扭曲指标 | 同时报告 MAE 和 RMSE |
| 用 MAPE 而非 WMAPE | 小真实值样本主导指标 | 改用 WMAPE 避免除零问题 |
| 跨数据集比 RMSE/MAE | 单位不同无法比较 | 用 WMAPE 等无量纲指标 |
| 忽略 RMSE/MAE 比值 | 无法诊断异常值影响 | 比值 >1.4 时调查极端误差 |
| 不画残差分布图 | 无法判断最优指标 | 先画残差直方图再选指标 |
| 直接删除异常值 | 可能丢失重要信息 | 先调查根因,再决定保留/修正/删除 |
| 只看单一指标做决策 | 片面评估模型 | 组合使用 MAE+RMSE+WMAPE |
Regression Metrics GuideRMSE, MAE & WMAPE: Principles, Formulas, Comparison & Practice
Understand the three core evaluation metrics for regression and forecasting tasks: mathematical essence, use cases, and selection strategy
Contents
- 1. Overview: Foundations of Regression Evaluation
- 2. MAE (Mean Absolute Error)
- 3. RMSE (Root Mean Squared Error)
- 4. WMAPE (Weighted Mean Absolute Percentage Error)
- 5. Three-Metric Comparison
- 6. Error Distribution & Optimal Metrics
- 7. Outlier Diagnostics
- 8. Application Scenario Guide
- 9. Python Code Examples
- 10. Common Pitfalls & Best Practices
1. Overview: Foundations of Regression Evaluation
In regression and forecasting tasks, models output continuous values (e.g., house prices, temperature, sales volume) rather than discrete classes. The core approach to evaluating regression models is: compare predicted values against true values, then summarize overall performance with a scalar metric[1].
yᵢ, predictions be ŷᵢ, and sample count be n. Error eᵢ = yᵢ - ŷᵢ. Different aggregation methods (absolute value, squaring, normalization) produce different metrics, each penalizing errors differently and thus suited to different scenarios.
1.1 Three Metrics at a Glance
MAE
Mean Absolute Error. Average of absolute errors. Linear penalty, intuitive, robust to outliers.RMSE
Root Mean Squared Error. Square → mean → root. Quadratic penalty, amplifies extreme errors, outlier-sensitive.WMAPE
Weighted MAPE. Total absolute error / total actual. Unitless percentage, volume-weighted.2. MAE (Mean Absolute Error)
MAE is the arithmetic mean of absolute errors across all samples—the most intuitive regression metric[2].
2.1 Intuitive Understanding
MAE answers: “On average, how far off is each prediction?” Its value shares the target variable’s unit, directly interpretable as “average deviation of X units.” For example, MAE = 50K for house price prediction means the model averages 50K off from true prices[2].
2.2 Key Characteristics
| Dimension | Description |
|---|---|
| Penalty | Linear (|e|), each error weighted proportionally |
| Unit | Same as target variable (¥, °C, units) |
| Interpretability | Excellent—”average deviation of X units” |
| Outlier sensitivity | Low—a 10× error contributes 10× weight |
| Optimal distribution | Laplacian—median is the optimal estimate |
| Equivalent statistic | MAE = E[|y – ŷ|]; minimizing MAE = predicting median |
3. RMSE (Root Mean Squared Error)
RMSE squares errors, takes the mean, then takes the square root—restoring the unit to match the target variable[4].
3.1 Intuitive Understanding
RMSE answers: “How severe are the large errors?” By squaring before averaging, RMSE applies quadratic penalty—a sample with error=10 contributes 100, while error=1 contributes only 1, a 100:1 ratio (vs. MAE’s 10:1)[4].
3.2 Key Characteristics
| Dimension | Description |
|---|---|
| Penalty | Quadratic (e²), large errors squared and amplified |
| Unit | Same as target variable (square root restores unit) |
| Interpretability | Moderate—”effective error magnitude,” less direct than MAE |
| Outlier sensitivity | High—one extreme error significantly inflates RMSE |
| Optimal distribution | Normal (Gaussian)—mean is the optimal estimate |
| Equivalent statistic | RMSE = √(E[(y-ŷ)²]); minimizing RMSE = predicting mean |
| Identity | Always RMSE ≥ MAE; equality iff all errors equal |
3.3 Mathematical Proof: RMSE ≥ MAE
Inequality
By Jensen’s inequality (non-negative variance), for any random variable:
E[|X|]² ≤ E[X²] i.e., MAE² ≤ MSE = RMSE² ∴ RMSE ≥ MAE
Equality holds iff all |eᵢ| are equal (all samples have identical error magnitude).
The RMSE/MAE ratio is a powerful diagnostic: ratio near 1 means uniform errors; ratio >> 1 indicates a few extreme errors[4].
4. WMAPE (Weighted Mean Absolute Percentage Error)
WMAPE is an improved version of MAPE that divides total absolute error by total actual values, yielding a unitless percentage[5].
4.1 Key Difference from MAPE
Traditional MAPE computes per-sample percentage errors then averages:
MAPE = (1/n) × Σ(|yᵢ - ŷᵢ| / |yᵢ|) × 100%
MAPE’s fatal flaw: when yᵢ is small (near 0), a single sample’s percentage error approaches infinity, severely distorting the overall metric. WMAPE avoids this by using “total error ÷ total actual”[5].
❌ MAPE’s Flaw
Sample A: actual=1, pred=2 → percentage error=100%
Sample B: actual=1000, pred=1010 → percentage error=1%
MAPE = (100% + 1%)/2 = 50.5%
A small-volume sample dominates the metric.
✅ WMAPE’s Fix
Total absolute error = 1 + 10 = 11
Total actual = 1 + 1000 = 1001
WMAPE = 11/1001 = 1.1%
Large-volume samples get proportionally more weight—result is reasonable.
4.2 Key Characteristics
| Dimension | Description |
|---|---|
| Penalty | Linear (based on |e|), weighted by actual volume |
| Unit | Unitless percentage (%), comparable across datasets |
| Interpretability | Excellent—”error is X% of total” |
| Outlier sensitivity | Low—small-volume anomalies don’t dominate |
| Equivalence | WMAPE = MAE / mean(|y|), i.e., MAE normalized by actual mean |
| Zero problem | Undefined when Σ|yᵢ| = 0 (needs filtering or smoothing) |
| Symmetry | Asymmetric: equal absolute over/underestimates yield same WMAPE |
5. Three-Metric Comparison
| Dimension | MAE | RMSE | WMAPE |
|---|---|---|---|
| Formula | Σ|eᵢ|/n | √(Σeᵢ²/n) | Σ|eᵢ|/Σ|yᵢ| |
| Penalty | Linear | Quadratic (squared) | Linear (weighted) |
| Unit | Same as target | Same as target | Percentage (unitless) |
| Outlier sensitivity | Low | High | Low |
| Interpretability | High (avg deviation) | Moderate | High (error %) |
| Cross-dataset | No (unit-dependent) | No (unit-dependent) | Yes (%) |
| Optimal distribution | Laplacian | Gaussian | — |
| Minimizing ≡ | Predict median | Predict mean | Weighted median |
5.1 Numerical Example
House Price Prediction Example
5 houses with true and predicted prices:
Sample Actual y Pred ŷ Error e |e| e² 1 100K 95K 5K 5 25 2 200K 210K -10K 10 100 3 150K 145K 5K 5 25 4 80K 90K -10K 10 100 5 300K 280K 20K 20 400 ───────────────────────────────────────────────── Total 830K 820K — 50 650
MAE = 50/5 = 10.00K (average deviation 10K)
RMSE = √(650/5) = √130 ≈ 11.40K (inflated by sample 5’s e²=400)
WMAPE = 50/830 × 100% ≈ 6.02% (error is 6% of total actual)
RMSE/MAE ratio = 11.40/10 = 1.14 (near 1, uniform errors)
6. Error Distribution & Optimal Metrics
Choosing MAE vs. RMSE isn’t subjective preference—it’s determined by the statistical distribution of errors. There’s rigorous theoretical backing[7].
6.1 Two Classic Error Distributions
Gaussian (Normal) Errors
Errors symmetric around 0, large errors decay exponentially. Most samples have small errors; extreme errors are rare.
Optimal metric: RMSE
Minimizing RMSE ≡ maximum likelihood estimation; optimal prediction is the conditional mean.
Typical: Physical measurements, sensor noise, most natural phenomena.
Laplacian Errors
Heavier tails—extreme values occur more frequently than Gaussian. A few samples may produce large errors.
Optimal metric: MAE
Minimizing MAE ≡ maximum likelihood estimation; optimal prediction is the conditional median.
Typical: Sales forecasting, economic data, noisy business data.
6.2 Maximum Likelihood Perspective
Why Distribution Determines Metric
Assuming errors ~ N(0, σ²) (Gaussian), the log-likelihood’s negative term is e²/(2σ²). Maximizing likelihood ≡ minimizing Σeᵢ² = MSE/RMSE.
Assuming errors ~ L(0, b) (Laplacian), the log-likelihood’s negative term is |e|/b. Maximizing likelihood ≡ minimizing Σ|eᵢ| = MAE.
Thus, the choice of metric is fundamentally an assumption about the error-generating mechanism.
7. Outlier Diagnostics
The RMSE/MAE ratio is a powerful tool for diagnosing the degree of outlier influence in data[4].
| RMSE/MAE Ratio | Error Distribution | Diagnosis | Recommendation |
|---|---|---|---|
| ≈ 1.0 | All errors similar | Uniform errors, no outliers | Either MAE or RMSE |
| 1.0 – 1.4 | Some variation | Few larger errors | Little difference; pick either |
| 1.4 – 2.0 | Clear extreme errors | Outliers inflate RMSE | Prefer MAE; investigate |
| > 2.0 | Severe extremes | RMSE badly distorted | Use MAE; clean data |
8. Application Scenario Guide
⚡ Energy Forecasting
Recommended: RMSE
In power load forecasting, extreme deviations can cause grid overload or blackouts. RMSE’s quadratic penalty ensures the model focuses on worst cases.
🛒 Retail Sales Forecasting
Recommended: WMAPE
Different SKUs have vastly different volumes (best-sellers vs slow-movers). WMAPE weights by volume, preventing small items from dominating.
💰 Financial Risk
Recommended: RMSE
Extreme prediction errors can cause huge losses. RMSE’s quadratic penalty amplifies tail risk—exactly what’s needed.
📦 Demand Planning
Recommended: MAE + WMAPE
Need to know “average deviation in units” (MAE) and “error as % of total” (WMAPE). Together they provide a complete business view.
8.1 Selection Decision Flow
9. Python Code Examples
import numpy as np from sklearn.metrics import mean_absolute_error, mean_squared_error # True values and predictions y_true = np.array([100, 200, 150, 80, 300]) y_pred = np.array([95, 210, 145, 90, 280]) # ── MAE ── mae = mean_absolute_error(y_true, y_pred) print(f"MAE: {mae:.2f}") # MAE: 10.00 # ── RMSE ── rmse = np.sqrt(mean_squared_error(y_true, y_pred)) print(f"RMSE: {rmse:.2f}") # RMSE: 11.40 # ── WMAPE ── wmape = np.sum(np.abs(y_true - y_pred)) / np.sum(np.abs(y_true)) * 100 print(f"WMAPE: {wmape:.2f}%") # WMAPE: 6.02% # ── Diagnostic: RMSE/MAE ratio ── ratio = rmse / mae print(f"RMSE/MAE ratio: {ratio:.2f}") # RMSE/MAE ratio: 1.14 (uniform errors, no significant outliers) # ── Comparison: with an outlier ── y_true_out = np.array([100, 200, 150, 80, 300]) y_pred_out = np.array([95, 210, 145, 90, 100]) # Sample 5 off by 200 mae_out = mean_absolute_error(y_true_out, y_pred_out) rmse_out = np.sqrt(mean_squared_error(y_true_out, y_pred_out)) wmape_out = np.sum(np.abs(y_true_out - y_pred_out)) / np.sum(y_true_out) * 100 print(f"\n--- With Outlier ---") print(f"MAE: {mae_out:.2f}") # MAE: 42.00 print(f"RMSE: {rmse_out:.2f}") # RMSE: 89.44 ← squared amplification print(f"WMAPE: {wmape_out:.2f}%") # WMAPE: 25.30% print(f"Ratio: {rmse_out/mae_out:.2f}") # Ratio: 2.13 ← outlier present! # ── Custom WMAPE function (handles zeros) ── def wmape(y_true, y_pred): """Calculate WMAPE, handling zero-sum case""" total_actual = np.sum(np.abs(y_true)) if total_actual == 0: return np.nan return np.sum(np.abs(y_true - y_pred)) / total_actual * 100 # ── Cross-validation with multiple metrics ── from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor(random_state=42) mae_scores = cross_val_score(model, X, y, cv=5, scoring="neg_mean_absolute_error") rmse_scores = cross_val_score(model, X, y, cv=5, scoring="neg_root_mean_squared_error") print(f"CV MAE: {-mae_scores.mean():.2f} ± {mae_scores.std():.2f}") print(f"CV RMSE: {-rmse_scores.mean():.2f} ± {rmse_scores.std():.2f}")
10. Common Pitfalls & Best Practices
| Pitfall | Problem | Correction |
|---|---|---|
| Using only RMSE | Outliers distort the metric | Report MAE and RMSE together |
| Using MAPE not WMAPE | Small-actual samples dominate | Switch to WMAPE to avoid division-by-zero |
| Comparing RMSE/MAE across datasets | Different units, not comparable | Use unitless WMAPE |
| Ignoring RMSE/MAE ratio | Can’t diagnose outlier impact | Investigate when ratio >1.4 |
| Not plotting residuals | Can’t determine optimal metric | Plot residual histogram first |
| Deleting outliers outright | May lose important info | Investigate root cause first |
| Single-metric decisions | One-sided evaluation | Use MAE+RMSE+WMAPE together |
