Skip to content

Instantly share code, notes, and snippets.

@jremmen
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jremmen/9457357 to your computer and use it in GitHub Desktop.
Save jremmen/9457357 to your computer and use it in GitHub Desktop.
js: feature scaling using max - min or standard deviation
scale = function(a,d) { return a.map(function(x) { return (x - avg(a)) / d}) }
avg = function(a) { return sum(a) / a.length }
sum = function(a) { return a.reduce(function(x,y) { return x + y; }) }
max = function(a) { return a.sort(function(x,y) { return x < y; })[0] }
min = function(a) { return a.sort(function(x,y) { return x > y; })[0] }
sd = function(a,av) { return Math.sqrt(avg(a.map(function(x) { return (x - av) * x; }))); }
z = [20,25,10,33,50,42,19]
scale(z,(max(z) - min(z))) // [-0.2107142857142857, -0.23571428571428568, -0.2107142857142857, -0.08571428571428567, 0.11428571428571432, 0.3392857142857143, 0.5392857142857144]
scale(z, sd(z)) // [-1.418353378255674, -0.7256691702703448, -0.648704258271975, -0.2638796982801253, 0.35183959770683404, 1.0445238056921633, 1.6602431016791226]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment