classifier-1.3.3/0000775000175000017500000000000011752523257013511 5ustar uwabamiuwabamiclassifier-1.3.3/metadata.yml0000664000175000017500000000355411752523257016023 0ustar uwabamiuwabami--- !ruby/object:Gem::Specification name: classifier version: !ruby/object:Gem::Version version: 1.3.3 platform: ruby authors: - Lucas Carlson autorequire: classifier bindir: bin cert_chain: [] date: 2010-07-06 00:00:00 -07:00 default_executable: dependencies: - !ruby/object:Gem::Dependency name: fast-stemmer type: :runtime version_requirement: version_requirements: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: 1.0.0 version: description: " A general classifier module to allow Bayesian and other types of classifications.\n" email: lucas@rufy.com executables: [] extensions: [] extra_rdoc_files: [] files: - lib/classifier/bayes.rb - lib/classifier/extensions/string.rb - lib/classifier/extensions/vector.rb - lib/classifier/extensions/vector_serialize.rb - lib/classifier/extensions/word_hash.rb - lib/classifier/lsi/content_node.rb - lib/classifier/lsi/summary.rb - lib/classifier/lsi/word_list.rb - lib/classifier/lsi.rb - lib/classifier.rb - bin/bayes.rb - bin/summarize.rb - test/bayes/bayesian_test.rb - test/extensions/word_hash_test.rb - test/lsi/lsi_test.rb - test/test_helper.rb - LICENSE - Rakefile - README has_rdoc: true homepage: http://classifier.rufy.com/ licenses: [] post_install_message: rdoc_options: [] require_paths: - lib required_ruby_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: "0" version: required_rubygems_version: !ruby/object:Gem::Requirement requirements: - - ">=" - !ruby/object:Gem::Version version: "0" version: requirements: - A porter-stemmer module to split word stems. rubyforge_project: rubygems_version: 1.3.5 signing_key: specification_version: 3 summary: A general classifier module to allow Bayesian and other types of classifications. test_files: [] classifier-1.3.3/README0000644000175000017500000000672711752523257014403 0ustar uwabamiuwabami== Welcome to Classifier Classifier is a general module to allow Bayesian and other types of classifications. == Download * http://rubyforge.org/projects/classifier * gem install classifier * svn co http://rufy.com/svn/classifier/trunk == Dependencies If you install Classifier from source, you'll need to install Martin Porter's stemmer algorithm with RubyGems as follows: gem install stemmer If you would like to speed up LSI classification by at least 10x, please install the following libraries: GNU GSL:: http://www.gnu.org/software/gsl rb-gsl:: http://rb-gsl.rubyforge.org Notice that LSI will work without these libraries, but as soon as they are installed, Classifier will make use of them. No configuration changes are needed, we like to keep things ridiculously easy for you. == Bayes A Bayesian classifier by Lucas Carlson. Bayesian Classifiers are accurate, fast, and have modest memory requirements. === Usage require 'classifier' b = Classifier::Bayes.new 'Interesting', 'Uninteresting' b.train_interesting "here are some good words. I hope you love them" b.train_uninteresting "here are some bad words, I hate you" b.classify "I hate bad words and you" # returns 'Uninteresting' require 'madeleine' m = SnapshotMadeleine.new("bayes_data") { Classifier::Bayes.new 'Interesting', 'Uninteresting' } m.system.train_interesting "here are some good words. I hope you love them" m.system.train_uninteresting "here are some bad words, I hate you" m.take_snapshot m.system.classify "I love you" # returns 'Interesting' Using Madeleine, your application can persist the learned data over time. === Bayesian Classification * http://www.process.com/precisemail/bayesian_filtering.htm * http://en.wikipedia.org/wiki/Bayesian_filtering * http://www.paulgraham.com/spam.html == LSI A Latent Semantic Indexer by David Fayram. Latent Semantic Indexing engines are not as fast or as small as Bayesian classifiers, but are more flexible, providing fast search and clustering detection as well as semantic analysis of the text that theoretically simulates human learning. === Usage require 'classifier' lsi = Classifier::LSI.new strings = [ ["This text deals with dogs. Dogs.", :dog], ["This text involves dogs too. Dogs! ", :dog], ["This text revolves around cats. Cats.", :cat], ["This text also involves cats. Cats!", :cat], ["This text involves birds. Birds.",:bird ]] strings.each {|x| lsi.add_item x.first, x.last} lsi.search("dog", 3) # returns => ["This text deals with dogs. Dogs.", "This text involves dogs too. Dogs! ", # "This text also involves cats. Cats!"] lsi.find_related(strings[2], 2) # returns => ["This text revolves around cats. Cats.", "This text also involves cats. Cats!"] lsi.classify "This text is also about dogs!" # returns => :dog Please see the Classifier::LSI documentation for more information. It is possible to index, search and classify with more than just simple strings. === Latent Semantic Indexing * http://www.c2.com/cgi/wiki?LatentSemanticIndexing * http://www.chadfowler.com/index.cgi/Computing/LatentSemanticIndexing.rdoc * http://en.wikipedia.org/wiki/Latent_semantic_analysis == Authors * Lucas Carlson (mailto:lucas@rufy.com) * David Fayram II (mailto:dfayram@gmail.com) * Cameron McBride (mailto:cameron.mcbride@gmail.com) This library is released under the terms of the GNU LGPL. See LICENSE for more details. classifier-1.3.3/Rakefile0000644000175000017500000000441711752523257015162 0ustar uwabamiuwabamirequire 'rubygems' require 'rake' require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' require 'rake/contrib/rubyforgepublisher' PKG_VERSION = "1.3.3" PKG_FILES = FileList[ "lib/**/*", "bin/*", "test/**/*", "[A-Z]*", "Rakefile", "html/**/*" ] desc "Default Task" task :default => [ :test ] # Run the unit tests desc "Run all unit tests" Rake::TestTask.new("test") { |t| t.libs << "lib" t.pattern = 'test/*/*_test.rb' t.verbose = true } # Make a console, useful when working on tests desc "Generate a test console" task :console do verbose( false ) { sh "irb -I lib/ -r 'classifier'" } end # Genereate the RDoc documentation desc "Create documentation" Rake::RDocTask.new("doc") { |rdoc| rdoc.title = "Ruby Classifier - Bayesian and LSI classification library" rdoc.rdoc_dir = 'html' rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/**/*.rb') } # Genereate the package spec = Gem::Specification.new do |s| #### Basic information. s.name = 'classifier' s.version = PKG_VERSION s.summary = <<-EOF A general classifier module to allow Bayesian and other types of classifications. EOF s.description = <<-EOF A general classifier module to allow Bayesian and other types of classifications. EOF #### Which files are to be included in this gem? Everything! (Except CVS directories.) s.files = PKG_FILES #### Load-time details: library and application (you will need one or both). s.require_path = 'lib' s.autorequire = 'classifier' #### Documentation and testing. s.has_rdoc = true #### Dependencies and requirements. s.add_dependency('fast-stemmer', '>= 1.0.0') s.requirements << "A porter-stemmer module to split word stems." #### Author and project details. s.author = "Lucas Carlson" s.email = "lucas@rufy.com" s.homepage = "http://classifier.rufy.com/" end Rake::GemPackageTask.new(spec) do |pkg| pkg.need_zip = true pkg.need_tar = true end desc "Report code statistics (KLOCs, etc) from the application" task :stats do require 'code_statistics' CodeStatistics.new( ["Library", "lib"], ["Units", "test"] ).to_s end desc "Publish new documentation" task :publish do `ssh rufy update-classifier-doc` Rake::RubyForgePublisher.new('classifier', 'cardmagic').upload end classifier-1.3.3/LICENSE0000644000175000017500000005445211752523257014526 0ustar uwabamiuwabami GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted byclassifier-1.3.3/test/0000775000175000017500000000000011752523257014470 5ustar uwabamiuwabamiclassifier-1.3.3/test/test_helper.rb0000644000175000017500000000013011752523257017323 0ustar uwabamiuwabami$:.unshift(File.dirname(__FILE__) + '/../lib') require 'test/unit' require 'classifier'classifier-1.3.3/test/lsi/0000775000175000017500000000000011752523257015257 5ustar uwabamiuwabamiclassifier-1.3.3/test/lsi/lsi_test.rb0000644000175000017500000001005011752523257017424 0ustar uwabamiuwabamirequire File.dirname(__FILE__) + '/../test_helper' class LSITest < Test::Unit::TestCase def setup # we repeat principle words to help weight them. # This test is rather delicate, since this system is mostly noise. @str1 = "This text deals with dogs. Dogs." @str2 = "This text involves dogs too. Dogs! " @str3 = "This text revolves around cats. Cats." @str4 = "This text also involves cats. Cats!" @str5 = "This text involves birds. Birds." end def test_basic_indexing lsi = Classifier::LSI.new [@str1, @str2, @str3, @str4, @str5].each { |x| lsi << x } assert ! lsi.needs_rebuild? # note that the closest match to str1 is str2, even though it is not # the closest text match. assert_equal [@str2, @str5, @str3], lsi.find_related(@str1, 3) end def test_not_auto_rebuild lsi = Classifier::LSI.new :auto_rebuild => false lsi.add_item @str1, "Dog" lsi.add_item @str2, "Dog" assert lsi.needs_rebuild? lsi.build_index assert ! lsi.needs_rebuild? end def test_basic_categorizing lsi = Classifier::LSI.new lsi.add_item @str2, "Dog" lsi.add_item @str3, "Cat" lsi.add_item @str4, "Cat" lsi.add_item @str5, "Bird" assert_equal "Dog", lsi.classify( @str1 ) assert_equal "Cat", lsi.classify( @str3 ) assert_equal "Bird", lsi.classify( @str5 ) end def test_external_classifying lsi = Classifier::LSI.new bayes = Classifier::Bayes.new 'Dog', 'Cat', 'Bird' lsi.add_item @str1, "Dog" ; bayes.train_dog @str1 lsi.add_item @str2, "Dog" ; bayes.train_dog @str2 lsi.add_item @str3, "Cat" ; bayes.train_cat @str3 lsi.add_item @str4, "Cat" ; bayes.train_cat @str4 lsi.add_item @str5, "Bird" ; bayes.train_bird @str5 # We're talking about dogs. Even though the text matches the corpus on # cats better. Dogs have more semantic weight than cats. So bayes # will fail here, but the LSI recognizes content. tricky_case = "This text revolves around dogs." assert_equal "Dog", lsi.classify( tricky_case ) assert_not_equal "Dog", bayes.classify( tricky_case ) end def test_recategorize_interface lsi = Classifier::LSI.new lsi.add_item @str1, "Dog" lsi.add_item @str2, "Dog" lsi.add_item @str3, "Cat" lsi.add_item @str4, "Cat" lsi.add_item @str5, "Bird" tricky_case = "This text revolves around dogs." assert_equal "Dog", lsi.classify( tricky_case ) # Recategorize as needed. lsi.categories_for(@str1).clear.push "Cow" lsi.categories_for(@str2).clear.push "Cow" assert !lsi.needs_rebuild? assert_equal "Cow", lsi.classify( tricky_case ) end def test_search lsi = Classifier::LSI.new [@str1, @str2, @str3, @str4, @str5].each { |x| lsi << x } # Searching by content and text, note that @str2 comes up first, because # both "dog" and "involve" are present. But, the next match is @str1 instead # of @str4, because "dog" carries more weight than involves. assert_equal( [@str2, @str1, @str4, @str5, @str3], lsi.search("dog involves", 100) ) # Keyword search shows how the space is mapped out in relation to # dog when magnitude is remove. Note the relations. We move from dog # through involve and then finally to other words. assert_equal( [@str1, @str2, @str4, @str5, @str3], lsi.search("dog", 5) ) end def test_serialize_safe lsi = Classifier::LSI.new [@str1, @str2, @str3, @str4, @str5].each { |x| lsi << x } lsi_md = Marshal.dump lsi lsi_m = Marshal.load lsi_md assert_equal lsi_m.search("cat", 3), lsi.search("cat", 3) assert_equal lsi_m.find_related(@str1, 3), lsi.find_related(@str1, 3) end def test_keyword_search lsi = Classifier::LSI.new lsi.add_item @str1, "Dog" lsi.add_item @str2, "Dog" lsi.add_item @str3, "Cat" lsi.add_item @str4, "Cat" lsi.add_item @str5, "Bird" assert_equal [:dog, :text, :deal], lsi.highest_ranked_stems(@str1) end def test_summary assert_equal "This text involves dogs too [...] This text also involves cats", [@str1, @str2, @str3, @str4, @str5].join.summary(2) end endclassifier-1.3.3/test/extensions/0000775000175000017500000000000011752523257016667 5ustar uwabamiuwabamiclassifier-1.3.3/test/extensions/word_hash_test.rb0000644000175000017500000000101711752523257022226 0ustar uwabamiuwabamirequire File.dirname(__FILE__) + '/../test_helper' class StringExtensionsTest < Test::Unit::TestCase def test_word_hash hash = {:good=>1, :"!"=>1, :hope=>1, :"'"=>1, :"."=>1, :love=>1, :word=>1, :them=>1, :test=>1} assert_equal hash, "here are some good words of test's. I hope you love them!".word_hash end def test_clean_word_hash hash = {:good=>1, :word=>1, :hope=>1, :love=>1, :them=>1, :test=>1} assert_equal hash, "here are some good words of test's. I hope you love them!".clean_word_hash end end classifier-1.3.3/test/bayes/0000775000175000017500000000000011752523257015573 5ustar uwabamiuwabamiclassifier-1.3.3/test/bayes/bayesian_test.rb0000644000175000017500000000176211752523257020756 0ustar uwabamiuwabamirequire File.dirname(__FILE__) + '/../test_helper' class BayesianTest < Test::Unit::TestCase def setup @classifier = Classifier::Bayes.new 'Interesting', 'Uninteresting' end def test_good_training assert_nothing_raised { @classifier.train_interesting "love" } end def test_bad_training assert_raise(StandardError) { @classifier.train_no_category "words" } end def test_bad_method assert_raise(NoMethodError) { @classifier.forget_everything_you_know "" } end def test_categories assert_equal ['Interesting', 'Uninteresting'].sort, @classifier.categories.sort end def test_add_category @classifier.add_category 'Test' assert_equal ['Test', 'Interesting', 'Uninteresting'].sort, @classifier.categories.sort end def test_classification @classifier.train_interesting "here are some good words. I hope you love them" @classifier.train_uninteresting "here are some bad words, I hate you" assert_equal 'Uninteresting', @classifier.classify("I hate bad words and you") end endclassifier-1.3.3/bin/0000775000175000017500000000000011752523257014261 5ustar uwabamiuwabamiclassifier-1.3.3/bin/summarize.rb0000755000175000017500000000042611752523257016625 0ustar uwabamiuwabami#!/usr/bin/env ruby begin require 'rubygems' require 'classifier' rescue require 'classifier' end require 'open-uri' num = ARGV[1].to_i num = num < 1 ? 10 : num text = open(ARGV.first).read puts text.gsub(/<[^>]+>/,"").gsub(/[\s]+/," ").summary(num) classifier-1.3.3/bin/bayes.rb0000755000175000017500000000146211752523257015715 0ustar uwabamiuwabami#!/usr/bin/env ruby begin require 'rubygems' require 'classifier' rescue require 'classifier' end require 'madeleine' m = SnapshotMadeleine.new(File.expand_path("~/.bayes_data")) { Classifier::Bayes.new 'Interesting', 'Uninteresting' } case ARGV[0] when "add" case ARGV[1].downcase when "interesting" m.system.train_interesting File.open(ARGV[2]).read puts "#{ARGV[2]} has been classified as interesting" when "uninteresting" m.system.train_uninteresting File.open(ARGV[2]).read puts "#{ARGV[2]} has been classified as uninteresting" else puts "Invalid category: choose between interesting and uninteresting" exit(1) end when "classify" puts m.system.classify(File.open(ARGV[1]).read) else puts "Invalid option: choose add [category] [file] or clasify [file]" exit(-1) end m.take_snapshot classifier-1.3.3/lib/0000775000175000017500000000000011752523257014257 5ustar uwabamiuwabamiclassifier-1.3.3/lib/classifier.rb0000644000175000017500000000246311752523257016733 0ustar uwabamiuwabami#-- # Copyright (c) 2005 Lucas Carlson # # 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. #++ # Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL require 'rubygems' require 'classifier/extensions/string' require 'classifier/bayes' require 'classifier/lsi'classifier-1.3.3/lib/classifier/0000775000175000017500000000000011752523257016403 5ustar uwabamiuwabamiclassifier-1.3.3/lib/classifier/lsi.rb0000644000175000017500000003014311752523257017516 0ustar uwabamiuwabami# Author:: David Fayram (mailto:dfayram@lensmen.net) # Copyright:: Copyright (c) 2005 David Fayram II # License:: LGPL begin raise LoadError if ENV['NATIVE_VECTOR'] == "true" # to test the native vector class, try `rake test NATIVE_VECTOR=true` require 'gsl' # requires http://rb-gsl.rubyforge.org/ require 'classifier/extensions/vector_serialize' $GSL = true rescue LoadError warn "Notice: for 10x faster LSI support, please install http://rb-gsl.rubyforge.org/" require 'classifier/extensions/vector' end require 'classifier/lsi/word_list' require 'classifier/lsi/content_node' require 'classifier/lsi/summary' module Classifier # This class implements a Latent Semantic Indexer, which can search, classify and cluster # data based on underlying semantic relations. For more information on the algorithms used, # please consult Wikipedia[http://en.wikipedia.org/wiki/Latent_Semantic_Indexing]. class LSI attr_reader :word_list attr_accessor :auto_rebuild # Create a fresh index. # If you want to call #build_index manually, use # Classifier::LSI.new :auto_rebuild => false # def initialize(options = {}) @auto_rebuild = true unless options[:auto_rebuild] == false @word_list, @items = WordList.new, {} @version, @built_at_version = 0, -1 end # Returns true if the index needs to be rebuilt. The index needs # to be built after all informaton is added, but before you start # using it for search, classification and cluster detection. def needs_rebuild? (@items.keys.size > 1) && (@version != @built_at_version) end # Adds an item to the index. item is assumed to be a string, but # any item may be indexed so long as it responds to #to_s or if # you provide an optional block explaining how the indexer can # fetch fresh string data. This optional block is passed the item, # so the item may only be a reference to a URL or file name. # # For example: # lsi = Classifier::LSI.new # lsi.add_item "This is just plain text" # lsi.add_item "/home/me/filename.txt" { |x| File.read x } # ar = ActiveRecordObject.find( :all ) # lsi.add_item ar, *ar.categories { |x| ar.content } # def add_item( item, *categories, &block ) clean_word_hash = block ? block.call(item).clean_word_hash : item.to_s.clean_word_hash @items[item] = ContentNode.new(clean_word_hash, *categories) @version += 1 build_index if @auto_rebuild end # A less flexible shorthand for add_item that assumes # you are passing in a string with no categorries. item # will be duck typed via to_s . # def <<( item ) add_item item end # Returns the categories for a given indexed items. You are free to add and remove # items from this as you see fit. It does not invalide an index to change its categories. def categories_for(item) return [] unless @items[item] return @items[item].categories end # Removes an item from the database, if it is indexed. # def remove_item( item ) if @items.keys.contain? item @items.remove item @version += 1 end end # Returns an array of items that are indexed. def items @items.keys end # Returns the categories for a given indexed items. You are free to add and remove # items from this as you see fit. It does not invalide an index to change its categories. def categories_for(item) return [] unless @items[item] return @items[item].categories end # This function rebuilds the index if needs_rebuild? returns true. # For very large document spaces, this indexing operation may take some # time to complete, so it may be wise to place the operation in another # thread. # # As a rule, indexing will be fairly swift on modern machines until # you have well over 500 documents indexed, or have an incredibly diverse # vocabulary for your documents. # # The optional parameter "cutoff" is a tuning parameter. When the index is # built, a certain number of s-values are discarded from the system. The # cutoff parameter tells the indexer how many of these values to keep. # A value of 1 for cutoff means that no semantic analysis will take place, # turning the LSI class into a simple vector search engine. def build_index( cutoff=0.75 ) return unless needs_rebuild? make_word_list doc_list = @items.values tda = doc_list.collect { |node| node.raw_vector_with( @word_list ) } if $GSL tdm = GSL::Matrix.alloc(*tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.size[1].times do |col| vec = GSL::Vector.alloc( ntdm.column(col) ).row doc_list[col].lsi_vector = vec doc_list[col].lsi_norm = vec.normalize end else tdm = Matrix.rows(tda).trans ntdm = build_reduced_matrix(tdm, cutoff) ntdm.row_size.times do |col| doc_list[col].lsi_vector = ntdm.column(col) if doc_list[col] doc_list[col].lsi_norm = ntdm.column(col).normalize if doc_list[col] end end @built_at_version = @version end # This method returns max_chunks entries, ordered by their average semantic rating. # Essentially, the average distance of each entry from all other entries is calculated, # the highest are returned. # # This can be used to build a summary service, or to provide more information about # your dataset's general content. For example, if you were to use categorize on the # results of this data, you could gather information on what your dataset is generally # about. def highest_relative_content( max_chunks=10 ) return [] if needs_rebuild? avg_density = Hash.new @items.each_key { |x| avg_density[x] = proximity_array_for_content(x).inject(0.0) { |x,y| x + y[1]} } avg_density.keys.sort_by { |x| avg_density[x] }.reverse[0..max_chunks-1].map end # This function is the primitive that find_related and classify # build upon. It returns an array of 2-element arrays. The first element # of this array is a document, and the second is its "score", defining # how "close" it is to other indexed items. # # These values are somewhat arbitrary, having to do with the vector space # created by your content, so the magnitude is interpretable but not always # meaningful between indexes. # # The parameter doc is the content to compare. If that content is not # indexed, you can pass an optional block to define how to create the # text data. See add_item for examples of how this works. def proximity_array_for_content( doc, &block ) return [] if needs_rebuild? content_node = node_for_content( doc, &block ) result = @items.keys.collect do |item| if $GSL val = content_node.search_vector * @items[item].search_vector.col else val = (Matrix[content_node.search_vector] * @items[item].search_vector)[0] end [item, val] end result.sort_by { |x| x[1] }.reverse end # Similar to proximity_array_for_content, this function takes similar # arguments and returns a similar array. However, it uses the normalized # calculated vectors instead of their full versions. This is useful when # you're trying to perform operations on content that is much smaller than # the text you're working with. search uses this primitive. def proximity_norms_for_content( doc, &block ) return [] if needs_rebuild? content_node = node_for_content( doc, &block ) result = @items.keys.collect do |item| if $GSL val = content_node.search_norm * @items[item].search_norm.col else val = (Matrix[content_node.search_norm] * @items[item].search_norm)[0] end [item, val] end result.sort_by { |x| x[1] }.reverse end # This function allows for text-based search of your index. Unlike other functions # like find_related and classify, search only takes short strings. It will also ignore # factors like repeated words. It is best for short, google-like search terms. # A search will first priortize lexical relationships, then semantic ones. # # While this may seem backwards compared to the other functions that LSI supports, # it is actually the same algorithm, just applied on a smaller document. def search( string, max_nearest=3 ) return [] if needs_rebuild? carry = proximity_norms_for_content( string ) result = carry.collect { |x| x[0] } return result[0..max_nearest-1] end # This function takes content and finds other documents # that are semantically "close", returning an array of documents sorted # from most to least relavant. # max_nearest specifies the number of documents to return. A value of # 0 means that it returns all the indexed documents, sorted by relavence. # # This is particularly useful for identifing clusters in your document space. # For example you may want to identify several "What's Related" items for weblog # articles, or find paragraphs that relate to each other in an essay. def find_related( doc, max_nearest=3, &block ) carry = proximity_array_for_content( doc, &block ).reject { |pair| pair[0] == doc } result = carry.collect { |x| x[0] } return result[0..max_nearest-1] end # This function uses a voting system to categorize documents, based on # the categories of other documents. It uses the same logic as the # find_related function to find related documents, then returns the # most obvious category from this list. # # cutoff signifies the number of documents to consider when clasifying # text. A cutoff of 1 means that every document in the index votes on # what category the document is in. This may not always make sense. # def classify( doc, cutoff=0.30, &block ) icutoff = (@items.size * cutoff).round carry = proximity_array_for_content( doc, &block ) carry = carry[0..icutoff-1] votes = {} carry.each do |pair| categories = @items[pair[0]].categories categories.each do |category| votes[category] ||= 0.0 votes[category] += pair[1] end end ranking = votes.keys.sort_by { |x| votes[x] } return ranking[-1] end # Prototype, only works on indexed documents. # I have no clue if this is going to work, but in theory # it's supposed to. def highest_ranked_stems( doc, count=3 ) raise "Requested stem ranking on non-indexed content!" unless @items[doc] arr = node_for_content(doc).lsi_vector.to_a top_n = arr.sort.reverse[0..count-1] return top_n.collect { |x| @word_list.word_for_index(arr.index(x))} end private def build_reduced_matrix( matrix, cutoff=0.75 ) # TODO: Check that M>=N on these dimensions! Transpose helps assure this u, v, s = matrix.SV_decomp # TODO: Better than 75% term, please. :\ s_cutoff = s.sort.reverse[(s.size * cutoff).round - 1] s.size.times do |ord| s[ord] = 0.0 if s[ord] < s_cutoff end # Reconstruct the term document matrix, only with reduced rank u * ($GSL ? GSL::Matrix : ::Matrix).diag( s ) * v.trans end def node_for_content(item, &block) if @items[item] return @items[item] else clean_word_hash = block ? block.call(item).clean_word_hash : item.to_s.clean_word_hash cn = ContentNode.new(clean_word_hash, &block) # make the node and extract the data unless needs_rebuild? cn.raw_vector_with( @word_list ) # make the lsi raw and norm vectors end end return cn end def make_word_list @word_list = WordList.new @items.each_value do |node| node.word_hash.each_key { |key| @word_list.add_word key } end end end end classifier-1.3.3/lib/classifier/lsi/0000775000175000017500000000000011752523257017172 5ustar uwabamiuwabamiclassifier-1.3.3/lib/classifier/lsi/word_list.rb0000644000175000017500000000156411752523257021531 0ustar uwabamiuwabami# Author:: David Fayram (mailto:dfayram@lensmen.net) # Copyright:: Copyright (c) 2005 David Fayram II # License:: LGPL module Classifier # This class keeps a word => index mapping. It is used to map stemmed words # to dimensions of a vector. class WordList def initialize @location_table = Hash.new end # Adds a word (if it is new) and assigns it a unique dimension. def add_word(word) term = word @location_table[term] = @location_table.size unless @location_table[term] end # Returns the dimension of the word or nil if the word is not in the space. def [](lookup) term = lookup @location_table[term] end def word_for_index(ind) @location_table.invert[ind] end # Returns the number of words mapped. def size @location_table.size end end end classifier-1.3.3/lib/classifier/lsi/summary.rb0000644000175000017500000000167611752523257021224 0ustar uwabamiuwabami# Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL class String def summary( count=10, separator=" [...] " ) perform_lsi split_sentences, count, separator end def paragraph_summary( count=1, separator=" [...] " ) perform_lsi split_paragraphs, count, separator end def split_sentences split /(\.|\!|\?)/ # TODO: make this less primitive end def split_paragraphs split /(\n\n|\r\r|\r\n\r\n)/ # TODO: make this less primitive end private def perform_lsi(chunks, count, separator) lsi = Classifier::LSI.new :auto_rebuild => false chunks.each { |chunk| lsi << chunk unless chunk.strip.empty? || chunk.strip.split.size == 1 } lsi.build_index summaries = lsi.highest_relative_content count return summaries.reject { |chunk| !summaries.include? chunk }.map { |x| x.strip }.join(separator) end endclassifier-1.3.3/lib/classifier/lsi/content_node.rb0000644000175000017500000000402311752523257022173 0ustar uwabamiuwabami# Author:: David Fayram (mailto:dfayram@lensmen.net) # Copyright:: Copyright (c) 2005 David Fayram II # License:: LGPL module Classifier # This is an internal data structure class for the LSI node. Save for # raw_vector_with, it should be fairly straightforward to understand. # You should never have to use it directly. class ContentNode attr_accessor :raw_vector, :raw_norm, :lsi_vector, :lsi_norm, :categories attr_reader :word_hash # If text_proc is not specified, the source will be duck-typed # via source.to_s def initialize( word_hash, *categories ) @categories = categories || [] @word_hash = word_hash end # Use this to fetch the appropriate search vector. def search_vector @lsi_vector || @raw_vector end # Use this to fetch the appropriate search vector in normalized form. def search_norm @lsi_norm || @raw_norm end # Creates the raw vector out of word_hash using word_list as the # key for mapping the vector space. def raw_vector_with( word_list ) if $GSL vec = GSL::Vector.alloc(word_list.size) else vec = Array.new(word_list.size, 0) end @word_hash.each_key do |word| vec[word_list[word]] = @word_hash[word] if word_list[word] end # Perform the scaling transform total_words = vec.sum # Perform first-order association transform if this vector has more # than one word in it. if total_words > 1.0 weighted_total = 0.0 vec.each do |term| if ( term > 0 ) weighted_total += (( term / total_words ) * Math.log( term / total_words )) end end vec = vec.collect { |val| Math.log( val + 1 ) / -weighted_total } end if $GSL @raw_norm = vec.normalize @raw_vector = vec else @raw_norm = Vector[*vec].normalize @raw_vector = Vector[*vec] end end end end classifier-1.3.3/lib/classifier/extensions/0000775000175000017500000000000011752523257020602 5ustar uwabamiuwabamiclassifier-1.3.3/lib/classifier/extensions/word_hash.rb0000644000175000017500000000443211752523257023106 0ustar uwabamiuwabami# Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL # These are extensions to the String class to provide convenience # methods for the Classifier package. class String # Removes common punctuation symbols, returning a new string. # E.g., # "Hello (greeting's), with {braces} < >...?".without_punctuation # => "Hello greetings with braces " def without_punctuation tr( ',?.!;:"@#$%^&*()_=+[]{}\|<>/`~', " " ) .tr( "'\-", "") end # Return a Hash of strings => ints. Each word in the string is stemmed, # interned, and indexes to its frequency in the document. def word_hash word_hash_for_words(gsub(/[^\w\s]/,"").split + gsub(/[\w]/," ").split) end # Return a word hash without extra punctuation or short symbols, just stemmed words def clean_word_hash word_hash_for_words gsub(/[^\w\s]/,"").split end private def word_hash_for_words(words) d = Hash.new words.each do |word| word.downcase! if word =~ /[\w]+/ key = word.stem.intern if word =~ /[^\w]/ || ! CORPUS_SKIP_WORDS.include?(word) && word.length > 2 d[key] ||= 0 d[key] += 1 end end return d end CORPUS_SKIP_WORDS = [ "a", "again", "all", "along", "are", "also", "an", "and", "as", "at", "but", "by", "came", "can", "cant", "couldnt", "did", "didn", "didnt", "do", "doesnt", "dont", "ever", "first", "from", "have", "her", "here", "him", "how", "i", "if", "in", "into", "is", "isnt", "it", "itll", "just", "last", "least", "like", "most", "my", "new", "no", "not", "now", "of", "on", "or", "should", "sinc", "so", "some", "th", "than", "this", "that", "the", "their", "then", "those", "to", "told", "too", "true", "try", "until", "url", "us", "were", "when", "whether", "while", "with", "within", "yes", "you", "youll", ] endclassifier-1.3.3/lib/classifier/extensions/vector_serialize.rb0000644000175000017500000000043711752523257024502 0ustar uwabamiuwabamimodule GSL class Vector def _dump(v) Marshal.dump( self.to_a ) end def self._load(arr) arry = Marshal.load(arr) return GSL::Vector.alloc(arry) end end class Matrix class < 0 if block_given? map(&block).sum else inject { |sum, element| sum + element }.to_f end end end class Vector def magnitude sumsqs = 0.0 self.size.times do |i| sumsqs += self[i] ** 2.0 end Math.sqrt(sumsqs) end def normalize nv = [] mag = self.magnitude self.size.times do |i| nv << (self[i] / mag) end Vector[*nv] end end class Matrix def Matrix.diag(s) Matrix.diagonal(*s) end alias :trans :transpose def SV_decomp(maxSweeps = 20) if self.row_size >= self.column_size q = self.trans * self else q = self * self.trans end qrot = q.dup v = Matrix.identity(q.row_size) azrot = nil mzrot = nil cnt = 0 s_old = nil mu = nil while true do cnt += 1 for row in (0...qrot.row_size-1) do for col in (1..qrot.row_size-1) do next if row == col h = Math.atan((2 * qrot[row,col])/(qrot[row,row]-qrot[col,col]))/2.0 hcos = Math.cos(h) hsin = Math.sin(h) mzrot = Matrix.identity(qrot.row_size) mzrot[row,row] = hcos mzrot[row,col] = -hsin mzrot[col,row] = hsin mzrot[col,col] = hcos qrot = mzrot.trans * qrot * mzrot v = v * mzrot end end s_old = qrot.dup if cnt == 1 sum_qrot = 0.0 if cnt > 1 qrot.row_size.times do |r| sum_qrot += (qrot[r,r]-s_old[r,r]).abs if (qrot[r,r]-s_old[r,r]).abs > 0.001 end s_old = qrot.dup end break if (sum_qrot <= 0.001 and cnt > 1) or cnt >= maxSweeps end # of do while true s = [] qrot.row_size.times do |r| s << Math.sqrt(qrot[r,r]) end #puts "cnt = #{cnt}" if self.row_size >= self.column_size mu = self * v * Matrix.diagonal(*s).inverse return [mu, v, s] else puts v.row_size puts v.column_size puts self.row_size puts self.column_size puts s.size mu = (self.trans * v * Matrix.diagonal(*s).inverse) return [mu, v, s] end end def []=(i,j,val) @rows[i][j] = val end end classifier-1.3.3/lib/classifier/extensions/string.rb0000644000175000017500000000042011752523257022427 0ustar uwabamiuwabami# Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL require 'fast_stemmer' require 'classifier/extensions/word_hash' class Object def prepare_category_name; to_s.gsub("_"," ").capitalize.intern end end classifier-1.3.3/lib/classifier/bayes.rb0000644000175000017500000000772211752523257020041 0ustar uwabamiuwabami# Author:: Lucas Carlson (mailto:lucas@rufy.com) # Copyright:: Copyright (c) 2005 Lucas Carlson # License:: LGPL module Classifier class Bayes # The class can be created with one or more categories, each of which will be # initialized and given a training method. E.g., # b = Classifier::Bayes.new 'Interesting', 'Uninteresting', 'Spam' def initialize(*categories) @categories = Hash.new categories.each { |category| @categories[category.prepare_category_name] = Hash.new } @total_words = 0 end # # Provides a general training method for all categories specified in Bayes#new # For example: # b = Classifier::Bayes.new 'This', 'That', 'the_other' # b.train :this, "This text" # b.train "that", "That text" # b.train "The other", "The other text" def train(category, text) category = category.prepare_category_name text.word_hash.each do |word, count| @categories[category][word] ||= 0 @categories[category][word] += count @total_words += count end end # # Provides a untraining method for all categories specified in Bayes#new # Be very careful with this method. # # For example: # b = Classifier::Bayes.new 'This', 'That', 'the_other' # b.train :this, "This text" # b.untrain :this, "This text" def untrain(category, text) category = category.prepare_category_name text.word_hash.each do |word, count| if @total_words >= 0 orig = @categories[category][word] @categories[category][word] ||= 0 @categories[category][word] -= count if @categories[category][word] <= 0 @categories[category].delete(word) count = orig end @total_words -= count end end end # # Returns the scores in each category the provided +text+. E.g., # b.classifications "I hate bad words and you" # => {"Uninteresting"=>-12.6997928013932, "Interesting"=>-18.4206807439524} # The largest of these scores (the one closest to 0) is the one picked out by #classify def classifications(text) score = Hash.new @categories.each do |category, category_words| score[category.to_s] = 0 total = category_words.values.inject(0) {|sum, element| sum+element} text.word_hash.each do |word, count| s = category_words.has_key?(word) ? category_words[word] : 0.1 score[category.to_s] += Math.log(s/total.to_f) end end return score end # # Returns the classification of the provided +text+, which is one of the # categories given in the initializer. E.g., # b.classify "I hate bad words and you" # => 'Uninteresting' def classify(text) (classifications(text).sort_by { |a| -a[1] })[0][0] end # # Provides training and untraining methods for the categories specified in Bayes#new # For example: # b = Classifier::Bayes.new 'This', 'That', 'the_other' # b.train_this "This text" # b.train_that "That text" # b.untrain_that "That text" # b.train_the_other "The other text" def method_missing(name, *args) category = name.to_s.gsub(/(un)?train_([\w]+)/, '\2').prepare_category_name if @categories.has_key? category args.each { |text| eval("#{$1}train(category, text)") } elsif name.to_s =~ /(un)?train_([\w]+)/ raise StandardError, "No such category: #{category}" else super #raise StandardError, "No such method: #{name}" end end # # Provides a list of category names # For example: # b.categories # => ['This', 'That', 'the_other'] def categories # :nodoc: @categories.keys.collect {|c| c.to_s} end # # Allows you to add categories to the classifier. # For example: # b.add_category "Not spam" # # WARNING: Adding categories to a trained classifier will # result in an undertrained category that will tend to match # more criteria than the trained selective categories. In short, # try to initialize your categories at initialization. def add_category(category) @categories[category.prepare_category_name] = Hash.new end alias append_category add_category end end