Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Initial commit

  • Loading branch information...
commit 9c91b1d9518daead8fefbfb081d2c1ddd89b0ad7 0 parents
@rjlee rjlee authored
16 Gemfile
@@ -0,0 +1,16 @@
+source "http://rubygems.org"
+# Add dependencies required to use your gem here.
+# Example:
+# gem "activesupport", ">= 2.3.5"
+
+gem 'libsvm-ruby-swig'
+gem 'fast-stemmer'
+
+# Add dependencies to develop your gem here.
+# Include everything needed to run rake, tests, features, etc.
+group :development do
+ gem "shoulda", ">= 0"
+ gem "bundler", "~> 1.0.0"
+ gem "jeweler", "~> 1.5.2"
+ gem "rcov", ">= 0"
+end
24 Gemfile.lock
@@ -0,0 +1,24 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ fast-stemmer (1.0.0)
+ git (1.2.5)
+ jeweler (1.5.2)
+ bundler (~> 1.0.0)
+ git (>= 1.2.5)
+ rake
+ libsvm-ruby-swig (0.4.0)
+ rake (0.8.7)
+ rcov (0.9.9)
+ shoulda (2.11.3)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ bundler (~> 1.0.0)
+ fast-stemmer
+ jeweler (~> 1.5.2)
+ libsvm-ruby-swig
+ rcov
+ shoulda
20 LICENSE.txt
@@ -0,0 +1,20 @@
+Copyright (c) 2010 robl
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
48 README.markdown
@@ -0,0 +1,48 @@
+# hoatzin
+
+Hoatzin is a text classifier in Ruby that uses SVM for it's classification.
+
+## Installation
+
+gem install hoatzin
+
+## Usage
+
+ # Create a hoatzin classifier
+ c = Hoatzin::Classifier.new()
+
+ # Train the classifier with a classification and some text
+ c.train(:positive, "Thats nice")
+
+ # This will return the most likely classification (:positive)
+ c.classify("Thats nice")
+
+## Storage
+
+The Hoatzin classifier supports saving your trained classifier to the filesystem. It needs
+to store the libsvm model and the associated metadata as two separate files.
+
+ # Load a previously trained classifier
+ c = Hoatzin::Classifier.new(:metadata => '/path/to/file', :model => '/path/to/file')
+
+ # Save an existing trained classifier, without training data
+ # The #train method will raise an exception if called when the classifier is reloaded
+ c.save(:metadata => '/path/to/file', :model => '/path/to/file')
+
+ # Save an existing trained classifier, with training data
+ # The #train method can continue to be called when the classifier is reloaded
+ c.save(:metadata => '/path/to/file', :model => '/path/to/file', :update => true)
+
+The classifier can continue to be trained if the model is saved with the :update => true option,
+however the files stored on the filesystem will be much larger as they will contain copies
+of all the documents used during training the classifier. It is generally advised to save without
+the :update => true option unless it is definitely required.
+
+## Acknowledgements
+
+See http://www.igvita.com/2008/01/07/support-vector-machines-svm-in-ruby/ for the original inspiration.
+
+## Copyright and License
+
+GPL v3 - See LICENSE.txt for details.
+Copyright (c) 2010, Rob Lee
53 Rakefile
@@ -0,0 +1,53 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'rake'
+
+require 'jeweler'
+Jeweler::Tasks.new do |gem|
+ # gem is a Gem::Specification... see http://docs.rubygems.org/read/chapter/20 for more options
+ gem.name = "hoatzin"
+ gem.homepage = "http://github.com/rjlee/hoatzin"
+ gem.license = "MIT"
+ gem.summary = %Q{TODO: one-line summary of your gem}
+ gem.description = %Q{TODO: longer description of your gem}
+ gem.email = "robl@monkeyhelper.com"
+ gem.authors = ["robl"]
+ # Include your dependencies below. Runtime dependencies are required when using your gem,
+ # and development dependencies are only needed for development (ie running rake tasks, tests, etc)
+ # gem.add_runtime_dependency 'jabber4r', '> 0.1'
+ # gem.add_development_dependency 'rspec', '> 1.2.3'
+end
+Jeweler::RubygemsDotOrgTasks.new
+
+require 'rake/testtask'
+Rake::TestTask.new(:test) do |test|
+ test.libs << 'lib' << 'test'
+ test.pattern = 'test/**/test_*.rb'
+ test.verbose = true
+end
+
+require 'rcov/rcovtask'
+Rcov::RcovTask.new do |test|
+ test.libs << 'test'
+ test.pattern = 'test/**/test_*.rb'
+ test.verbose = true
+end
+
+task :default => :test
+
+require 'rake/rdoctask'
+Rake::RDocTask.new do |rdoc|
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
+
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = "hoatzin #{version}"
+ rdoc.rdoc_files.include('README*')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
189 lib/hoatzin.rb
@@ -0,0 +1,189 @@
+require 'svm'
+require 'fast_stemmer'
+require 'iconv'
+
+module Hoatzin
+ class Classifier
+
+ class ReadOnly < Exception; end
+
+ attr_reader :classifications
+
+ def initialize options = {}
+
+ @metadata_file = options.delete(:metadata) || nil
+ @model_file = options.delete(:model) || nil
+ @documents = []
+ @dictionary = []
+ @classifications = []
+ @labels = []
+ @feature_vectors = []
+ @problem = @model = nil
+ @cache = 0
+ @readonly = false
+
+ # If we have model and metadata files then load them
+ load if @metadata_file && @model_file
+
+ # Define kernel parameters for libsvm
+ @parameters = Parameter.new(:C => 100,
+ :degree => 1,
+ :coef0 => 0,
+ :eps => 0.001)
+
+ end
+
+ def train classification, text
+ # Only allow retraining if we have all the required data
+ raise ReadOnly if @readonly
+
+ # Add the classification if we haven't seen it before
+ @classifications << classification unless @classifications.include?(classification)
+
+ # Tokenize the text
+ tokens = Classifier.tokenize(text)
+
+ # Add tokens to word list
+ @dictionary << tokens
+ @dictionary.flatten!.uniq!
+
+ # Add to list of documents
+ @documents << tokens
+
+ # Add classification to classification list
+ @labels << @classifications.index(classification)
+
+ # Compute the feature vectors
+ @feature_vectors = @documents.map { |doc| @dictionary.map{|x| doc.include?(x) ? 1 : 0} }
+ end
+
+ def classify text
+ # Only update the model if we've trained more documents since it was last updated
+ if !@readonly && @documents.length > @cache
+ return nil if @documents.length == 0
+ @cache = @documents.length
+ assign_model
+ end
+
+ # Tokenize the text
+ tokens = Classifier.tokenize(text)
+
+ # Calculate the feature vectors for the text to be classified
+ f_vector = @dictionary.map{|x| tokens.include?(x) ? 1 : 0}
+
+ # Classify and return classification
+ pred, probs = @model.predict_probability(f_vector)
+ @classifications[pred.to_i]
+ end
+
+ def save options = {}
+ @metadata_file = options[:metadata] if options.key?(:metadata)
+ @model_file = options[:model] if options.key?(:model)
+ return false unless (@metadata_file && @model_file)
+ data = { :dictionary => @dictionary, :classifications => @classifications}
+ data.merge!(:documents => @documents,
+ :labels => @labels,
+ :feature_vectors => @feature_vectors,
+ :cache => @cache) if options[:update]
+ File.open(@metadata_file, 'w+') { |f| Marshal.dump(data, f) }
+ assign_model if @model.nil?
+ @model.save(@model_file)
+ end
+
+ protected
+ def load
+ data = {}
+ File.open(@metadata_file) { |f| data = Marshal.load(f) }
+ @dictionary = data[:dictionary]
+ @classifications = data[:classifications]
+ if data.key?(:documents)
+ @documents = data[:documents]
+ @labels = data[:labels]
+ @feature_vectors = data[:feature_vectors]
+ @cache = data[:cache]
+ end
+ @readonly = @documents.length > 0 ? false : true
+ @model = Model.new(@model_file)
+ end
+
+ def assign_model
+ @problem = Problem.new(@labels, @feature_vectors)
+ @model = Model.new(@problem, @parameters)
+ end
+
+ # Adapted from ankusa, to replace with tokenizer gem
+ def self.tokenize text
+ tokens = []
+ # from http://www.jroller.com/obie/tags/unicode
+ converter = Iconv.new('ASCII//IGNORE//TRANSLIT', 'UTF-8')
+ converter.iconv(text).unpack('U*').select { |cp| cp < 127 }.pack('U*') rescue ""
+ text.tr('-', ' ').gsub(/[^\w\s]/," ").split.each do |token|
+ tokens << token if (token.length > 3 && !Classifier.stop_words.include?(token))
+ end
+ tokens
+ end
+
+ # ftp://ftp.cs.cornell.edu/pub/smart/english.stop
+ def self.stop_words
+ %w{
+ a a's able about above according accordingly across actually after
+ afterwards again against ain't all allow allows almost alone along
+ already also although always am among amongst an and another any
+ anybody anyhow anyone anything anyway anyways anywhere apart appear
+ appreciate appropriate are aren't around as aside ask asking
+ associated at available away awfully b be became because become
+ becomes becoming been before beforehand behind being believe below
+ beside besides best better between beyond both brief but by c
+ c'mon c's came can can't cannot cant cause causes certain certainly
+ changes clearly co com come comes concerning consequently consider
+ considering contain containing contains corresponding could couldn't
+ course currently d definitely described despite did didn't different
+ do does doesn't doing don't done down downwards during e each edu
+ eg eight either else elsewhere enough entirely especially et etc
+ even ever every everybody everyone everything everywhere ex exactly
+ example except f far few fifth first five followed following follows
+ for former formerly forth four from further furthermore g get gets
+ getting given gives go goes going gone got gotten greetings h had
+ hadn't happens hardly has hasn't have haven't having he he's hello
+ help hence her here here's hereafter hereby herein hereupon hers
+ herself hi him himself his hither hopefully how howbeit however i
+ i'd i'll i'm i've ie if ignored immediate in inasmuch inc indeed
+ indicate indicated indicates inner insofar instead into inward is
+ isn't it it'd it'll it's its itself j just k keep keeps kept know
+ knows known l last lately later latter latterly least less lest let
+ let's like liked likely little look looking looks ltd m mainly many
+ may maybe me mean meanwhile merely might more moreover most mostly
+ much must my myself n name namely nd near nearly necessary need needs
+ neither never nevertheless new next nine no nobody non none noone
+ nor normally not nothing novel now nowhere o obviously of off often
+ oh ok okay old on once one ones only onto or other others otherwise
+ ought our ours ourselves out outside over overall own p particular
+ particularly per perhaps placed please plus possible presumably
+ probably provides q que quite qv r rather rd re really reasonably
+ regarding regardless regards relatively respectively right s said
+ same saw say saying says second secondly see seeing seem seemed
+ seeming seems seen self selves sensible sent serious seriously
+ seven several shall she should shouldn't since six so some somebody
+ somehow someone something sometime sometimes somewhat somewhere soon
+ sorry specified specify specifying still sub such sup sure t t's
+ take taken tell tends th than thank thanks thanx that that's thats
+ the their theirs them themselves then thence there there's thereafter
+ thereby therefore therein theres thereupon these they they'd they'll
+ they're they've think third this thorough thoroughly those though
+ three through throughout thru thus to together too took toward
+ towards tried tries truly try trying twice two u un under
+ unfortunately unless unlikely until unto up upon us use used useful
+ uses using usually uucp v value various very via viz vs w want wants
+ was wasn't way we we'd we'll we're we've welcome well went were weren't
+ what what's whatever when whence whenever where where's whereafter
+ whereas whereby wherein whereupon wherever whether which while
+ whither who who's whoever whole whom whose why will willing wish
+ with within without won't wonder would would wouldn't x y yes yet
+ you you'd you'll you're you've your yours yourself yourselves
+ z zero
+ }
+ end
+
+
+ end
+end
43 test/helper.rb
@@ -0,0 +1,43 @@
+require 'rubygems'
+require 'bundler'
+begin
+ Bundler.setup(:default, :development)
+rescue Bundler::BundlerError => e
+ $stderr.puts e.message
+ $stderr.puts "Run `bundle install` to install missing gems"
+ exit e.status_code
+end
+require 'test/unit'
+require 'shoulda'
+
+$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
+$LOAD_PATH.unshift(File.dirname(__FILE__))
+require 'hoatzin'
+
+class Test::Unit::TestCase
+
+ TRAINING_LABELS = [1, 1, 0, 1, 1, 0, 0]
+ TRAINING_DOCS = [
+ 'FREE NATIONAL TREASURE',
+ 'FREE TV for EVERY visitor',
+ 'Peter and Stewie are hilarious',
+ 'AS SEEN ON NATIONAL TV',
+ 'FREE drugs',
+ 'New episode rocks, Peter and Stewie are hilarious',
+ 'Peter is my fav!'
+ # ...
+ ]
+
+ TESTING_LABELS = [1, 0, 0]
+ TESTING_DOCS = [
+ 'FREE lotterry for the NATIONAL TREASURE !!!',
+ 'Stewie is hilarious',
+ 'Poor Peter ... hilarious',
+ # ...
+ ]
+
+ READONLY_METADATA_FILE = File.join(File.dirname(__FILE__), 'models', 'readonly-test', 'model')
+ READONLY_MODEL_FILE = File.join(File.dirname(__FILE__), 'models', 'readonly-test', 'metadata')
+ METADATA_FILE = File.join(File.dirname(__FILE__), 'models', 'test', 'model')
+ MODEL_FILE = File.join(File.dirname(__FILE__), 'models', 'test', 'metadata')
+end
16 test/models/readonly-test/metadata
@@ -0,0 +1,16 @@
+svm_type c_svc
+kernel_type rbf
+gamma 0.0454545
+nr_class 2
+total_sv 7
+rho -0.00785397
+label 0 1
+nr_sv 4 3
+SV
+1.178526450216892 0:1 1:1 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+0.8670862694825178 0:1 1:0 2:0 3:1 4:1 5:1 6:1 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+1.565208229773764 0:0 1:1 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1 13:1 14:1 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+3.06895439364994 0:1 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:1 16:0 17:0 18:0 19:0 20:0 21:0
+-2.445428417806817 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:1 9:1 10:1 11:1 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+-0.5364005807527658 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:1 9:1 10:1 11:1 12:0 13:0 14:0 15:0 16:1 17:1 18:1 19:0 20:0 21:0
+-3.697946344563531 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:1 20:1 21:1
BIN  test/models/readonly-test/model
Binary file not shown
16 test/models/test/metadata
@@ -0,0 +1,16 @@
+svm_type c_svc
+kernel_type rbf
+gamma 0.0454545
+nr_class 2
+total_sv 7
+rho -0.00785397
+label 0 1
+nr_sv 4 3
+SV
+1.178526450216892 0:1 1:1 2:1 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+0.8670862694825178 0:1 1:0 2:0 3:1 4:1 5:1 6:1 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+1.565208229773764 0:0 1:1 2:0 3:1 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:1 13:1 14:1 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+3.06895439364994 0:1 1:0 2:0 3:0 4:0 5:0 6:0 7:0 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:1 16:0 17:0 18:0 19:0 20:0 21:0
+-2.445428417806817 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:1 9:1 10:1 11:1 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:0 20:0 21:0
+-0.5364005807527658 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:1 9:1 10:1 11:1 12:0 13:0 14:0 15:0 16:1 17:1 18:1 19:0 20:0 21:0
+-3.697946344563531 0:0 1:0 2:0 3:0 4:0 5:0 6:0 7:1 8:0 9:0 10:0 11:0 12:0 13:0 14:0 15:0 16:0 17:0 18:0 19:1 20:1 21:1
BIN  test/models/test/model
Binary file not shown
74 test/test_hoatzin.rb
@@ -0,0 +1,74 @@
+require 'helper'
+
+class TestHoatzin < Test::Unit::TestCase
+
+ context "An untrained Hoatzin classifier" do
+
+ setup do
+ @c = Hoatzin::Classifier.new()
+ end
+
+ should "support training and classification" do
+ assert_equal @c.train(:positive, "Thats nice"), [[1, 1]]
+ assert_equal @c.classify("Thats nice"), :positive
+ end
+
+ context "that has been trained" do
+
+ setup do
+ TRAINING_LABELS.each_with_index do |label, index|
+ @c.train(label, TRAINING_DOCS[index])
+ end
+ end
+
+ should "classify the test set correctly" do
+ #@c.save(:metadata => METADATA_FILE, :model => MODEL_FILE, :update => true)
+ TESTING_LABELS.each_with_index do |label, index|
+ assert_equal @c.classify(TESTING_DOCS[index]), label
+ end
+ end
+
+ should "return the classifications" do
+ assert_equal @c.classifications, [1,0]
+ end
+ end
+
+ end
+
+ context "An untrained Hoatzin classifier with an un-updatable model" do
+
+ setup do
+ @c = Hoatzin::Classifier.new(:metadata => READONLY_METADATA_FILE, :model => READONLY_MODEL_FILE )
+ end
+
+ should "classify the test set correctly" do
+ TESTING_LABELS.each_with_index do |label, index|
+ assert_equal @c.classify(TESTING_DOCS[index]), label
+ end
+ end
+
+ should "not allow further training" do
+ #@c.train(:positive, "Thats nice")
+ assert_raises(Hoatzin::Classifier::ReadOnly) { @c.train(:positive, "Thats nice") }
+ end
+
+ end
+
+ context "An untrained Hoatzin classifier with an updatable model" do
+
+ setup do
+ @c = Hoatzin::Classifier.new(:metadata => METADATA_FILE, :model => MODEL_FILE )
+ end
+
+ should "classify the test set correctly" do
+ TESTING_LABELS.each_with_index do |label, index|
+ assert_equal @c.classify(TESTING_DOCS[index]), label
+ end
+ end
+
+ should "allow further training" do
+ assert_nothing_raised {@c.train :positive, "Thats nice" }
+ end
+
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.