Sha256: 7566857fd6c0db6274e17e8182356bcfcf844a9ca5088ceb5d8b9db36abb249f

Contents?: true

Size: 938 Bytes

Versions: 1

Compression:

Stored size: 938 Bytes

Contents

module RSemantic
  module Transform
    class TFIDF

      @@number_of_documents_with_term = []
      def self.transform!(matrix)
        number_of_documents = matrix.size2
        @@number_of_documents_with_term = []

        matrix.transpose.enum_for(:each_row).with_index do |document, column_index|
          document.enum_for(:each).with_index do |term_weight, row_index|
            unless term_weight == 0.0
              inverse_document_frequency = 1 + GSL::Sf.log(number_of_documents / (number_of_documents_with_term(row_index, matrix).to_f + 1))
              term_frequency = Math.sqrt(term_weight)

              matrix[row_index, column_index] = term_frequency * inverse_document_frequency
            end
          end
        end
      end

      def self.number_of_documents_with_term(row_index, matrix)
        @@number_of_documents_with_term[row_index] ||= matrix.row(row_index).where.size
      end

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rsemantic-0.3.0 lib/rsemantic/transform/tf_idf_transform.rb