From 062eda911830c779aa685885b8e15ecceabfc085 Mon Sep 17 00:00:00 2001 From: Patrick Simianer Date: Fri, 14 Feb 2014 18:56:47 +0100 Subject: some class methods; Translation scores dict; DAG edges->outgoing; TFIDF module --- lib/nlp_ruby/SparseVector.rb | 57 +++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 17 deletions(-) (limited to 'lib/nlp_ruby/SparseVector.rb') diff --git a/lib/nlp_ruby/SparseVector.rb b/lib/nlp_ruby/SparseVector.rb index b80373c..3096412 100644 --- a/lib/nlp_ruby/SparseVector.rb +++ b/lib/nlp_ruby/SparseVector.rb @@ -12,14 +12,32 @@ class SparseVector < Hash a.each_with_index { |i,j| self[j] = i } end + def self.from_a a + v = SparseVector.new + v.from_a a + return v + end + def from_h h h.each_pair { |k,v| self[k] = v } end + def self.from_h h + v = SparseVector.new + v.from_h h + return v + end + def from_s s from_h eval(s) end + def self.from_s s + v = SparseVector.new + v.from_s s + return v + end + def to_kv sep='=', join=' ' a = [] self.each_pair { |k,v| @@ -35,6 +53,12 @@ class SparseVector < Hash } end + def self.from_kv s + v = SparseVector.new + v.from_kv s + return v + end + def from_file fn, sep='=' f = ReadFile.new(fn) while line = f.gets @@ -44,6 +68,12 @@ class SparseVector < Hash end end + def self.from_file fn, sep='=' + v = SparseVector.new + v.from_file fn, sep + return v + end + def join_keys other self.keys + other.keys end @@ -126,24 +156,17 @@ class SparseVector < Hash } return new end -end - - -module SparseVector - -def SparseVector::mean a - mean = SparseVector.new - a.each { |i| - i.each_pair { |k,v| - mean[k] += v + def self.mean a + mean = SparseVector.new + a.each { |i| + i.each_pair { |k,v| + mean[k] += v + } } - } - n = array_of_vectors.size.to_f - mean.each_pair { |k,v| mean[k] = v/n } - return mean -end - - + n = a.size.to_f + mean.each_pair { |k,v| mean[k] = v/n } + return mean + end end -- cgit v1.2.3