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.

Examples:

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

#initializeL2Normalizer

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



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

def initialize
  @params = {}
  @norm_vec = nil
end

Instance Attribute Details

#norm_vecNumo::DFloat (readonly)

Return the vector consists of L2-norm for each sample.

Returns:

  • (Numo::DFloat)

    (shape: [n_samples])



20
21
22
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 20

def norm_vec
  @norm_vec
end

Instance Method Details

#fit(x) ⇒ L2Normalizer

Calculate L2-norms of each sample.

Parameters:

  • x (Numo::DFloat)

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

Returns:



34
35
36
37
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 34

def fit(x, _y = nil)
  @norm_vec = Numo::NMath.sqrt((x**2).sum(1))
  self
end

#fit_transform(x) ⇒ Numo::DFloat

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

Parameters:

  • x (Numo::DFloat)

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

Returns:

  • (Numo::DFloat)

    The normalized samples.



45
46
47
48
# File 'lib/svmkit/preprocessing/l2_normalizer.rb', line 45

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