It seems scipy once provided a function mad
to calculate the mean absolute deviation for a set of numbers:
http://projects.scipy.org/scipy/browser/trunk
I'm using:
from math import fabs
a = [1, 1, 2, 2, 4, 6, 9]
median = sorted(a)[len(a)//2]
for b in a:
mad = fabs(b - median)
print b,mad
I'm just learning Python and Numpy, but here is the code I wrote to check my 7th grader's math homework which wanted the M(ean)AD of 2 sets of numbers:
Data in Numpy matrix rows:
import numpy as np
>>> a = np.matrix( [ [ 80, 76, 77, 78, 79, 81, 76, 77, 79, 84, 75, 79, 76, 78 ], \\
... [ 66, 69, 76, 72, 79, 77, 74, 77, 71, 79, 74, 66, 67, 73 ] ], dtype=float )
>>> matMad = np.mean( np.abs( np.tile( np.mean( a, axis=1 ), ( 1, a.shape[1] ) ) - a ), axis=1 )
>>> matMad
matrix([[ 1.81632653],
[ 3.73469388]])
Data in Numpy 1D arrays:
>>> a1 = np.array( [ 80, 76, 77, 78, 79, 81, 76, 77, 79, 84, 75, 79, 76, 78 ], dtype=float )
>>> a2 = np.array( [ 66, 69, 76, 72, 79, 77, 74, 77, 71, 79, 74, 66, 67, 73 ], dtype=float )
>>> madA1 = np.mean( np.abs( np.tile( np.mean( a1 ), ( 1, len( a1 ) ) ) - a1 ) )
>>> madA2 = np.mean( np.abs( np.tile( np.mean( a2 ), ( 1, len( a2 ) ) ) - a2 ) )
>>> madA1, madA2
(1.816326530612244, 3.7346938775510199)
For what its worth, I use this for MAD:
def mad(arr):
""" Median Absolute Deviation: a "Robust" version of standard deviation.
Indices variabililty of the sample.
https://en.wikipedia.org/wiki/Median_absolute_deviation
"""
arr = np.ma.array(arr).compressed() # should be faster to not use masked arrays.
med = np.median(arr)
return np.median(np.abs(arr - med))
Using numpy
only:
def meanDeviation(numpyArray):
mean = np.mean(numpyArray)
f = lambda x: abs(x - mean)
vf = np.vectorize(f)
return (np.add.reduce(vf(numpyArray))) / len(numpyArray)