Skip to content
Search

Median absolute deviation

lastmod 2024-02-21created 2024-02-215 edits

The median absolute deviation (MAD) is similar to the average absolute deviation, but differs in that it uses the median instead of the mean. It is a kind of absolute deviation.

The formula is as follows.

\(MAD = median( | X_{i} - median(X) | )\)

Take the median of the values obtained by subtracting the median from the observations.

A similar term is the least absolute deviation, used in regression analysis.

Python Code

WARNING

This code was generated by GPT 3.5.

import numpy as np

# 주어진 데이터
x_coords = [...]  # x 좌표 데이터
y_coords = [...]  # y 좌표 데이터

# 중앙값 계산
x_median = np.median(x_coords)
y_median = np.median(y_coords)

# 절대 편차 계산
x_abs_deviation = np.abs(x_coords - x_median)
y_abs_deviation = np.abs(y_coords - y_median)

# MAD 계산
x_mad = np.median(x_abs_deviation)
y_mad = np.median(y_abs_deviation)

print("Median Absolute Deviation (MAD) for x-coordinates:", x_mad)
print("Median Absolute Deviation (MAD) for y-coordinates:", y_mad)

statsmodels implementation

Located at statsmodels/robust/scale.py.

import numpy as np
from scipy.stats import norm as Gaussian

from statsmodels.tools import tools
from statsmodels.tools.validation import array_like, float_like

from . import norms
from ._qn import _qn


def mad(a, c=Gaussian.ppf(3 / 4.0), axis=0, center=np.median):
    """
    The Median Absolute Deviation along given axis of an array

    Parameters
    ----------
    a : array_like
        Input array.
    c : float, optional
        The normalization constant.  Defined as scipy.stats.norm.ppf(3/4.),
        which is approximately 0.6745.
    axis : int, optional
        The default is 0. Can also be None.
    center : callable or float
        If a callable is provided, such as the default `np.median` then it
        is expected to be called center(a). The axis argument will be applied
        via np.apply_over_axes. Otherwise, provide a float.

    Returns
    -------
    mad : float
        `mad` = median(abs(`a` - center))/`c`
    """
    a = array_like(a, "a", ndim=None)
    c = float_like(c, "c")
    if not a.size:
        center_val = 0.0
    elif callable(center):
        if axis is not None:
            center_val = np.apply_over_axes(center, a, axis)
        else:
            center_val = center(a.ravel())
    else:
        center_val = float_like(center, "center")
    err = (np.abs(a - center_val)) / c
    if not err.size:
        if axis is None or err.ndim == 1:
            return np.nan
        else:
            shape = list(err.shape)
            shape.pop(axis)
            return np.empty(shape)
    return np.median(err, axis=axis)

See also

Favorite site

author Zer0 sitemap