├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── composer.json ├── importReuters.php ├── reuters-21578-json ├── LICENSE ├── README.md ├── justOne.json ├── reuters-000.json ├── reuters-001.json ├── reuters-002.json ├── reuters-003.json ├── reuters-004.json ├── reuters-005.json ├── reuters-006.json ├── reuters-007.json ├── reuters-008.json ├── reuters-009.json ├── reuters-010.json ├── reuters-011.json ├── reuters-012.json ├── reuters-013.json ├── reuters-014.json ├── reuters-015.json ├── reuters-016.json ├── reuters-017.json ├── reuters-018.json ├── reuters-019.json ├── reuters-020.json └── reuters-021.json ├── src └── ElasticBayes │ ├── ElasticBayes.php │ ├── TermCollection.php │ └── TermStats.php └── testReuters.php /.gitignore: -------------------------------------------------------------------------------- 1 | #composer related 2 | composer.lock 3 | vendor/ 4 | composer.phar 5 | 6 | #editor related 7 | .idea 8 | 9 | # OS generated files 10 | .DS_Store 11 | .DS_Store? 12 | ._* 13 | .Spotlight-V100 14 | .Trashes 15 | Icon? 16 | ehthumbs.db 17 | Thumbs.db 18 | 19 | #generator related 20 | generator/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2014 Zachary Tong 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2014 Zachary Tong 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Overview 2 | This is a fun proof-of-concept Naive Bayes classifier built using Elasticsearch aggregations. 3 | 4 | Naive Bayes classifiers work based on term and document frequencies differences between class labels. Elasticsearch is a search engine which is designed to handle term/doc frequencies and aggregating across features (such as labels), so this seemed like a natural fit. 5 | 6 | Most of the code is plumbing...the actual classification only requires two different aggregation queries. 7 | 8 | ### Dataset 9 | This project uses a subtree-split of the [Reuters-21578-JSON dataset](https://github.com/fergiemcdowall/reuters-21578-json). This is the classic Reuters dataset which has been jsonified. 10 | 11 | Note: the newer Reuters RCV1 would have been a better candidate for classification, but I did not feel like writing an XML parser for it :) 12 | 13 | ### Scripts 14 | 15 | - `importReuters.php` : imports the Reuters dataset into Elasticsearch. Data will go into `/reuters/train` and `/reuters/test` 16 | - `testReuters.php` : begins the classification on the test data 17 | - `/src/ElasticBayes/` : the NaiveBayes classification implementation using Elasticsearch 18 | 19 | ### Running this example locally 20 | 21 | ```shell 22 | git clone https://github.com/polyfractal/ElasticBayes.git 23 | curl -s http://getcomposer.org/installer | php 24 | php composer.phar install 25 | php importReuters.php 26 | php testReuters.php 27 | ``` 28 | 29 | ## Training 30 | Training the classifier is simple. Here are the steps: 31 | 32 | 1. Create an index with an appropriate mapping 33 | 2. Index the documents from your corpus 34 | 3. There is no step 3 35 | 36 | Naive Bayes classifiers are "trained" by obtaining term and document frequencies for each label. This is typically done by tokenizing your input, normalizing the tokens, then building an in-memory hash which holds all the data. 37 | 38 | Elasticsearch does this natively out of the box. Just create an analyzer and index documents. Voila! Trained Naive Bayes classifier 39 | 40 | ## Testing 41 | Once the clssifier has been "trained", we can use it to predict the classes of new documents. Rather than walk through all the code, I am going to show the salient Elasticsearch queries and explain their purpose. The rest of the code should be trivial to understand, since it is just logistical plumbing. 42 | 43 | There are three fields and two sets of labels that you can potentially test on: 44 | 45 | **Labels** 46 | - `topics` 47 | - `places` 48 | 49 | **Input Fields** 50 | - `body` 51 | - `title` 52 | - `combined` - both `body` and `title` concatenated into a single field 53 | 54 | #### Total label counts 55 | This query obtains the set of labels and their counts. 56 | 57 | ```php 58 | $params = [ 59 | 'index' => 'reuters', 60 | 'type' => 'train', 61 | 'search_type' => 'count', 62 | 'body' => [ 63 | 'aggs' => [ 64 | 'counts' => [ 65 | 'terms' => [ 66 | 'field' => $this->field, 67 | 'size' => 200 68 | ] 69 | ] 70 | ] 71 | ] 72 | ]; 73 | $results = $this->client->search($params); 74 | ``` 75 | 76 | #### Text analysis 77 | This query takes an input text and passes it through the analyzer for the field we are interested in. This will return a list of post-analysis tokens that we can use to build statistics on. 78 | 79 | For example, the input "The Quick brown fox" might return the tokens: [`quick`, `brown`, `fox`]. 80 | 81 | This step is important since we need the post-analysis version of the token. For simple analyzers this is trivial to do in application code, but more advanced analyzers which include stemming, stopword remove, negation tagging, etc require this analysis step 82 | 83 | ```php 84 | $params = [ 85 | 'index' => 'reuters', 86 | 'field' => $this->textField, 87 | 'body' => $data 88 | ]; 89 | 90 | $terms = $this->client->indices()->analyze($params); 91 | ``` 92 | 93 | #### Term Statistics 94 | This query is executed once for each term in the input document. It first filters 95 | out all documents which do not have our term (note: term is post-analysis, so we can safely use a term filter and benefit from caching). 96 | 97 | The query then performs an aggregation that collects the document counts for each label. 98 | 99 | The data that this query returns is the label counts for the term we are interested in. 100 | ```php 101 | $params = [ 102 | 'index' => 'reuters', 103 | 'type' => 'train', 104 | 'search_type' => 'count', 105 | 'body' => [ 106 | 'query' => [ 107 | 'filtered' => [ 108 | 'filter' => [ 109 | 'term' => [ 110 | $textField => $this->term 111 | ] 112 | ] 113 | ] 114 | ], 115 | 'aggs' => [ 116 | 'counts' => [ 117 | 'terms' => [ 118 | 'field' => $labelField, 119 | 'size' => 200 120 | ] 121 | ] 122 | ] 123 | ] 124 | ]; 125 | $results = $this->client->search($params); 126 | ``` 127 | 128 | #### Naive Bayes Math 129 | Once we have all the data from the above queries, we can very easily calculate the probability that a term belongs to a certain label. 130 | 131 | The code is fairly well commented and should be self-explanatory. For a more laymen's explanation, [see this excellent tutorial](http://burakkanber.com/blog/machine-learning-naive-bayes-1/). 132 | 133 | ```php 134 | /** 135 | * This is where all the Naive Bayes magic happens. 136 | * This function returns the predicted label score for the 137 | * current collection of terms 138 | * 139 | * For a good 'layman' explanation, see: http://burakkanber.com/blog/machine-learning-naive-bayes-1/ 140 | */ 141 | public function scoreLabel($label) { 142 | 143 | $logSum = 0; 144 | foreach ($this->terms as $term) { 145 | $termCount = $term->getTermCount(); 146 | if ($termCount === 0) { 147 | // Ignore terms that we have never seen before 148 | continue; 149 | } 150 | 151 | // a posteriori probability of $term conditioned on $label 152 | // (how often does $term occur in $label ?) 153 | $pXH = $term->getLabelProb($label); 154 | 155 | // a posteriori probability of $term conditioned on all other labels 156 | // (how often does $term occur in other labels?) 157 | $pNotXH = $term->getInverseLabelProb($label); 158 | 159 | // a priori probability of $label 160 | // (how many docs have this label?) 161 | // In reality, this term often hurts prediction accuracy, but I left it in to show hot it is done 162 | //$pH = $this->labelStats[$label]['prob']; 163 | $pH = 1; 164 | 165 | //$posteriori = ($pXH * $pH) / ($pXH + $pNotXH + 0.0001); 166 | // ^^^ Technically the 'accurate' formula, but the denominator is always 1 167 | $posteriori = ($pXH * $pH); 168 | 169 | // Normalize rarely seen terms. This also tends to hurt prediction accuracy imo 170 | //$posteriori = ( ( 5 * 0.5) + ($termCount * $posteriori) ) / ( 5 + $termCount); 171 | if ($posteriori === 0) { 172 | $posteriori = 0.00001; 173 | } elseif ($posteriori === 1) { 174 | $posteriori = 0.99999; 175 | } 176 | 177 | $logSum += log(1 - $posteriori) - log($posteriori); 178 | } 179 | 180 | return 1 / ( 1 + exp($logSum)); 181 | } 182 | ``` 183 | 184 | ### Performance (Speed) 185 | The code in this project is almost certainly not optimized for maximum performance. Firstly, it is written in PHP :P It is evident while running tests that PHP is the bottleneck and not Elasticearch. 186 | 187 | This code utilizes an LRU cache to keep frequently used terms cached in memory, which helps offest the PHP tax. 188 | 189 | With that said, the classifier can crank out predictions at an appreciable rate, even with the PHP tax. It would be perfectly usable as an online, one-pass classifier as data streams into your system. 190 | 191 | As an interesting side-effect, since the vast majority of the computation and heavy lifting is being performed by Elasticsearch, you can effectively build an "out of core" classifier in any language, such as PHP (which normally wouldn't have a prayer at high performance ML). It may be slower than a 100% in-memory solution, but it is much more scalable and hardware can be thrown at the problem easily. 192 | 193 | ### Classification Performance 194 | Classification performance is moderate to good. While playing with the dataset, I obtained accuracies ranging from 0.56 to 0.69. 195 | Admittedly, I didn't spend much time fiddling...this was mostly a proof-of-concept to implement a NaiveBayes in Elasticsearch, 196 | not to build a good classification model for Reuters. 197 | 198 | Classification accuracy boils down to intelligent preprocessing and normalization. Some potential routes to take: 199 | 200 | - Stemming (kstem, snowball, porter stemmer) 201 | - Stopword removal 202 | - Shingles 203 | - Frequency filtering 204 | - Negation tagging 205 | 206 | Note: Accuracy is generally a poor metric to optimize, especially in an unbalanced dataset. Double-especially on multi-class datasets like Reuters. This script simply calculates the accuracy of the top prediction and label. It does not inspect the rest of the labels, or the ordering of predictions. 207 | 208 | Since this is not a rigorous paper, accuracy was the easiest/fastest to calculate. Better metrics would include AUC, micro/macro F-measures and Balanced Error Rate. -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "require": { 3 | "elasticsearch/elasticsearch": "~1.0", 4 | "lrucache/lrucache": "master-dev" 5 | }, 6 | "autoload": { 7 | "psr-0": { 8 | "ElasticBayes": "src/" 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /importReuters.php: -------------------------------------------------------------------------------- 1 | indices()->delete(['index' => 'reuters', 'ignore' => 404]); 8 | $params = ['index' => 'reuters', 'body' => [ 9 | 'settings' => [ 10 | 'number_of_shards' => 1, 11 | 'number_of_replicas' => 0, 12 | 'analysis' => [ 13 | 'filter' => [ 14 | 'shingle' => [ 15 | 'type' => 'shingle' 16 | ] 17 | ], 18 | 'char_filter' => [ 19 | 'pre_negs' => [ 20 | 'type' => 'pattern_replace', 21 | 'pattern' => '(\\w+)\\s+((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\b', 22 | 'replacement' => '~$1 $2' 23 | ], 24 | 'post_negs' => [ 25 | 'type' => 'pattern_replace', 26 | 'pattern' => '\\b((?i:never|no|nothing|nowhere|noone|none|not|havent|hasnt|hadnt|cant|couldnt|shouldnt|wont|wouldnt|dont|doesnt|didnt|isnt|arent|aint))\\s+(\\w+)', 27 | 'replacement' => '$1 ~$2' 28 | ] 29 | ], 30 | 'analyzer' => [ 31 | 'reuters' => [ 32 | 'type' => 'custom', 33 | 'tokenizer' => 'standard', 34 | 'filter' => ['lowercase', 'stop', 'kstem'] 35 | ] 36 | ] 37 | ] 38 | ], 39 | 'mappings' => [ 40 | '_default_' => [ 41 | 'properties' => [ 42 | 'title' => [ 43 | 'type' => 'string', 44 | 'analyzer' => 'reuters', 45 | 'term_vector' => 'yes', 46 | 'copy_to' => 'combined' 47 | ], 48 | 'body' => [ 49 | 'type' => 'string', 50 | 'analyzer' => 'reuters', 51 | 'term_vector' => 'yes', 52 | 'copy_to' => 'combined' 53 | ], 54 | 'combined' => [ 55 | 'type' => 'string', 56 | 'analyzer' => 'reuters', 57 | 'term_vector' => 'yes' 58 | ], 59 | 'topics' => [ 60 | 'type' => 'string', 61 | 'index' => 'not_analyzed' 62 | ], 63 | 'places' => [ 64 | 'type' => 'string', 65 | 'index' => 'not_analyzed' 66 | ] 67 | ] 68 | ] 69 | ] 70 | ]]; 71 | $client->indices()->create($params); 72 | 73 | $params = []; 74 | for ($i = 0; $i < 17; ++$i) { 75 | $dir = realpath(dirname(__FILE__)); 76 | $fileNum = sprintf('%03d', $i); 77 | $data = file_get_contents("$dir/reuters-21578-json/reuters-$fileNum.json"); 78 | $data = json_decode($data, true); 79 | 80 | foreach ($data as $doc) { 81 | $params['body'][] = array('index' => array()); 82 | $params['body'][] = $doc; 83 | } 84 | 85 | $params['index'] = 'reuters'; 86 | $params['type'] = 'train'; 87 | $client->bulk($params); 88 | echo "\n$i"; 89 | $params = array(); 90 | 91 | } 92 | 93 | for ($i = 17; $i < 22; ++$i) { 94 | $dir = realpath(dirname(__FILE__)); 95 | $fileNum = sprintf('%03d', $i); 96 | $data = file_get_contents("$dir/reuters-21578-json/reuters-$fileNum.json"); 97 | $data = json_decode($data, true); 98 | 99 | foreach ($data as $doc) { 100 | $params['body'][] = array('index' => array()); 101 | $params['body'][] = $doc; 102 | } 103 | 104 | $params['index'] = 'reuters'; 105 | $params['type'] = 'test'; 106 | $client->bulk($params); 107 | echo "\n$i"; 108 | $params = array(); 109 | 110 | } 111 | -------------------------------------------------------------------------------- /reuters-21578-json/LICENSE: -------------------------------------------------------------------------------- 1 | Licence as per the terms of 2 | http://www.daviddlewis.com/resources/testcollections/reuters21578/readme.txt 3 | -------------------------------------------------------------------------------- /reuters-21578-json/README.md: -------------------------------------------------------------------------------- 1 | reuters-21578-json 2 | ================== 3 | 4 | An terse and JSONified version of the Reuters 21578 dataset 5 | -------------------------------------------------------------------------------- /reuters-21578-json/justOne.json: -------------------------------------------------------------------------------- 1 | {"1001":{"title":"SANDOZ PLANS WEEDKILLER JOINT VENTURE IN USSR","body":"Sandoz AG said it planned a joint venture\nto produce herbicides in the Soviet Union.\n The company said it had signed a letter of intent with the\nSoviet Ministry of Fertiliser Production to form the first\nforeign joint venture the ministry had undertaken since the\nSoviet Union allowed Western firms to enter into joint ventures\ntwo months ago.\n The ministry and Sandoz will each have a 50 pct stake, but\na company spokeswoman was unable to give details of the size of\ninvestment or planned output.\n Reuter\n\u0003","topics":["ussr"]}} 2 | -------------------------------------------------------------------------------- /src/ElasticBayes/ElasticBayes.php: -------------------------------------------------------------------------------- 1 | client = new Client(); 20 | $this->field = $labelField; 21 | $this->getLabelCounts(); 22 | $this->termLRU = new \LRUCache\LRUCache(10000); 23 | } 24 | 25 | /** 26 | * Predict the label scores for a certain piece of text. Scores are 27 | * sorted and normalized 1-100 by default 28 | */ 29 | public function predict($data, $textField, $normalize = true) { 30 | $termCollection = new TermCollection($this->client, $this->termLRU, $this->labels, $data); 31 | $termCollection->setLabelField($this->field); 32 | $termCollection->setTextField($textField); 33 | $termCollection->collectTerms($data); 34 | 35 | $scores = []; 36 | foreach ($this->labels as $label => $labelStats) { 37 | $scores[$label] = $termCollection->scoreLabel($label, $textField); 38 | } 39 | 40 | arsort($scores); 41 | return $normalize ? $this->normalize($scores) : $scores; 42 | 43 | } 44 | 45 | private function normalize($data) { 46 | $max = max($data); 47 | if ($max == 0) { 48 | $evenDistro = 100 / count($data); 49 | foreach ($data as $i => $v) { 50 | $data[$i] = $evenDistro; 51 | } 52 | } else { 53 | foreach ($data as $i => $v) { 54 | $data[$i] = ($v / $max) * 100; 55 | } 56 | } 57 | 58 | return $data; 59 | } 60 | 61 | /** 62 | * Before we can do anything, we need to know the distribution of label 63 | * counts across the whole index 64 | */ 65 | private function getLabelCounts() { 66 | 67 | $params = [ 68 | 'index' => 'reuters', 69 | 'type' => 'train', 70 | 'search_type' => 'count', 71 | 'body' => [ 72 | 'aggs' => [ 73 | 'counts' => [ 74 | 'terms' => [ 75 | 'field' => $this->field, 76 | 'size' => 200 77 | ] 78 | ] 79 | ] 80 | ] 81 | ]; 82 | 83 | $results = $this->client->search($params); 84 | 85 | $this->totalDocCount = $results['hits']['total']; 86 | foreach ($results['aggregations']['counts']['buckets'] as $bucket) { 87 | $this->labels[$bucket['key']]['count'] = $bucket['doc_count']; 88 | $this->labels[$bucket['key']]['prob'] = $bucket['doc_count'] / $this->totalDocCount; 89 | } 90 | } 91 | 92 | } -------------------------------------------------------------------------------- /src/ElasticBayes/TermCollection.php: -------------------------------------------------------------------------------- 1 | client = $client; 30 | $this->labelStats = $labelStats; 31 | $this->termLRU = $termLRU; 32 | } 33 | 34 | /** 35 | * sets the field that we will collect labels from. 36 | * In the reuters dataset, this will be either 'topics' or 'places' 37 | */ 38 | public function setLabelField($labelField) { 39 | $this->labelField = $labelField; 40 | } 41 | 42 | /** 43 | * sets the field where we will collect terms from 44 | * In the reuters dataset, this will be 'body', 'title', or 'combined' 45 | */ 46 | public function setTextField($textField) { 47 | $this->textField = $textField; 48 | } 49 | 50 | /** 51 | * given an input text, we need to analyze it and then collect 52 | * stats for each term 53 | */ 54 | public function collectTerms($data) { 55 | 56 | // Get the post-analysis terms from this input text 57 | $terms = $this->getTerms($data); 58 | 59 | // And farm out the stat collection to TermStats object 60 | foreach ($terms as $term) { 61 | $t = new TermStats($this->client, $this->termLRU, $term['token'], count($this->labelStats)); 62 | $t->collectStats( $this->labelField, $this->textField); 63 | $this->terms[] = $t; 64 | } 65 | } 66 | 67 | /** 68 | * This is where all the Naive Bayes magic happens. 69 | * This function returns the predicted label score for the 70 | * current collection of terms 71 | * 72 | * For a good 'layman' explanation, see: http://burakkanber.com/blog/machine-learning-naive-bayes-1/ 73 | */ 74 | public function scoreLabel($label) { 75 | 76 | $logSum = 0; 77 | foreach ($this->terms as $term) { 78 | $termCount = $term->getTermCount(); 79 | if ($termCount === 0) { 80 | // Ignore terms that we have never seen before 81 | continue; 82 | } 83 | 84 | // a posteriori probability of $term conditioned on $label 85 | // (how often does $term occur in $label ?) 86 | $pXH = $term->getLabelProb($label); 87 | 88 | // a posteriori probability of $term conditioned on all other labels 89 | // (how often does $term occur in other labels?) 90 | $pNotXH = $term->getInverseLabelProb($label); 91 | 92 | // a priori probability of $label 93 | // (how many docs have this label?) 94 | // In reality, this term often hurts prediction accuracy, but I left it in to show hot it is done 95 | //$pH = $this->labelStats[$label]['prob']; 96 | $pH = 1; 97 | 98 | //$posteriori = ($pXH * $pH) / ($pXH + $pNotXH + 0.0001); 99 | // ^^^ Technically the 'accurate' formula, but the denominator is always 1 100 | $posteriori = ($pXH * $pH); 101 | 102 | // Normalize rarely seen terms. This also tends to hurt prediction accuracy imo 103 | //$posteriori = ( ( 5 * 0.5) + ($termCount * $posteriori) ) / ( 5 + $termCount); 104 | if ($posteriori === 0) { 105 | $posteriori = 0.00001; 106 | } elseif ($posteriori === 1) { 107 | $posteriori = 0.99999; 108 | } 109 | 110 | $logSum += log(1 - $posteriori) - log($posteriori); 111 | } 112 | 113 | return 1 / ( 1 + exp($logSum)); 114 | } 115 | 116 | /** 117 | * Performs a call to /_analyze, so that we can retrieve 118 | * a collection of post-analysis terms 119 | */ 120 | private function getTerms($data) { 121 | $params = [ 122 | 'index' => 'reuters', 123 | 'field' => $this->textField, 124 | 'body' => $data 125 | ]; 126 | 127 | $terms = $this->client->indices()->analyze($params); 128 | 129 | return $terms['tokens']; 130 | 131 | } 132 | } -------------------------------------------------------------------------------- /src/ElasticBayes/TermStats.php: -------------------------------------------------------------------------------- 1 | term = $term; 25 | $this->client = $client; 26 | $this->labelCardinality = $cardinality; 27 | $this->termLRU = $termLRU; 28 | } 29 | 30 | /** 31 | * Collect the statistics for this term. 32 | * Stats include total doc count and count-per-label 33 | */ 34 | public function collectStats($labelField, $textField) { 35 | 36 | // We are using an LRU cache so we don't have to whack ES on every term 37 | // If it is in the cache, use it, otherwise ask ES politely 38 | $cached = $this->termLRU->get($this->term); 39 | if ($cached !== null) { 40 | $cached = unserialize($cached); 41 | $this->numDocsWithTerm = $cached['hits']['total']; 42 | $this->labelCounts = array_fill(0, $this->labelCardinality, 0); 43 | foreach ($cached['aggregations']['counts']['buckets'] as $bucket) { 44 | $this->labelCounts[$bucket['key']] = $bucket['doc_count']; 45 | } 46 | return; 47 | } 48 | 49 | /** 50 | * This query is the main guts of the NaiveBayes statistics. It: 51 | * - finds all documents containing the term (note: post-analysis term filter) 52 | * - terms agg over the labels to get label counts for this term 53 | */ 54 | $params = [ 55 | 'index' => 'reuters', 56 | 'type' => 'train', 57 | 'search_type' => 'count', 58 | 'body' => [ 59 | 'query' => [ 60 | 'filtered' => [ 61 | 'filter' => [ 62 | 'term' => [ 63 | $textField => $this->term 64 | ] 65 | ] 66 | ] 67 | ], 68 | 'aggs' => [ 69 | 'counts' => [ 70 | 'terms' => [ 71 | 'field' => $labelField, 72 | 'size' => 200 73 | ] 74 | ] 75 | ] 76 | ] 77 | ]; 78 | $results = $this->client->search($params); 79 | 80 | // Logistics to make the counts usable 81 | $this->numDocsWithTerm = $results['hits']['total']; 82 | $this->labelCounts = array_fill(0, $this->labelCardinality, 0); 83 | foreach ($results['aggregations']['counts']['buckets'] as $bucket) { 84 | $this->labelCounts[$bucket['key']] = $bucket['doc_count']; 85 | } 86 | 87 | // Stick it in the cache for future use 88 | $this->termLRU->put($this->term, serialize($results)); 89 | } 90 | 91 | /** 92 | * Return the probability that this label has this term 93 | */ 94 | public function getLabelProb($label) { 95 | if (isset($this->labelCounts[$label]) === false) { 96 | return 0; 97 | } 98 | return $this->labelCounts[$label] / $this->numDocsWithTerm; 99 | } 100 | 101 | /** 102 | * Return the probability that all other labels have this term 103 | */ 104 | public function getInverseLabelProb($label) { 105 | if (isset($this->labelCounts[$label]) === false) { 106 | return 0; 107 | } 108 | return ($this->numDocsWithTerm - $this->labelCounts[$label]) / $this->numDocsWithTerm; 109 | } 110 | 111 | public function getTermCount() { 112 | return $this->numDocsWithTerm; 113 | } 114 | 115 | 116 | } -------------------------------------------------------------------------------- /testReuters.php: -------------------------------------------------------------------------------- 1 | predict($testText, 'body'); 26 | 27 | $predicted = implode(",", array_keys(array_slice($scores, 0, count($doc['topics'])+5))); 28 | $actual = implode(",",$doc['topics']); 29 | 30 | if ($actual[0] == $predicted[0]) { 31 | $correctPredictions += 1; 32 | } 33 | 34 | echo "$numTest: P:[$predicted] A:[$actual]\n"; 35 | } 36 | 37 | $accuracy = $correctPredictions / $numTest; 38 | echo "Final Accuracy: $accuracy\n"; 39 | 40 | 41 | } 42 | 43 | 44 | --------------------------------------------------------------------------------