Class: SVMKit::Preprocessing::L2Normalizer

Inherits:
Object
  • Object
show all
Includes:
Base::BaseEstimator, Base::Transformer
Defined in:
lib/svmkit/preprocessing/l2_normalizer.rb

Overview

Normalize samples to unit L2-norm.

normalizer = SVMKit::Preprocessing::StandardScaler.new
new_samples = normalizer.fit_transform(samples)

Instance Attribute Summary collapse

Attributes included from Base::BaseEstimator

#params

Instance Method Summary collapse

Constructor Details

#initialize(_params = {}) ⇒ L2Normalizer

Create a new normalizer for normaliing to unit L2-norm.

:call-seq:

new() -> L2Normalizer


22
23
24
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 22

def initialize(_params = {})
  @norm_vec = nil
end

Instance Attribute Details

#norm_vecObject (readonly)

The vector consists of norms of each sample.



16
17
18
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 16

def norm_vec
  @norm_vec
end

Instance Method Details

#fit(x, _y = nil) ⇒ Object

Calculate L2 norms of each sample.

:call-seq:

fit(x) -> L2Normalizer
  • Arguments :

    • x (NMatrix, shape: [n_samples, n_features]) – The samples to calculate L2-norms.

  • Returns :

    • L2Normalizer



35
36
37
38
39
40
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 35

def fit(x, _y = nil)
  n_samples, = x.shape
  @norm_vec = NMatrix.new([1, n_samples],
                          Array.new(n_samples) { |n| x.row(n).norm2 })
  self
end

#fit_transform(x, _y = nil) ⇒ Object

Calculate L2 norms of each sample, and then normalize samples to unit L2-norm.

:call-seq:

fit_transform(x) -> NMatrix
  • Arguments :

    • x (NMatrix, shape: [n_samples, n_features]) – The samples to calculate L2-norms.

  • Returns :

    • The normalized samples (NMatrix)



51
52
53
54
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 51

def fit_transform(x, _y = nil)
  fit(x)
  x / @norm_vec.transpose.repeat(x.shape[1], 1)
end