Permalink
Browse files

Added readme with usage, fixed issues under 1.9.2

  • Loading branch information...
1 parent 9a300d5 commit 8d144b320c20697e59a5f574328925e206cad094 @willcannings committed May 30, 2011
Showing with 42 additions and 7 deletions.
  1. +0 −6 README
  2. +36 −0 README.markdown
  3. +4 −0 lib/lsa.rb
  4. +2 −1 lib/svd_matrix.rb
View
6 README
@@ -1,6 +0,0 @@
-Singular Value Decomposition for Ruby with no dependency on GSL or LAPACK. Uses a C extension
-to the Numerical Recipies C implementation of an SVD matrix decomposer. Also includes an
-extension to the native Ruby Matrix class with a simple LSA method (decomposes the matrix,
-transposes matrix V, diagonalises the S array into a matrix, then removes all but the two
-leading terms in S to compress the original matrix to two dimensions).
-
View
36 README.markdown
@@ -0,0 +1,36 @@
+Ruby SVD
+========
+Singular Value Decomposition for Ruby with no dependency on GSL or LAPACK.
+
+About
+-----
+Ruby SVD provides an interface to the Numerical Recipies C implementation of an SVD matrix decomposer. It also includes an extension to the native Ruby Matrix class with a simple LSA
+method (decomposes the matrix, transposes matrix V, diagonalises the S array into a matrix, then removes all but the two leading terms in S to compress the original matrix to two dimensions).
+
+Sample Usage
+------------
+```ruby
+require 'ruby-svd'
+
+tdm = SVDMatrix.new(4, 2)
+tdm.set_row(0, [1,0])
+tdm.set_row(1, [1,0])
+tdm.set_row(2, [0,1])
+tdm.set_row(3, [0,1])
+
+puts "== Term document matrix:"
+p tdm
+
+puts "\n== Decomposing matrix:"
+lsa = LSA.new(tdm)
+p lsa
+
+puts "\n== Classifying new column vector: [1, 0.5, 0, 0.5]"
+puts "Format is [column, similarity]"
+ranks = lsa.classify_vector([1,0.5,0,0.5])
+p ranks
+
+sorted_ranks = ranks.sort_by(&:last).reverse
+puts "\n== Vector most similar to column #{sorted_ranks.first[0]}"
+p tdm.column(sorted_ranks.first[0])
+```
View
4 lib/lsa.rb
@@ -7,6 +7,10 @@ def initialize(matrix)
@u, @s, @v = matrix.decompose(2)
end
+ def inspect
+ "U:\n#{@u.inspect}\n\nS:\n#{@s.inspect}\n\nV:\n#{@v.inspect}"
+ end
+
# Return a distance (cosine similarity) between a new vector,
# and all the clusters (columns) used in the original matrix.
# Returns a sorted list of indexes and distances,
View
3 lib/svd_matrix.rb
@@ -7,6 +7,7 @@ class SVDMatrix < Matrix
# Create a new SVD Matrix with m rows, n columns
def initialize(m, n)
@rows = Array.new(m)
+ @column_size = n
m.times {|i| @rows[i] = Array.new(n)}
end
@@ -22,7 +23,7 @@ def set_row(i, row)
# Nicely formatted inspect string for the matrix
def inspect
- @rows.collect {|row| "#{row.inspect}\n"}
+ @rows.collect {|row| row.inspect}.join("\n")
end
# Perform SVD and decompose the matrix into three matrices:

0 comments on commit 8d144b3

Please sign in to comment.