콘텐츠로 이동
Search

Median absolute deviation

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

중앙값 절대 편차(median absolute deviation, 줄여서 MAD)는 평균 절대 편차(average absolute deviation)와 유사하지만 평균 대신 중앙값을 쓴다는 점이 다르다. 절대 편차(absolute deviation)의 일종이다.

구하는 공식은 아래와 같다.

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

관측값에서 중앙값을 뺀 값들의 중앙값을 구한다.

유사한 용어로 회귀 분석에 쓰는 최소 절대 편차(least absolute deviation)가 있다.

Python Code

WARNING

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 구현체

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