Sha256: 8a748fc5e7f49718960708a0047cd369efaa21e477d01fbfac49b8df490940a2

Contents?: true

Size: 1020 Bytes

Versions: 1

Compression:

Stored size: 1020 Bytes

Contents

require "matrix"

module Uranai
  class FeatureNormalizer
    def initialize(feature)
      @feature = feature
    end

    def normalize
      (matrix_feature - matrix_mean)
        .transpose
        .to_a
        .zip(std_of_each_feature)
        .map do |arr|
          arr[0].map { |ele| ele / arr[1] }
        end
    end

    private

    attr_reader :feature

    def matrix_feature
      Matrix.columns(feature)
    end

    def matrix_mean
      mean = Array([mean_of_each_feature]) * feature_size
      Matrix.rows(mean)
    end

    def mean_of_each_feature
      feature.map { |arr| mean(arr) }
    end

    def std_of_each_feature
      feature.map { |arr| std(arr) }
    end

    def feature_size
      feature[0].length
    end

    def mean(arr)
      arr.reduce(:+) / arr.length.to_f
    end

    def variance(arr)
      mean = mean(arr)
      sum = arr.inject(0.0) { |acc,i| acc + (i - mean)**2 }
      sum / (arr.length - 1)
    end

    def std(arr)
      Math.sqrt(variance(arr))
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
uranai-0.1.1 lib/uranai/feature_normalizer.rb