Sha256: a4026e82342b0c19873450c20caab0a469ef14f6137674c53eeec5858fabb9f4

Contents?: true

Size: 1.27 KB

Versions: 2

Compression:

Stored size: 1.27 KB

Contents

module Semantic
  module Transform
    class LSA

      class << self

        def transform(matrix, number_of_dimensions_to_reduce = 1)
          columns = matrix.num_columns

          if number_of_dimensions_to_reduce <= columns #Its a valid reduction
            u, sigma, vt = matrix.singular_value_decomposition

            sigma_prime = reduce_dimensions(number_of_dimensions_to_reduce, sigma)

            matrix_prime = u * sigma_prime * vt
          else
            raise Exception, "dimension reduction cannot be greater than %s" % columns
          end
          
          matrix_prime
        end
        
        private
        def reduce_dimensions(number_of_dimensions_to_reduce, matrix)
          for diagonal_index in dimensions_to_be_reduced(matrix, number_of_dimensions_to_reduce)
            matrix[diagonal_index, diagonal_index] = 0
          end
          matrix
        end
        
        def dimensions_to_be_reduced(matrix, number_of_dimensions_to_reduce)
          (diagonal_matrix_length(matrix) - number_of_dimensions_to_reduce)...diagonal_matrix_length(matrix)
        end
        
        def diagonal_matrix_length(matrix)
          matrix.num_columns < matrix.num_rows ? matrix.num_columns : matrix.num_rows
        end
        
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 2 rubygems

Version Path
josephwilk-rsemantic-0.1.3 lib/semantic/transform/lsa_transform.rb
rsemantic-0.1.3 lib/semantic/transform/lsa_transform.rb