diff options
Diffstat (limited to 'lib/nlp_ruby/SparseVector.rb')
-rw-r--r-- | lib/nlp_ruby/SparseVector.rb | 43 |
1 files changed, 42 insertions, 1 deletions
diff --git a/lib/nlp_ruby/SparseVector.rb b/lib/nlp_ruby/SparseVector.rb index 0033690..9919a65 100644 --- a/lib/nlp_ruby/SparseVector.rb +++ b/lib/nlp_ruby/SparseVector.rb @@ -5,10 +5,14 @@ class SparseVector < Hash self.default = 0 end - def from_hash h + def from_h h h.each_pair { |k,v| self[k] = v } end + def from_s s + from_h eval(s) + end + def sum self.values.inject(:+) end @@ -48,6 +52,43 @@ class SparseVector < Hash dims.each { |d| sum += (self[d] - other[d])**2 } return Math.sqrt(sum) end + + def to_kv + a = [] + self.each_pair { |k,v| + a << "#{k}=#{v}" + } + return a.join ' ' + end + + def join_keys other + self.keys + other.keys + end + + def + other + new = SparseVector.new + join_keys(other).each { |k| + new[k] = self[k]+other[k] + } + return new + end + + def - other + new = SparseVector.new + join_keys(other).each { |k| + new[k] = self[k]-other[k] + } + return new + end + + def * scalar + raise ArgumentError, "Arg is not numeric #{scalar}" unless scalar.is_a? Numeric + new = SparseVector.new + self.keys.each { |k| + new[k] = self[k] * scalar + } + return new + end end def mean_sparse_vector array_of_vectors |