Skip to content

Instantly share code, notes, and snippets.

@asemic-horizon
Last active September 22, 2021 15:51
Show Gist options
  • Save asemic-horizon/93a9082863155f26e36ccd6aa39c3843 to your computer and use it in GitHub Desktop.
Save asemic-horizon/93a9082863155f26e36ccd6aa39c3843 to your computer and use it in GitHub Desktop.
def discrete_mode(zs):
return sorted(
[(x, len([y for y in xs if y == x])) \
for x in set(zs)],
key=lambda x:x[1],reverse=True)[0][0]
def _hsmode(zs, tol):
if len(zs)==1:
return zs[0]
elif len(zs)==2:
return (zs[0]+zs[1])/2
elif len(zs)==3:
if (zs[1]-zs[0]) < (zs[2]-zs[1]):
return (zs[0]+zs[1])/2
else:
return (zs[1]+zs[2])/2
elif abs(zs[-1] - zs[0]) <= tol:
return (zs[0]+zs[-1])/2
else:
h = math.floor(len(zs)/2)
if (zs[h]-zs[0]) < (zs[-1]-zs[h+1]):
return hsmode(zs[:h],tol)
else:
return hsmode(zs[h:],tol)
def hsmode(xs,tol=1e-4):
return _hsmode(sorted(xs),tol)
# Source and references:
# https://stats.stackexchange.com/questions/189379/finding-the-peak-of-a-kernel-density-estimator
# Bickel, D.R. 2002. Robust estimators of the mode and skewness of continuous data. Computational Statistics & Data Analysis 39: 153-163.
# Bickel, D.R. and R. Frühwirth. 2006. On a fast, robust estimator of the mode: comparisons to other estimators with applications. Computational Statistics & Data Analysis 50: 3500-3530.
# Dalenius, T. 1965. The mode - A neglected statistical parameter.
# Journal, Royal Statistical Society A 128: 110-117.
# Robertson, T. and J.D. Cryer. 1974. An iterative procedure for estimating the mode. Journal, American Statistical Association 69: 1012-1016.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment