summaryrefslogtreecommitdiff
path: root/lib/nlp_ruby/SparseVector.rb
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2014-02-05 22:39:35 +0100
committerPatrick Simianer <p@simianer.de>2014-02-05 22:39:35 +0100
commit3db876b9fbd93670e421f0ddb627ca7463330533 (patch)
tree8e0b9b5abd09dc6d479fe76f21a97ab915e7ed8d /lib/nlp_ruby/SparseVector.rb
parent4228c0af3c550a85d37b5565a806b8864a774c83 (diff)
bleu, more methods for SparseVector, misc => bump to 0.2
Diffstat (limited to 'lib/nlp_ruby/SparseVector.rb')
-rw-r--r--lib/nlp_ruby/SparseVector.rb43
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