【机器学习】平均绝对误差(MAE:Mean Absolute Error)

平均绝对误差 (Mean Absolute Error, MAE) 是一种衡量预测值与实际值之间平均差异的统计指标。它在机器学习、统计学等领域中广泛应用,用于评估模型的预测精度。与均方误差 (MSE) 或均方误差根 (RMSE) 不同,MAE 使用误差的绝对值,因此它在处理异常值时更加稳定。

1. MAE 的定义和公式

给定预测值 \hat{y}_i​ 和真实值 y_i,MAE 的公式为:

\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |\hat{y}_i - y_i|

其中:

  • n 是样本总数。
  • \hat{y}_i 是模型的预测值。
  • y_i​ 是对应的真实值。

MAE 表示了预测值与真实值之间的平均绝对差异。由于取了绝对值,每个误差的正负号被忽略,保证了所有差异的非负性。

2. MAE 的计算步骤

计算 MAE 的步骤如下:

  1. 求出误差:计算预测值 \hat{y}_i 与真实值 y_i 之间的差异。
  2. 取绝对值:计算每个误差的绝对值,以确保所有差异都是正值。
  3. 求均值:将所有误差的绝对值加总,并除以样本数量 n,得到 MAE。

3. MAE 的性质和意义

  • 易于解释:MAE 具有与原始数据相同的单位,直接表示预测值与真实值的平均差距,因而易于理解和解释。
  • 对异常值更稳定:相比 MSE 和 RMSE,MAE 对异常值不敏感,不会因为少数大误差的平方而放大结果,适用于具有较多异常值的数据集。
  • 偏好绝对误差:由于 MAE 忽略了误差的正负号,它无法提供误差的方向性信息。

4. MAE 的优缺点

优点

  • 简单直观:MAE 仅计算绝对误差的平均值,简单明了。
  • 对异常值稳定:由于没有误差平方的放大效应,MAE 不易受异常值的影响,更能反映数据的整体趋势。

缺点

  • 缺乏方向性:由于计算绝对误差,MAE 无法反映出误差是正偏还是负偏,可能不适用于需要区分偏差方向的应用场景。
  • 较低的区分度:MAE 没有放大误差的功能,因此在评估较复杂模型的表现时,可能没有 RMSE 那样敏感。

5. MAE 的应用

MAE 是回归问题中常用的评估指标,广泛应用于以下场景:

  • 时间序列预测:在金融、气象等时间序列预测问题中,MAE 可以用来评估预测精度。
  • 经济预测:在经济领域,MAE 用于衡量经济指标的预测偏差,帮助判断模型的可靠性。
  • 机器学习模型的比较:MAE 在回归模型的评估中用于衡量不同模型的预测效果,是算法调优时

6.Python 实现代码

import numpy as np

def mae(y_true, y_pred):
    return np.mean(np.abs(y_pred - y_true))

# 示例
y_true = np.array([3, -0.5, 2, 7])
y_pred = np.array([2.5, 0.0, 2, 8])

result = mae(y_true, y_pred)
print("MAE:", result)

说明

  1. y_true 为真实值数组,y_pred 为预测值数组。
  2. np.abs(y_pred - y_true) 计算每个误差的绝对值。
  3. np.mean(...) 求所有误差的绝对值的平均,得到 MAE。

图中 MAE 值越小表示预测越准确。

7. MAE 的图解说明

上图展示了 MAE 的计算过程,其中:

  • 蓝色圆点连线代表真实值 y。
  • 红色叉点连线代表预测值 \hat{y}​。
  • 每条灰色虚线表示预测值和真实值之间的绝对误差。
# MAE Python implementation and visualization

import numpy as np
import matplotlib.pyplot as plt

# Generate sample data for illustration
np.random.seed(0)
x = np.linspace(0, 10, 10)                   # Independent variable (e.g., input feature)
y_true = 2 * x + 1                           # True relationship (e.g., ground truth values)
y_pred = y_true + np.random.normal(0, 2, 10) # Predicted values with random noise

# Calculate MAE
mae_value = np.mean(np.abs(y_pred - y_true))

# Plotting the true vs. predicted values with errors
plt.figure(figsize=(10, 6))
plt.plot(x, y_true, label="True Values", color="blue", marker='o')
plt.plot(x, y_pred, label="Predicted Values", color="red", marker='x')
plt.vlines(x, y_true, y_pred, colors='gray', linestyles='dotted', label='Absolute Errors')

# Adding text and labels
plt.xlabel("x")
plt.ylabel("y")
plt.title(f"Illustration of MAE (Mean Absolute Error)\nMAE = {mae_value:.2f}")
plt.legend()
plt.grid(True)
plt.show()

可以用垂直线表示预测值与实际值之间的绝对误差,每条线段的长度对应于预测值和真实值的差异。以下是一个 MAE 的计算图解步骤:

  1. 绘制真实值和预测值的散点图:将实际值和预测值分别绘制在坐标图上。
  2. 计算误差:每个预测点到真实点的垂直线段代表误差的绝对值。
  3. 平均误差长度:将这些垂直线段的长度平均,即得到 MAE。

通过这样的图示,MAE 能帮助直观展示预测结果与实际情况的整体差异。

8. MAE 与 RMSE 的对比

指标MAERMSE
计算方式绝对误差的均值平方误差的均值开平方根
对异常值敏感性
是否反映方向性
应用场景数据含有较多异常值的数据集对精度要求高的数据分析场景

9. 结论

MAE 是一种简单、直观且对异常值较为稳定的误差度量方法。它适合用于需要估计预测与真实值间差距的应用场景。对于希望避免极端值过度影响的情况,MAE 是一个有效的选择。而在需要更精细的模型评价时,通常会与 RMSE 一起使用,从而更全面地评估模型的预测表现。

03-08
### Mean Absolute Error (MAE) in Machine Learning In machine learning, particularly within regression tasks, evaluating model performance is crucial. One common metric used for this purpose is the **Mean Absolute Error (MAE)**. MAE measures the average magnitude of errors between predicted values and actual values without considering their direction. This means that all individual differences are treated as positive distances. The formula for calculating MAE can be expressed as follows: \[ \text{MAE} = \frac{1}{n}\sum_{i=1}^{n}|y_i - \hat{y}_i| \] where \( y_i \) represents the true value, \( \hat{y}_i \) denotes the prediction made by the model, and \( n \) stands for the total number of predictions[^2]. Compared to other metrics like Mean Squared Error (MSE), which squares the difference before averaging, MAE provides a more interpretable scale because it directly averages the absolute differences. However, unlike MSE, MAE does not penalize larger errors as heavily since no squaring operation amplifies these discrepancies. When implementing models using frameworks or libraries such as TensorFlow or PyTorch, one might encounter options to compute loss functions including MAE during training phases. For instance, after turning off gradient checking and utilizing backpropagation code specifically designed for learning purposes, ensuring accurate computation of losses becomes essential for effective optimization processes[^1]. Additionally, while tuning hyperparameters like `learning rate`, activation functions (`sigmoid` vs `ReLU`), and batch sizes, monitoring how changes affect evaluation metrics—including MAE—can provide insights into improving predictive accuracy[^4]. #### Example Code Snippet for Computing MAE To illustrate computing MAE programmatically, consider the following Python snippet using NumPy: ```python import numpy as np def mean_absolute_error(y_true, y_pred): """ Computes the Mean Absolute Error. Parameters: y_true : array-like of shape (n_samples,) Ground truth target values. y_pred : array-like of shape (n_samples,) Estimated targets as returned by a regressor. Returns: float: The computed MAE score. """ mae = np.mean(np.abs(y_true - y_pred)) return mae ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值