Skip to content

Instantly share code, notes, and snippets.

@glaucocustodio
Last active June 11, 2021 16: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 glaucocustodio/5dae79ed6f7d903ad631c0a60a6cb04c to your computer and use it in GitHub Desktop.
Save glaucocustodio/5dae79ed6f7d903ad631c0a60a6cb04c to your computer and use it in GitHub Desktop.
Implements 3 types of normalization in ruby
class Array
# Few types of normalizations
# https://developers.google.com/machine-learning/data-prep/transform/normalization
def normalize
return if self.empty?
x_min, x_max = self.minmax
dx = (x_max-x_min).to_f
self.map { ((_1 - x_min) / dx) * 100 }
end
def mean_normalize
return if self.empty?
mean = self.reduce(&:+) / self.count
self.map { _1 / mean }
end
def clipping_normalize(max = nil)
max ||= self.max
self.map { _1 > max ? max : _1 }.normalize
end
# not a normalization but I find it useful
def geometric_mean
return if self.empty?
self.reduce(&:*) ** (1.0 / self.count)
end
end
# usage ex:
[1,2,3].normalize
# => [0.0, 50.0, 100.0]
# x can't be greater than 2
[1,2,3].clipping_normalize(2)
# => [0.0, 100.0, 100.0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment