├── .gitignore ├── LICENSE ├── README.md ├── corpus.py ├── display.py ├── predict.py ├── reviews.py ├── reviews_parallel.py ├── settings.py ├── stopwords.txt ├── train.py └── yelp └── yelp-reviews.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | bin/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | eggs/ 16 | lib/ 17 | lib64/ 18 | parts/ 19 | sdist/ 20 | var/ 21 | *.egg-info/ 22 | .installed.cfg 23 | *.egg 24 | 25 | # Installer logs 26 | pip-log.txt 27 | pip-delete-this-directory.txt 28 | 29 | # Unit test / coverage reports 30 | htmlcov/ 31 | .tox/ 32 | .coverage 33 | .cache 34 | nosetests.xml 35 | coverage.xml 36 | 37 | # Translations 38 | *.mo 39 | 40 | # Mr Developer 41 | .mr.developer.cfg 42 | .project 43 | .pydevproject 44 | 45 | # Rope 46 | .ropeproject 47 | 48 | # Django stuff: 49 | *.log 50 | *.pot 51 | 52 | # Sphinx documentation 53 | docs/_build/ 54 | 55 | .idea/ 56 | examples/ 57 | models/ 58 | providers/ 59 | yelp/dataset/ 60 | yelp/academic/ 61 | yelp/phoenix/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Topics 2 | ==== 3 | 4 | Please read more about this repository on my blog http://www.vladsandulescu.com/topic-prediction-lda-user-reviews/ 5 | -------------------------------------------------------------------------------- /corpus.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | from pymongo import MongoClient 5 | from nltk.stem.wordnet import WordNetLemmatizer 6 | 7 | from settings import Settings 8 | 9 | 10 | tags_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.TAGS_DATABASE][Settings.REVIEWS_COLLECTION] 11 | corpus_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.TAGS_DATABASE][Settings.CORPUS_COLLECTION] 12 | 13 | reviews_cursor = tags_collection.find() 14 | reviewsCount = reviews_cursor.count() 15 | reviews_cursor.batch_size(5000) 16 | 17 | lem = WordNetLemmatizer() 18 | 19 | done = 0 20 | start = time.time() 21 | 22 | for review in reviews_cursor: 23 | nouns = [] 24 | words = [word for word in review["words"] if word["pos"] in ["NN", "NNS"]] 25 | 26 | for word in words: 27 | nouns.append(lem.lemmatize(word["word"])) 28 | 29 | corpus_collection.insert({ 30 | "reviewId": review["reviewId"], 31 | "business": review["business"], 32 | "text": review["text"], 33 | "words": nouns 34 | }) 35 | 36 | done += 1 37 | if done % 100 == 0: 38 | end = time.time() 39 | os.system('cls') 40 | print 'Done ' + str(done) + ' out of ' + str(reviewsCount) + ' in ' + str((end - start)) -------------------------------------------------------------------------------- /display.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from gensim.models import LdaModel 4 | from gensim import corpora 5 | 6 | 7 | logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) 8 | 9 | dictionary_path = "models/dictionary.dict" 10 | corpus_path = "models/corpus.lda-c" 11 | lda_num_topics = 50 12 | lda_model_path = "models/lda_model_50_topics.lda" 13 | 14 | dictionary = corpora.Dictionary.load(dictionary_path) 15 | corpus = corpora.BleiCorpus(corpus_path) 16 | lda = LdaModel.load(lda_model_path) 17 | 18 | for i, topic in enumerate(lda.show_topics(num_topics=lda_num_topics)): 19 | print '#%i: %s' %(i, str(topic)) 20 | 21 | -------------------------------------------------------------------------------- /predict.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from gensim.models import LdaModel 4 | from gensim import corpora 5 | import nltk 6 | from nltk.stem.wordnet import WordNetLemmatizer 7 | 8 | 9 | class Predict(): 10 | def __init__(self): 11 | dictionary_path = "models/dictionary.dict" 12 | lda_model_path = "models/lda_model_50_topics.lda" 13 | self.dictionary = corpora.Dictionary.load(dictionary_path) 14 | self.lda = LdaModel.load(lda_model_path) 15 | 16 | def load_stopwords(self): 17 | stopwords = {} 18 | with open('stopwords.txt', 'rU') as f: 19 | for line in f: 20 | stopwords[line.strip()] = 1 21 | 22 | return stopwords 23 | 24 | def extract_lemmatized_nouns(self, new_review): 25 | stopwords = self.load_stopwords() 26 | words = [] 27 | 28 | sentences = nltk.sent_tokenize(new_review.lower()) 29 | for sentence in sentences: 30 | tokens = nltk.word_tokenize(sentence) 31 | text = [word for word in tokens if word not in stopwords] 32 | tagged_text = nltk.pos_tag(text) 33 | 34 | for word, tag in tagged_text: 35 | words.append({"word": word, "pos": tag}) 36 | 37 | lem = WordNetLemmatizer() 38 | nouns = [] 39 | for word in words: 40 | if word["pos"] in ["NN", "NNS"]: 41 | nouns.append(lem.lemmatize(word["word"])) 42 | 43 | return nouns 44 | 45 | def run(self, new_review): 46 | nouns = self.extract_lemmatized_nouns(new_review) 47 | new_review_bow = self.dictionary.doc2bow(nouns) 48 | new_review_lda = self.lda[new_review_bow] 49 | 50 | print new_review_lda 51 | 52 | 53 | def main(): 54 | logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) 55 | 56 | new_review = "It's like eating with a big Italian family. " \ 57 | "Great, authentic Italian food, good advice when asked, and terrific service. " \ 58 | "With a party of 9, last minute on a Saturday night, we were sat within 15 minutes. " \ 59 | "The owner chatted with our kids, and made us feel at home. " \ 60 | "They have meat-filled raviolis, which I can never find. " \ 61 | "The Fettuccine Alfredo was delicious. We had just about every dessert on the menu. " \ 62 | "The tiramisu had only a hint of coffee, the cannoli was not overly sweet, " \ 63 | "and they had this custard with wine that was so strangely good. " \ 64 | "It was an overall great experience!" 65 | 66 | predict = Predict() 67 | predict.run(new_review) 68 | 69 | 70 | if __name__ == '__main__': 71 | main() 72 | 73 | 74 | -------------------------------------------------------------------------------- /reviews.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | 4 | from pymongo import MongoClient 5 | import nltk 6 | 7 | from settings import Settings 8 | 9 | 10 | reviews_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.REVIEWS_DATABASE][ 11 | Settings.REVIEWS_COLLECTION] 12 | tags_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.TAGS_DATABASE][Settings.REVIEWS_COLLECTION] 13 | 14 | reviews_cursor = reviews_collection.find() 15 | reviewsCount = reviews_cursor.count() 16 | reviews_cursor.batch_size(1000) 17 | 18 | stopwords = {} 19 | with open('stopwords.txt', 'rU') as f: 20 | for line in f: 21 | stopwords[line.strip()] = 1 22 | 23 | done = 0 24 | start = time.time() 25 | 26 | for review in reviews_cursor: 27 | words = [] 28 | sentences = nltk.sent_tokenize(review["text"].lower()) 29 | 30 | for sentence in sentences: 31 | tokens = nltk.word_tokenize(sentence) 32 | text = [word for word in tokens if word not in stopwords] 33 | tagged_text = nltk.pos_tag(text) 34 | 35 | for word, tag in tagged_text: 36 | words.append({"word": word, "pos": tag}) 37 | 38 | tags_collection.insert({ 39 | "reviewId": review["reviewId"], 40 | "business": review["business"], 41 | "text": review["text"], 42 | "words": words 43 | }) 44 | 45 | done += 1 46 | if done % 100 == 0: 47 | end = time.time() 48 | os.system('cls') 49 | print 'Done ' + str(done) + ' out of ' + str(reviewsCount) + ' in ' + str((end - start)) -------------------------------------------------------------------------------- /reviews_parallel.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import time 3 | import sys 4 | 5 | import nltk 6 | from pymongo import MongoClient 7 | 8 | from settings import Settings 9 | 10 | 11 | def load_stopwords(): 12 | stopwords = {} 13 | with open('stopwords.txt', 'rU') as f: 14 | for line in f: 15 | stopwords[line.strip()] = 1 16 | 17 | return stopwords 18 | 19 | 20 | def worker(identifier, skip, count): 21 | done = 0 22 | start = time.time() 23 | 24 | stopwords = load_stopwords() 25 | reviews_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.REVIEWS_DATABASE][ 26 | Settings.REVIEWS_COLLECTION] 27 | tags_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.TAGS_DATABASE][ 28 | Settings.REVIEWS_COLLECTION] 29 | 30 | batch_size = 50 31 | for batch in range(0, count, batch_size): 32 | reviews_cursor = reviews_collection.find().skip(skip + batch).limit(batch_size) 33 | for review in reviews_cursor: 34 | words = [] 35 | sentences = nltk.sent_tokenize(review["text"].lower()) 36 | 37 | for sentence in sentences: 38 | tokens = nltk.word_tokenize(sentence) 39 | text = [word for word in tokens if word not in stopwords] 40 | tagged_text = nltk.pos_tag(text) 41 | 42 | for word, tag in tagged_text: 43 | words.append({"word": word, "pos": tag}) 44 | 45 | tags_collection.insert({ 46 | "reviewId": review["reviewId"], 47 | "business": review["business"], 48 | "text": review["text"], 49 | "words": words 50 | }) 51 | 52 | done += 1 53 | if done % 100 == 0: 54 | end = time.time() 55 | print 'Worker' + str(identifier) + ': Done ' + str(done) + ' out of ' + str(count) + ' in ' + ( 56 | "%.2f" % (end - start)) + ' sec ~ ' + ("%.2f" % (done / (end - start))) + '/sec' 57 | sys.stdout.flush() 58 | 59 | 60 | def main(): 61 | reviews_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.REVIEWS_DATABASE][ 62 | Settings.REVIEWS_COLLECTION] 63 | reviews_cursor = reviews_collection.find() 64 | count = reviews_cursor.count() 65 | workers = 3 66 | batch = count / workers 67 | left = count % workers 68 | 69 | jobs = [] 70 | for i in range(workers): 71 | size = count / workers 72 | if i == (workers - 1): 73 | size += left 74 | p = multiprocessing.Process(target=worker, args=((i + 1), i * batch, size)) 75 | jobs.append(p) 76 | p.start() 77 | 78 | for j in jobs: 79 | j.join() 80 | print '%s.exitcode = %s' % (j.name, j.exitcode) 81 | 82 | 83 | if __name__ == '__main__': 84 | main() 85 | -------------------------------------------------------------------------------- /settings.py: -------------------------------------------------------------------------------- 1 | class Settings: 2 | def __init__(self): 3 | pass 4 | 5 | DATASET_FILE = 'dataset/yelp_dataset_challenge_academic_dataset' 6 | MONGO_CONNECTION_STRING = "mongodb://localhost:27030/" 7 | REVIEWS_DATABASE = "Dataset_Challenge_Reviews" 8 | TAGS_DATABASE = "Tags" 9 | REVIEWS_COLLECTION = "Reviews" 10 | CORPUS_COLLECTION = "Corpus" -------------------------------------------------------------------------------- /stopwords.txt: -------------------------------------------------------------------------------- 1 | a a's able about above according accordingly across actually after afterwards again against ain't all allow allows almost alone along already also although always am among amongst an and another any anybody anyhow anyone anything anyway anyways anywhere apart appear appreciate appropriate are aren't around as aside ask asking associated at available away awfully b be became because become becomes becoming been before beforehand behind being believe below beside besides best better between beyond both brief but by c c'mon c's came can can't cannot cant cause causes certain certainly changes clearly co com come comes concerning consequently consider considering contain containing contains corresponding could couldn't course currently d definitely described despite did didn't different do does doesn't doing don't done down downwards during e each edu eg eight either else elsewhere enough entirely especially et etc even ever every everybody everyone everything everywhere ex exactly example except f far few fifth first five followed following follows for former formerly forth four from further furthermore g get gets getting given gives go goes going gone got gotten greetings h had hadn't happens hardly has hasn't have haven't having he he's hello help hence her here here's hereafter hereby herein hereupon hers herself hi him himself his hither hopefully how howbeit however i i'd i'll i'm i've ie if ignored immediate in inasmuch inc indeed indicate indicated indicates inner insofar instead into inward is isn't it it'd it'll it's its itself j just k keep keeps kept know knows known l last lately later latter latterly least less lest let let's like liked likely little look looking looks ltd m mainly many may maybe me mean meanwhile merely might more moreover most mostly much must my myself n name namely nd near nearly necessary need needs neither never nevertheless new next nine no nobody non none noone nor normally not nothing novel now nowhere o obviously of off often oh ok okay old on once one ones only onto or other others otherwise ought our ours ourselves out outside over overall own p particular particularly per perhaps placed please plus possible presumably probably provides q que quite qv r rather rd re really reasonably regarding regardless regards relatively respectively right s said same saw say saying says second secondly see seeing seem seemed seeming seems seen self selves sensible sent serious seriously seven several shall she should shouldn't since six so some somebody somehow someone something sometime sometimes somewhat somewhere soon sorry specified specify specifying still sub such sup sure t t's take taken tell tends th than thank thanks thanx that that's thats the their theirs them themselves then thence there there's thereafter thereby therefore therein theres thereupon these they they'd they'll they're they've think third this thorough thoroughly those though three through throughout thru thus to together too took toward towards tried tries truly try trying twice two u un under unfortunately unless unlikely until unto up upon us use used useful uses using usually uucp v value various very via viz vs w want wants was wasn't way we we'd we'll we're we've welcome well went were weren't what what's whatever when whence whenever where where's whereafter whereas whereby wherein whereupon wherever whether which while whither who who's whoever whole whom whose why will willing wish with within without won't wonder would would wouldn't x y yes yet you you'd you'll you're you've your yours yourself yourselves z zero -------------------------------------------------------------------------------- /train.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import gensim 4 | from gensim.corpora import BleiCorpus 5 | from gensim import corpora 6 | from pymongo import MongoClient 7 | 8 | from settings import Settings 9 | 10 | 11 | class Corpus(object): 12 | def __init__(self, cursor, reviews_dictionary, corpus_path): 13 | self.cursor = cursor 14 | self.reviews_dictionary = reviews_dictionary 15 | self.corpus_path = corpus_path 16 | 17 | def __iter__(self): 18 | self.cursor.rewind() 19 | for review in self.cursor: 20 | yield self.reviews_dictionary.doc2bow(review["words"]) 21 | 22 | def serialize(self): 23 | BleiCorpus.serialize(self.corpus_path, self, id2word=self.reviews_dictionary) 24 | 25 | return self 26 | 27 | 28 | class Dictionary(object): 29 | def __init__(self, cursor, dictionary_path): 30 | self.cursor = cursor 31 | self.dictionary_path = dictionary_path 32 | 33 | def build(self): 34 | self.cursor.rewind() 35 | dictionary = corpora.Dictionary(review["words"] for review in self.cursor) 36 | dictionary.filter_extremes(keep_n=10000) 37 | dictionary.compactify() 38 | corpora.Dictionary.save(dictionary, self.dictionary_path) 39 | 40 | return dictionary 41 | 42 | 43 | class Train: 44 | def __init__(self): 45 | pass 46 | 47 | @staticmethod 48 | def run(lda_model_path, corpus_path, num_topics, id2word): 49 | corpus = corpora.BleiCorpus(corpus_path) 50 | lda = gensim.models.LdaModel(corpus, num_topics=num_topics, id2word=id2word) 51 | lda.save(lda_model_path) 52 | 53 | return lda 54 | 55 | 56 | def main(): 57 | logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) 58 | 59 | dictionary_path = "models/dictionary.dict" 60 | corpus_path = "models/corpus.lda-c" 61 | lda_num_topics = 50 62 | lda_model_path = "models/lda_model_50_topics.lda" 63 | 64 | corpus_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.TAGS_DATABASE][ 65 | Settings.CORPUS_COLLECTION] 66 | reviews_cursor = corpus_collection.find() 67 | 68 | dictionary = Dictionary(reviews_cursor, dictionary_path).build() 69 | Corpus(reviews_cursor, dictionary, corpus_path).serialize() 70 | Train.run(lda_model_path, corpus_path, lda_num_topics, dictionary) 71 | 72 | 73 | if __name__ == '__main__': 74 | main() 75 | -------------------------------------------------------------------------------- /yelp/yelp-reviews.py: -------------------------------------------------------------------------------- 1 | import os 2 | import time 3 | import json 4 | 5 | from pymongo import MongoClient 6 | 7 | from settings import Settings 8 | 9 | 10 | dataset_file = Settings.DATASET_FILE 11 | reviews_collection = MongoClient(Settings.MONGO_CONNECTION_STRING)[Settings.REVIEWS_DATABASE][ 12 | Settings.REVIEWS_COLLECTION] 13 | 14 | count = 0 15 | done = 0 16 | start = time.time() 17 | 18 | with open(dataset_file) as dataset: 19 | count = sum(1 for line in dataset) 20 | 21 | with open(dataset_file) as dataset: 22 | next(dataset) 23 | for line in dataset: 24 | try: 25 | data = json.loads(line) 26 | except ValueError: 27 | print 'Oops!' 28 | if data["type"] == "review": 29 | reviews_collection.insert({ 30 | "reviewId": data["review_id"], 31 | "business": data["business_id"], 32 | "text": data["text"] 33 | }) 34 | 35 | done += 1 36 | if done % 100 == 0: 37 | end = time.time() 38 | os.system('cls') 39 | print 'Done ' + str(done) + ' out of ' + str(count) + ' in ' + str((end - start)) 40 | --------------------------------------------------------------------------------