Last active
June 11, 2021 16:57
-
-
Save glaucocustodio/5dae79ed6f7d903ad631c0a60a6cb04c to your computer and use it in GitHub Desktop.
Implements 3 types of normalization in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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