clusterer 0.1.0 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,54 @@
1
+ #--
2
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ module Clusterer
24
+ module DocumentVector
25
+ module InstanceMethods
26
+ attr_accessor :position
27
+
28
+ def cosine_similarity(doc)
29
+ return 1.0 unless doc# && doc.centroid
30
+ self.dot((doc.class == DocumentsCentroidVector ? doc.centroid : doc)) #.transpose
31
+ end
32
+ end
33
+
34
+ module ClassMethods
35
+ def centroid_class
36
+ DocumentsCentroidVector
37
+ end
38
+ end
39
+ end
40
+ end
41
+
42
+ if $LINALG == true
43
+ module Linalg
44
+ class DMatrix
45
+ include Clusterer::DocumentVector::InstanceMethods
46
+ extend Clusterer::DocumentVector::ClassMethods
47
+ end
48
+ end
49
+ else
50
+ class Vector
51
+ include Clusterer::DocumentVector::InstanceMethods
52
+ extend Clusterer::DocumentVector::ClassMethods
53
+ end
54
+ end
@@ -0,0 +1,51 @@
1
+ #--
2
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ module Clusterer
24
+ class DocumentsCentroidVector
25
+ attr_reader :no_of_documents
26
+ attr_reader :centroid
27
+
28
+ def initialize(docs = [])
29
+ @no_of_documents = docs.size
30
+ return if @no_of_documents == 0
31
+ @centroid = docs[0]
32
+ docs.slice(1..docs.length).each {|d| @centroid = @centroid + d}
33
+ @centroid = @centroid / @no_of_documents
34
+ end
35
+
36
+ def to_dmatrix
37
+ @centroid
38
+ end
39
+
40
+ def merge!(centroid)
41
+ return unless centroid.centroid
42
+ unless @centroid
43
+ @centroid = centroid.centroid
44
+ @no_of_documents = centroid.no_of_documents
45
+ else
46
+ @centroid = (@centroid * @no_of_documents) + (centroid.centroid * centroid.no_of_documents)
47
+ @centroid = @centroid / (@no_of_documents += centroid.no_of_documents)
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,95 @@
1
+ #--
2
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ begin
24
+ require 'linalg'
25
+ $LINALG = true
26
+ rescue LoadError
27
+ warn 'For faster LSI support, please install Linalg: '
28
+ require 'clusterer/lsi/dmatrix'
29
+ end
30
+
31
+ require 'clusterer/lsi/document_vector'
32
+ require 'clusterer/lsi/documents_centroid_vector'
33
+
34
+ module Clusterer
35
+ class Lsi
36
+ include Linalg if $LINALG
37
+
38
+ attr_reader :documents
39
+ def initialize(docs)
40
+ @documents = docs
41
+ end
42
+
43
+ def rebuild_if_needed
44
+ perform_svd unless @t && @d && @s
45
+ end
46
+
47
+ def clear_cached_results
48
+ @t= @s= @d= @s_inv= @sd= nil
49
+ end
50
+
51
+ def perform_svd (cutoff = 0.80)
52
+ matrix = DMatrix[*@documents].transpose
53
+ @t, @s, @d = matrix.svd
54
+ val = @s.trace * cutoff
55
+ cnt = -1
56
+ (0..([@s.nrow, @s.ncol].min - 1)).inject(0) {|n,v| cnt += 1; (n > val) ? break : n + @s[v,v] }
57
+ @t = DMatrix.join_columns((0..cnt).collect {|i|@t.column(i) })
58
+ @d = DMatrix.join_rows((0..cnt).collect {|i| @d.row(i) })
59
+ @s = DMatrix.join_columns((0..cnt).collect {|i|@s.column(i) })
60
+ @s = DMatrix.join_rows((0..cnt).collect {|i|@s.row(i) }) unless @s.ncol == cnt
61
+ end
62
+
63
+ def cluster_documents(k, options = { })
64
+ rebuild_if_needed
65
+ cnt = -1
66
+ clusters = Algorithms.send(options[:algorithm] || :kmeans,
67
+ sd.columns.collect{|c| c.position = (cnt += 1); c}, k, options)
68
+ clusters.collect {|clus| clus.documents.collect {|d| @documents[d.position]}}
69
+ end
70
+
71
+ def search(document, threshold = 0.5)
72
+ rebuild_if_needed
73
+ vec = $LINALG ? DMatrix[document] : DMatrix[document] #DMatrix[document] #transform_to_vector(document)
74
+ vec = (vec * @t) * s_inv
75
+ results = []
76
+ vec = (vec * @s).transpose # * @s
77
+ vec = vec.column(0) unless $LINALG
78
+ sd.columns.each_with_index {|d,i| results << documents[i] if d.cosine_similarity(vec) >= threshold}
79
+ results
80
+ end
81
+
82
+ def <<(doc)
83
+ @documents << doc
84
+ end
85
+
86
+ private
87
+ def sd
88
+ @sd ||= @s*@d
89
+ end
90
+
91
+ def s_inv
92
+ @s_inv ||= @s.inverse
93
+ end
94
+ end
95
+ end
@@ -0,0 +1,34 @@
1
+ #The MIT License
2
+
3
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
4
+
5
+ module Clusterer
6
+ module DocumentSimilarity
7
+ #find similarity between two documents, or cluster centroids
8
+ def cosine_similarity(document)
9
+ return 1.0 if self.empty? || document.nil? || document.empty?
10
+ similarity = 0
11
+ self.each do |w,value|
12
+ similarity += (value * (document[w] || 0))
13
+ end
14
+ similarity /= (self.vector_length * document.vector_length)
15
+ end
16
+ end
17
+
18
+ module ClusterSimilarity
19
+ #the algorithms given below find similarity between two clusters
20
+ def intra_cluster_similarity(y)
21
+ (self+y).intra_cluster_cosine_similarity - self.intra_cluster_cosine_similarity - y.intra_cluster_cosine_similarity
22
+ end
23
+
24
+ def centroid_similarity(y)
25
+ self.centroid.cosine_similarity(y.centroid)
26
+ end
27
+
28
+ def upgma(y)
29
+ self.documents.inject(0) do |n,d|
30
+ n + y.documents.inject(0) {|s,e| s + d.cosine_similarity(e) }
31
+ end / (self.documents.size * y.documents.size)
32
+ end
33
+ end
34
+ end
@@ -1,28 +1,26 @@
1
- #The MIT License
2
-
1
+ #--
3
2
  ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
4
22
 
5
- begin
6
- require 'stemmer'
7
- rescue LoadError
8
- puts "Please install stemmer from http://rubyforge.org/projects/stemmer or 'gem install stemmer'"
9
- exit(-1)
10
- end
11
-
12
- class String
13
- def clean_word_hash
14
- word_hash gsub(/[^\w\s]/,"").split
15
- end
16
- private
17
- def word_hash(words)
18
- h = Hash.new
19
- words.each do |w|
20
- w = w.downcase.stem
21
- h[w] = (h[w] || 0) + 1 if w.size > 2 and !STOP_WORDS.include?(w)
22
- end
23
- h
24
- end
25
-
23
+ module Clusterer
26
24
  STOP_WORDS = ["and",
27
25
  "but",
28
26
  "came",
@@ -0,0 +1,70 @@
1
+ #--
2
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
3
+ #
4
+ # Permission is hereby granted, free of charge, to any person obtaining
5
+ # a copy of this software and associated documentation files (the
6
+ # "Software"), to deal in the Software without restriction, including
7
+ # without limitation the rights to use, copy, modify, merge, publish,
8
+ # distribute, sublicense, and/or sell copies of the Software, and to
9
+ # permit persons to whom the Software is furnished to do so, subject to
10
+ # the following conditions:
11
+ #
12
+ # The above copyright notice and this permission notice shall be
13
+ # included in all copies or substantial portions of the Software.
14
+ #
15
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16
+ # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17
+ # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18
+ # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
19
+ # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
20
+ # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
21
+ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
+
23
+ begin
24
+ require 'stemmer'
25
+ rescue LoadError
26
+ puts "If you want to use stemming for better performance, then please install stemmer from http://rubyforge.org/projects/stemmer or 'gem install stemmer'"
27
+ class String
28
+ def stem
29
+ self
30
+ end
31
+ end
32
+ end
33
+
34
+ module Clusterer
35
+ #the tokenizer algorithms take a block, to which the string tokens are passed
36
+
37
+ module Tokenizer
38
+ def simple_tokenizer (text, options = {})
39
+ text.gsub(/[^\w\s]/,"").split.each do |word|
40
+ word.downcase!
41
+ word = word.stem unless options[:no_stem]
42
+ yield(word) if word.size > 2 and !STOP_WORDS.include?(word)
43
+ end
44
+ end
45
+
46
+ def simple_ngram_tokenizer (text, options = {})
47
+ ngram = options[:ngram] || 3
48
+
49
+ ngram_list = (0..ngram).collect { []}
50
+ text.split(/[\.\?\!]/).each do |sentence|
51
+ #split the text into sentences, Ngrams cannot straddle sentences
52
+
53
+ sentence.gsub(/[^\w\s]/,"").split.each do |word|
54
+ word.downcase!
55
+ word = word.stem unless options[:no_stem]
56
+ if word.size > 2 and !STOP_WORDS.include?(word)
57
+ yield(word)
58
+ 2.upto(ngram) do |i|
59
+ ngram_list[i].delete_if {|j| j << word; j.size == i ? (yield(j.join(" ")); true) : false}
60
+ ngram_list[i] << [word]
61
+ end
62
+ else
63
+ #the ngrams cannot have a stop word at beginning and end
64
+ 2.upto(ngram) {|i| ngram_list[i].delete_if {|j| (j.size == i - 1) ? true : (j << word; false)}}
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,48 @@
1
+ #The MIT License
2
+
3
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
4
+
5
+ $:.unshift File.join(File.dirname(__FILE__), "..", "lib")
6
+
7
+ require 'test/unit'
8
+ require 'clusterer'
9
+
10
+ class TestAlgorithms < Test::Unit::TestCase
11
+ include Clusterer
12
+
13
+ def setup
14
+ @idf = InverseDocumentFrequency.new()
15
+ @d = Document.new("hello world, mea culpa, goodbye world.", :idf => @idf).normalize!(@idf)
16
+ @e = Document.new("the world is not a bad place to live.", :idf => @idf).normalize!(@idf)
17
+ @f = Document.new("the world is a crazy place to live.", :idf => @idf).normalize!(@idf)
18
+ @g = Document.new("unique document.")
19
+ end
20
+
21
+ def test_kmeans
22
+ 3.times do
23
+ assert_equal 2, Algorithms.kmeans([@d, @e, @f, @g], 2).size
24
+ assert_equal 2, Algorithms.kmeans([@d, @e, @f, @g], 2, :maximum_iterations => 5).size
25
+ assert_equal 2, Algorithms.kmeans([@d, @e, @f, @g], 2, :maximum_iterations => 5,
26
+ :seeds => [Cluster.new([@d]), Cluster.new([@d])]).size
27
+ assert_equal 3, Algorithms.kmeans([@d, @e, @f, @g],3).size
28
+ end
29
+ end
30
+
31
+ def test_hierarchical_clustering
32
+ assert_equal 2, Algorithms.hierarchical([@d, @e, @f, @g], 2, :similarity_function => :intra_cluster_similarity).size
33
+ assert_equal 1, Algorithms.hierarchical([@d, @e, @f, @g], 1, :similarity_function => :centroid_similarity).size
34
+ assert_equal 2, Algorithms.hierarchical([@d, @e, @f, @g], 2, :similarity_function => :upgma).size
35
+ assert_equal 2, Algorithms.hierarchical([@d, @e, @f, @g], 2, :refined => true).size
36
+ assert_equal 3, Algorithms.hierarchical([@d, @e, @f, @g], 3, :similarity_function => :centroid_similarity,
37
+ :refined => true).size
38
+ end
39
+
40
+ def test_bisecting_kmeans
41
+ assert_equal 2, Algorithms.bisecting_kmeans([@d, @e, @f, @g], 2, :maximum_iterations => 5).size
42
+ assert_equal 1, Algorithms.bisecting_kmeans([@d, @e, @f, @g], 1).size
43
+ assert_equal 2, Algorithms.bisecting_kmeans([@d, @e, @f, @g], 2).size
44
+ assert_equal 2, Algorithms.bisecting_kmeans([@d, @e, @f, @g], 2, :maximum_iterations => 5, :refined => true).size
45
+ assert_equal 3, Algorithms.bisecting_kmeans([@d, @e, @f, @g], 3, :refined => true).size
46
+ end
47
+
48
+ end
@@ -0,0 +1,68 @@
1
+ #The MIT License
2
+
3
+ ###Copyright (c) 2006 Surendra K Singhi <ssinghi AT kreeti DOT com>
4
+
5
+ $:.unshift File.join(File.dirname(__FILE__), "..", "lib")
6
+
7
+ require 'test/unit'
8
+ require 'clusterer'
9
+
10
+ class TestBayes < Test::Unit::TestCase
11
+ include Clusterer
12
+
13
+ def setup
14
+ @idf = InverseDocumentFrequency.new()
15
+ @d = Document.new("hello world, mea culpa, goodbye world.",:idf => @idf).normalize!(@idf)
16
+ @e = Document.new("the world is not a bad place to live.",:idf => @idf).normalize!(@idf)
17
+ @f = Document.new("the world is a crazy place to live.",:idf => @idf).normalize!(@idf)
18
+ @g = Document.new("unique document.")
19
+ end
20
+
21
+ def test_multinomial
22
+ b = MultinomialBayes.new(["good", "evil"])
23
+ b.train(@d, "good")
24
+ b.train(@e, :good)
25
+ b.train_evil @g
26
+ assert_raise(ArgumentError) { b.train(@e, :funny) }
27
+ assert_equal :good, b.classify(@f)
28
+ assert !b.distribution(@f).empty?
29
+ end
30
+
31
+ def test_complement
32
+ b = ComplementBayes.new(["good", "evil"])
33
+ b.train(@d, "good")
34
+ b.train(@e, :good)
35
+ b.train_evil @g
36
+ assert_raise(ArgumentError) { b.train(@e, :funny) }
37
+ assert_equal :good, b.classify(@f)
38
+ assert !b.distribution(@f).empty?
39
+ end
40
+
41
+ def test_weight_normalized_complement
42
+ b = WeightNormalizedComplementBayes.new(["good", "evil"])
43
+ b.train(@d, "good")
44
+ b.train(@e, :good)
45
+ b.train(@g, "evil")
46
+ assert_raise(ArgumentError) { b.train(@e, :funny) }
47
+ assert_equal :good, b.classify(@f)
48
+ assert !b.distribution(@f).empty?
49
+ b.train(@f, "good")
50
+ assert b.instance_variable_get("@weighted_likelihood").empty?
51
+ assert_equal :good, b.classify(@f)
52
+ assert !b.instance_variable_get("@weighted_likelihood").empty?
53
+ end
54
+
55
+ def test_weight_normalized_multinomial
56
+ b = WeightNormalizedMultinomialBayes.new(["good", "evil"])
57
+ b.train(@d, "good")
58
+ b.train(@e, :good)
59
+ b.train(@g, "evil")
60
+ assert_raise(ArgumentError) { b.train(@e, :funny) }
61
+ assert_equal :good, b.classify(@f)
62
+ assert !b.distribution(@f).empty?
63
+ b.train(@f, "good")
64
+ assert b.instance_variable_get("@weighted_likelihood").empty?
65
+ assert_equal :good, b.classify(@f)
66
+ assert !b.instance_variable_get("@weighted_likelihood").empty?
67
+ end
68
+ end