├── .gitignore ├── LICENSE ├── README.md ├── docs ├── babi-lstm.dia ├── babi-lstm.png ├── babi-memnn.dia ├── babi-memnn.png ├── babi-task1-format.dia ├── babi-task1-format.png ├── deploy.dia ├── deploy.png ├── dlqa-workshop-2016.pptx ├── flashcard-format.dia ├── flashcard-format.png ├── kaggle-format.dia ├── kaggle-format.png ├── qa-lstm-attn.dia ├── qa-lstm-attn.png ├── qa-lstm-cnn.dia ├── qa-lstm-cnn.png ├── qa-lstm-fem-attn-rex.png ├── qa-lstm-story.dia ├── qa-lstm-story.png ├── qa-lstm.dia ├── qa-lstm.png ├── qa-pipeline-1.dia ├── qa-pipeline-1.png ├── qa-pipeline.dia ├── qa-pipeline.png ├── storyfinder.dia └── storyfinder.png └── src ├── add-story.py ├── babi-dmn.py ├── babi-lstm.py ├── babi-memnn.py ├── babi.py ├── deploy-model.py ├── es-load-flashcards.py ├── flashcards-embedding.py ├── kaggle.py ├── predict-testfile.py ├── qa-blstm-attn.py ├── qa-blstm-fem-attn.py ├── qa-blstm-story.py ├── qa-blstm.py ├── qa-dense-autoencoder.py ├── qa-lstm-attn.py ├── qa-lstm-autoencoder.py ├── qa-lstm-cnn.py ├── qa-lstm-fem-attn.py ├── qa-lstm-fem.py ├── qa-lstm-story.py └── qa-lstm.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | *.pyc 3 | data/* 4 | -------------------------------------------------------------------------------- /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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dl-models-for-qa 2 | 3 | ⚠ __WARNING:__ As pointed out recently by a colleague, the 75% accuracies achieved by the QA models described in this project could have been achieved by a classifier that learns to always return false (since 3 of 4 of the training set consists of false answers). He took the evaluation one step further and compared the softmax probabilities associated with each of the 4 possible answers against the correct answer, and achieved accuracies around 25%, once again indicative of a model that is only as good as random (1 in 4 answers are correct). 4 | 5 | ## Table of Contents 6 | 7 | * [Introduction](#introduction) 8 | * [Models](#models) 9 | * [Models using bAbI dataset](#models-using-babi-dataset) 10 | * [BABI-LSTM](#babi-lstm) 11 | * [BABI-MEMNN](#babi-memnn) 12 | * [Models using Kaggle dataset](#models-using-kaggle-dataset) 13 | * [QA-LSTM](#qa-lstm) 14 | * [QA-LSTM CNN](#qa-lstm-cnn) 15 | * [QA-LSTM with Attention](#qa-lstm-with-attention) 16 | * [Incorporating External Knowledge](#incorporating-external-knowledge) 17 | * [QA-LSTM with Attention and Custom Embedding](#qa-lstm-with-attention-and-custom-embedding) 18 | * [QA-LSTM with Story](#qa-lstm-with-story) 19 | * [Data](#data) 20 | * [Results](#results) 21 | * [Model deployment](#model-deployment) 22 | 23 | ## Introduction 24 | 25 | This repository contains Python code to train and deploy Deep Learning (DL) models for Question Answering (QA). The code accompanies a talk I gave at the Question Answering Workshop organized by the Elsevier Search Guild. 26 | 27 | You can find the [slides for this talk](http://www.slideshare.net/sujitpal/deep-learning-models-for-question-answering) on Slideshare. 28 | 29 | Code is in Python. All the models are built using the awesome [Keras](https://keras.io/) library. Supporting code also uses [gensim](https://radimrehurek.com/gensim/), [NLTK](http://www.nltk.org/) and [Spacy](https://spacy.io/). 30 | 31 | Objective of the code was to build DL model(s) to answer 8th grade multiple-choice science questions, provided as part of this [AllenAI competition on Kaggle](Thttps://www.kaggle.com/c/the-allen-ai-science-challenge). 32 | 33 | ## Models 34 | 35 | Much of the inspiration for the DL implementations in this project came from the [solution posted](https://github.com/tambetm/allenAI) by the 4th place winner of the competition, who used DL models along with traditional Information Retrieval (IR) models. 36 | 37 | ### Models using bAbI dataset 38 | 39 | In order to gain some intuition about how to use DL for QA, I looked at two examples from the Keras examples, that use the single supporting fact (task #1) from the [bAbI dataset](https://research.facebook.com/research/babi/) created by Facebook. These two models are described below: 40 | 41 | The bAbI dataset can be thought of as (story, question, answer) triples. In case of task #1, the answer is always a single word. Figure below illustrates the data format for task #1. 42 | 43 | 44 | 45 | Both models attempt to predict the answer as the most probable word from the entire vocabulary. 46 | 47 | ### BABI-LSTM 48 | 49 | Implementation based on paper [Towards AI-Complete Question Answering: A set of Prerequisite Toy Tasks](http://arxiv.org/abs/1502.05698) - Weston, et al. Adapted from similar example in Keras examples. 50 | 51 | Embedding is computed inline using story and patient. Observed accuracy (56%) is similar to that reported in paper (50%). 52 | 53 | 54 | 55 | ### BABI-MEMNN 56 | 57 | Implementation based on paper [End to End Memory Networks](http://arxiv.org/abs/1503.08895) - Sukhbaatar, Szlam, Weston and Fergus. Adapted from similar example in Keras examples. 58 | 59 | Accuracy achieved by implementation (on 1k triples) is around 42% compared to 99% reported in paper. 60 | 61 | 62 | 63 | ### Models using Kaggle dataset 64 | 65 | From this point on, all our models use the competition dataset. A training set record is composed of (question, answer\_A, answer\_B, answer\_C, answer\_D, correct\_answer) tuples. Objective is to predict the index of the correct answer. 66 | 67 | 68 | 69 | We can thus think of this as a classification problem, where we have 1 positive example and 3 negative examples for each training record. 70 | 71 | ### QA-LSTM 72 | 73 | Implementation based on paper [LSTM-based Deep Learning Models for Non-factoid Answer Selection](https://arxiv.org/abs/1511.04108) - Tan, dos Santos, Xiang and Zhou. 74 | 75 | Unlike bABi models, embedding uses pre-trained Google News Word2Vec model to convert story and question input vector (1 hot sparse representation) into dense representation of size (300,). 76 | 77 | Accuracy numbers from implementation are 56.93% with unidirectional LSTMs and 57% with bidirectional LSTMs. 78 | 79 | 80 | 81 | ### QA-LSTM CNN 82 | 83 | Same as qa-lstm, but with an additional 1D Convolution/MaxPool layer to further extract the meaning of the question and answer. 84 | 85 | Produces slightly worse accuracy numbers than QA-LSTM model - 55.7% with unidirectional LSTMs, did not try with bidirectional LSTMs. 86 | 87 | 88 | 89 | ### QA-LSTM with Attention 90 | 91 | Problem with RNNs in general is the vanishing gradient problem. While LSTMs address the problem, they still suffer from it because of the very long distances involved in QA contexts. The solution to this is attention, where the network is forced to look at certain parts of the context and ignore (in a relative sense) everything else. 92 | 93 | 94 | 95 | ### Incorporating External Knowledge 96 | 97 | Based on the competition message boards, there seems to be general consensus that external content is okay to use. Here are some mentioned: 98 | 99 | * [ConceptNet](http://conceptnet5.media.mit.edu/) 100 | * [CK-12 books](http://www.ck12.org/student/) 101 | * [Quizlets](https://quizlet.com/) 102 | * [Studystack Flashcards](http://www.studystack.com/) 103 | 104 | Most of the contents mentioned involve quite a lot of effort to scrape/crawl the sites and parse the crawled content. There was one content source (Flashcards from StudyStack) that was [available here](https://drive.google.com/file/d/0B0fFJSGDUPcgUFJpTVl3QXhnNTQ/view?usp=sharing) in pre-parsed form, so I used that. This gave me 400k flashcard records, questions followed by the correct answer. I thought of this as the "story" from the bAbI context. 105 | 106 | 107 | 108 | ### QA-LSTM with Attention and Custom Embedding 109 | 110 | My first attempt at incorporating the story was to replace the embedding from the pre-trained Word2Vec model with a Word2Vec model generated using the Flashcard data. This created a smaller, more compact embedding and gave me quite a good boost in accuracy. 111 | 112 | | Model | Default Embedding | Story Embedding | 113 | | -----------------------------------| ----------------- | --------------- | 114 | | QA-LSTM w/Attention | 62.93% | 76.27% | 115 | | QA-LSTM bidirectional w/Attention | 60.43% | 76.27% | 116 | 117 | The qa-lstm-fem-attn model(s) are identical to the qa-lstm-attn model(s) except for the embedding used - instead of the default embedding from Word2Vec, I am now using a custom embedding from the flashcard data. 118 | 119 | ### QA-LSTM with Story 120 | 121 | My second attempt at incorporating the story data was to try to create (story, question, answer) triples similar to the bAbI models. The first step is to load the flashcards into an Elasticsearch (ES) index, one flashcard per record. For each question, the nouns and verbs are filtered and an OR query constructed and sent to ES. The top 10 flashcards retrieved for each question become the story for that triple. 122 | 123 | 124 | 125 | 126 | Once I have the "story" associated with our (question, answer) pairs, I construct a network as shown below. This model did not perform as well as the QA-LSTM with Attention models, accuracy was 70.47% with unidirectional LSTMs and 61.77% with bidirectional LSTMs. 127 | 128 | 129 | 130 | 131 | ## Results 132 | 133 | Results from the various QA-LSTM variants against the Kaggle dataset is summarized below. 134 | 135 | | Model Specifications | Test Acc. (%) | 136 | | ---------------------------------------------------- | ------------- | 137 | | QA-LSTM (Baseline) | 56.93 | 138 | | QA-LSTM Bidirectional | 57.0 | 139 | | QA-LSTM + CNN | 55.7 | 140 | | QA-LSTM with Attention | 62.93 | 141 | | QA-LSTM Bidirectional with Attention | 60.43 | 142 | | QA-LSTM with Attention + Custom Embedding | 76.27 | 143 | | QA-LSTM Bidirectional w/Attention + Custom Embedding | 76.27 | 144 | | QA-LSTM + Attention + Story Facts | 70.47 | 145 | | QA-LSTM Bidirectional + Attention + Story Facts | 61.77 | 146 | 147 | ## Data 148 | 149 | Data is not included in this project. However, most of the data is available on the Internet, I have included links to the data where applicable. The code expects the following directory structure. 150 | 151 | PROJECT_HOME 152 | | 153 | +---- data 154 | | | 155 | | +---- babi_data 156 | | | 157 | | +---- comp_data 158 | | | 159 | | +---- models 160 | 161 | 162 | The bAbI dataset is available from [this URL]. Download it and expand the tarball under the babi\_data directory. 163 | 164 | My code uses the **original dataset** provided along with the competition, which is no longer available (and cannot be distributed). However, AllenAI provides an [alternative dataset](http://allenai.org/data.html) which can be used instead. These files need to be copied into the comp\_data subdirectory. Note that the format of the new data is slightly different, but fortunately well documented, so you will have to adapt the parsing logic in kaggle.py. Look for the following verbiage to find the correct dataset to download. 165 | 166 | > AI2 8th Grade Science Questions (No Diagrams) 167 | > 168 | > 641 questions February 2016 These question sets are derived from a variety of regional and state science exams. 169 | > 170 | > These science exam questions guide our research into multiple choice question answering at the elementary science level. This download contains 8th grade-level multiple choice questions that do not incorporate diagrams. 171 | 172 | The comp\_data directory should also contain the [GoogleNews Word2Vec model](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing), which is needed to load the default word vectors. In addition, the [StudyStack Flashcards](https://drive.google.com/file/d/0B0fFJSGDUPcgUFJpTVl3QXhnNTQ/view?usp=sharing) should also be downloaded and exploded in the same directory. 173 | 174 | The models directory is used to hold the models that are written out by the different models when they run. The deploy code uses these models to make predictions. Models are not checked into github because of space considerations. 175 | 176 | ## Model deployment 177 | 178 | For deployment, we run each question + answer pair and consider the difference between the positive and negative outputs as the "score". The score is then normalized to sum to 1 and the one with the highest score selected as the winning choice. 179 | 180 | As an example, the following image shows the actual predictions for a question and answer from our dataset. The chart shows the probability of each choice according to our strongest model. 181 | 182 | 183 | 184 | -------------------------------------------------------------------------------- /docs/babi-lstm.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-lstm.dia -------------------------------------------------------------------------------- /docs/babi-lstm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-lstm.png -------------------------------------------------------------------------------- /docs/babi-memnn.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-memnn.dia -------------------------------------------------------------------------------- /docs/babi-memnn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-memnn.png -------------------------------------------------------------------------------- /docs/babi-task1-format.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-task1-format.dia -------------------------------------------------------------------------------- /docs/babi-task1-format.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/babi-task1-format.png -------------------------------------------------------------------------------- /docs/deploy.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/deploy.dia -------------------------------------------------------------------------------- /docs/deploy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/deploy.png -------------------------------------------------------------------------------- /docs/dlqa-workshop-2016.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/dlqa-workshop-2016.pptx -------------------------------------------------------------------------------- /docs/flashcard-format.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/flashcard-format.dia -------------------------------------------------------------------------------- /docs/flashcard-format.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/flashcard-format.png -------------------------------------------------------------------------------- /docs/kaggle-format.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/kaggle-format.dia -------------------------------------------------------------------------------- /docs/kaggle-format.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/kaggle-format.png -------------------------------------------------------------------------------- /docs/qa-lstm-attn.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-attn.dia -------------------------------------------------------------------------------- /docs/qa-lstm-attn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-attn.png -------------------------------------------------------------------------------- /docs/qa-lstm-cnn.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-cnn.dia -------------------------------------------------------------------------------- /docs/qa-lstm-cnn.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-cnn.png -------------------------------------------------------------------------------- /docs/qa-lstm-fem-attn-rex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-fem-attn-rex.png -------------------------------------------------------------------------------- /docs/qa-lstm-story.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-story.dia -------------------------------------------------------------------------------- /docs/qa-lstm-story.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm-story.png -------------------------------------------------------------------------------- /docs/qa-lstm.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm.dia -------------------------------------------------------------------------------- /docs/qa-lstm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-lstm.png -------------------------------------------------------------------------------- /docs/qa-pipeline-1.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-pipeline-1.dia -------------------------------------------------------------------------------- /docs/qa-pipeline-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-pipeline-1.png -------------------------------------------------------------------------------- /docs/qa-pipeline.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-pipeline.dia -------------------------------------------------------------------------------- /docs/qa-pipeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/qa-pipeline.png -------------------------------------------------------------------------------- /docs/storyfinder.dia: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/storyfinder.dia -------------------------------------------------------------------------------- /docs/storyfinder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sujitpal/dl-models-for-qa/cc9ec2af44d3e261cc865988d9828de165ec47e4/docs/storyfinder.png -------------------------------------------------------------------------------- /src/add-story.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | import elasticsearch 4 | import os 5 | import re 6 | import spacy.en 7 | 8 | DATA_DIR = "../data/comp_data" 9 | QA_TRAIN_INPUT = "8thGr-NDMC-Train.csv" 10 | 11 | ES_HOST = "localhost" 12 | ES_PORT = 9200 13 | ES_INDEXNAME = "flashcards-idx" 14 | ES_DOCTYPE = "stories" 15 | 16 | SQA_TRAIN_OUTPUT = "SQA-Train.csv" 17 | 18 | class StoryFinder(object): 19 | 20 | def __init__(self, host, port, index, doc_type): 21 | self.esconn = elasticsearch.Elasticsearch(hosts = [{ 22 | "host": host, "port": str(port) 23 | }]) 24 | self.nlp = spacy.en.English() 25 | self.posbag = {"NOUN", "PROPN", "VERB"} 26 | self.index = index 27 | self.doc_type = doc_type 28 | 29 | def find_stories_for_question(self, question, num_stories=10): 30 | # extract tokens from question to search with (NOUN, VERB, PROPN) 31 | question = re.sub(r"[^A-Za-z0-9 ]", "", question) 32 | tokens = self.nlp(unicode(question)) 33 | qwords = [] 34 | for token in tokens: 35 | if token.pos_ in self.posbag: 36 | qwords.append(token.string) 37 | # compose an OR query with all words and get num_stories results 38 | query_header = """ 39 | { 40 | "query": { 41 | "bool": { 42 | "should": [ 43 | """ 44 | qbody = [] 45 | for qword in qwords: 46 | qbody.append(""" 47 | { 48 | "term": { 49 | "story": "%s" 50 | } 51 | }""" % (qword.strip().lower())) 52 | query_footer = """ 53 | ] 54 | } 55 | } 56 | } 57 | """ 58 | query = query_header + ",".join(qbody) + query_footer 59 | resp = self.esconn.search(index=self.index, doc_type=self.doc_type, 60 | body=query) 61 | hits = resp["hits"]["hits"] 62 | stories = [] 63 | for hit in hits: 64 | stories.append(hit["_source"]["story"].encode("ascii", "ignore")) 65 | 66 | stories2 = [] 67 | for story in stories: 68 | stories2.append(story.decode('utf-8','ignore')) 69 | 70 | return stories2 71 | 72 | 73 | 74 | ###### main #### 75 | 76 | storyfinder = StoryFinder(ES_HOST, ES_PORT, ES_INDEXNAME, ES_DOCTYPE) 77 | 78 | fqa = open(os.path.join(DATA_DIR, QA_TRAIN_INPUT), "rb") 79 | fsqa = open(os.path.join(DATA_DIR, SQA_TRAIN_OUTPUT), "wb") 80 | 81 | nbr_lines = 1 82 | for line in fqa: 83 | if line.startswith("#"): 84 | continue 85 | if nbr_lines % 100 == 0: 86 | print("Processed %d lines of input..." % (nbr_lines)) 87 | line = line.strip() 88 | qid, question, correct_ans, ans_a, ans_b, ans_c, ans_d = \ 89 | line.split("\t") 90 | story = " ".join(storyfinder.find_stories_for_question(question)) 91 | correct_ans_idx = ord(correct_ans) - ord('A') 92 | answers = [ans_a, ans_b, ans_c, ans_d] 93 | for idx, answer in enumerate(answers): 94 | fsqa.write("%s\t%s\t%s\t%d\n" % (story, question, answer, 95 | 1 if idx == correct_ans_idx else 0)) 96 | nbr_lines += 1 97 | 98 | print("Processed %d lines of input...complete" % (nbr_lines)) 99 | fsqa.close() 100 | fqa.close() 101 | -------------------------------------------------------------------------------- /src/babi-dmn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Ask me Anything: Dynamic Memory Networks for Natural Language Processing 3 | # (http://arxiv.org/abs/1506.07285) 4 | from __future__ import division, print_function 5 | 6 | from keras.layers import Dense, Merge, Dropout, Permute, Activation 7 | from keras.layers.embeddings import Embedding 8 | from keras.layers.recurrent import LSTM 9 | from keras.models import Sequential 10 | 11 | import os 12 | 13 | import babi 14 | 15 | BABI_DIR = "../data/babi_data/tasks_1-20_v1-2/en" 16 | TASK_NBR = 1 17 | EMBED_HIDDEN_SIZE = 64 18 | LSTM_OUTPUT_SIZE = 32 19 | BATCH_SIZE = 32 20 | NBR_EPOCHS = 120 21 | 22 | train_file, test_file = babi.get_files_for_task(TASK_NBR, BABI_DIR) 23 | 24 | data_train = babi.get_stories(os.path.join(BABI_DIR, train_file)) 25 | data_test = babi.get_stories(os.path.join(BABI_DIR, test_file)) 26 | 27 | word2idx = babi.build_vocab([data_train, data_test]) 28 | vocab_size = len(word2idx) + 1 29 | print("vocab_size=", vocab_size) 30 | 31 | story_maxlen, question_maxlen = babi.get_maxlens([data_train, data_test]) 32 | print("story_maxlen=", story_maxlen, "question_maxlen=", question_maxlen) 33 | 34 | Xs_train, Xq_train, Y_train = babi.vectorize(data_train, word2idx, 35 | story_maxlen, question_maxlen) 36 | Xs_test, Xq_test, Y_test = babi.vectorize(data_test, word2idx, 37 | story_maxlen, question_maxlen) 38 | print(Xs_train.shape, Xq_train.shape, Y_train.shape) 39 | print(Xs_test.shape, Xq_test.shape, Y_test.shape) 40 | 41 | # story encoder. Output dim: (None, story_maxlen, EMBED_HIDDEN_SIZE) 42 | story_encoder = Sequential() 43 | story_encoder.add(Embedding(input_dim=vocab_size, 44 | output_dim=EMBED_HIDDEN_SIZE, 45 | input_length=story_maxlen)) 46 | story_encoder.add(Dropout(0.3)) 47 | 48 | # question encoder. Output dim: (None, question_maxlen, EMBED_HIDDEN_SIZE) 49 | question_encoder = Sequential() 50 | question_encoder.add(Embedding(input_dim=vocab_size, 51 | output_dim=EMBED_HIDDEN_SIZE, 52 | input_length=question_maxlen)) 53 | question_encoder.add(Dropout(0.3)) 54 | 55 | # episodic memory (facts): story * question 56 | # Output dim: (None, question_maxlen, story_maxlen) 57 | facts_encoder = Sequential() 58 | facts_encoder.add(Merge([story_encoder, question_encoder], 59 | mode="dot", dot_axes=[2, 2])) 60 | facts_encoder.add(Permute((2, 1))) 61 | 62 | ## combine response and question vectors and do logistic regression 63 | answer = Sequential() 64 | answer.add(Merge([facts_encoder, question_encoder], 65 | mode="concat", concat_axis=-1)) 66 | answer.add(LSTM(LSTM_OUTPUT_SIZE)) 67 | answer.add(Dropout(0.3)) 68 | answer.add(Dense(vocab_size)) 69 | answer.add(Activation("softmax")) 70 | 71 | answer.compile(optimizer="rmsprop", loss="categorical_crossentropy", 72 | metrics=["accuracy"]) 73 | 74 | answer.fit([Xs_train, Xq_train], Y_train, 75 | batch_size=BATCH_SIZE, nb_epoch=NBR_EPOCHS, 76 | validation_data=([Xs_test, Xq_test], Y_test)) 77 | -------------------------------------------------------------------------------- /src/babi-lstm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.layers import Dense, Merge, Dropout, RepeatVector 4 | from keras.layers.embeddings import Embedding 5 | from keras.layers.recurrent import LSTM 6 | from keras.models import Sequential 7 | import os 8 | 9 | import babi 10 | 11 | BABI_DIR = "../data/babi_data/tasks_1-20_v1-2/en" 12 | TASK_NBR = 1 13 | EMBED_HIDDEN_SIZE = 50 14 | BATCH_SIZE = 32 15 | NBR_EPOCHS = 40 16 | 17 | train_file, test_file = babi.get_files_for_task(TASK_NBR, BABI_DIR) 18 | 19 | data_train = babi.get_stories(os.path.join(BABI_DIR, train_file)) 20 | data_test = babi.get_stories(os.path.join(BABI_DIR, test_file)) 21 | 22 | word2idx = babi.build_vocab([data_train, data_test]) 23 | vocab_size = len(word2idx) + 1 24 | print("vocab_size=", vocab_size) 25 | 26 | story_maxlen, question_maxlen = babi.get_maxlens([data_train, data_test]) 27 | print("story_maxlen=", story_maxlen) 28 | print("question_maxlen=", question_maxlen) 29 | 30 | Xs_train, Xq_train, Y_train = babi.vectorize(data_train, word2idx, 31 | story_maxlen, question_maxlen) 32 | Xs_test, Xq_test, Y_test = babi.vectorize(data_test, word2idx, 33 | story_maxlen, question_maxlen) 34 | print(Xs_train.shape, Xq_train.shape, Y_train.shape) 35 | print(Xs_test.shape, Xq_test.shape, Y_test.shape) 36 | 37 | # define model 38 | # generate embeddings for stories 39 | story_rnn = Sequential() 40 | story_rnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE, 41 | input_length=story_maxlen)) 42 | story_rnn.add(Dropout(0.3)) 43 | 44 | # generate embeddings for question and make adaptable to story 45 | question_rnn = Sequential() 46 | question_rnn.add(Embedding(vocab_size, EMBED_HIDDEN_SIZE, 47 | input_length=question_maxlen)) 48 | question_rnn.add(Dropout(0.3)) 49 | question_rnn.add(LSTM(EMBED_HIDDEN_SIZE, return_sequences=False)) 50 | question_rnn.add(RepeatVector(story_maxlen)) 51 | 52 | # merge the two 53 | model = Sequential() 54 | model.add(Merge([story_rnn, question_rnn], mode="sum")) 55 | model.add(LSTM(EMBED_HIDDEN_SIZE, return_sequences=False)) 56 | model.add(Dropout(0.3)) 57 | model.add(Dense(vocab_size, activation="softmax")) 58 | 59 | model.compile(optimizer="adam", loss="categorical_crossentropy", 60 | metrics=["accuracy"]) 61 | 62 | print("Training...") 63 | model.fit([Xs_train, Xq_train], Y_train, 64 | batch_size=BATCH_SIZE, nb_epoch=NBR_EPOCHS, validation_split=0.05) 65 | loss, acc = model.evaluate([Xs_test, Xq_test], Y_test, batch_size=BATCH_SIZE) 66 | print() 67 | print("Test loss/accuracy = {:.4f}, {:.4f}".format(loss, acc)) 68 | -------------------------------------------------------------------------------- /src/babi-memnn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # End-to-end Memory Networks (http://arxiv.org/abs/1503.08895) 3 | # 4 | from __future__ import division, print_function 5 | from keras.layers import Dense, Merge, Dropout, Permute, Activation 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.models import Sequential 9 | 10 | import os 11 | 12 | import babi 13 | 14 | 15 | BABI_DIR = "../data/babi_data/tasks_1-20_v1-2/en" 16 | TASK_NBR = 1 17 | EMBED_HIDDEN_SIZE = 64 18 | LSTM_OUTPUT_SIZE = 32 19 | BATCH_SIZE = 32 20 | NBR_EPOCHS = 120 21 | 22 | train_file, test_file = babi.get_files_for_task(TASK_NBR, BABI_DIR) 23 | 24 | data_train = babi.get_stories(os.path.join(BABI_DIR, train_file)) 25 | data_test = babi.get_stories(os.path.join(BABI_DIR, test_file)) 26 | 27 | word2idx = babi.build_vocab([data_train, data_test]) 28 | vocab_size = len(word2idx) + 1 29 | print("vocab_size=", vocab_size) 30 | 31 | story_maxlen, question_maxlen = babi.get_maxlens([data_train, data_test]) 32 | print("story_maxlen=", story_maxlen, "question_maxlen=", question_maxlen) 33 | 34 | Xs_train, Xq_train, Y_train = babi.vectorize(data_train, word2idx, 35 | story_maxlen, question_maxlen) 36 | Xs_test, Xq_test, Y_test = babi.vectorize(data_test, word2idx, 37 | story_maxlen, question_maxlen) 38 | print(Xs_train.shape, Xq_train.shape, Y_train.shape) 39 | print(Xs_test.shape, Xq_test.shape, Y_test.shape) 40 | 41 | # story encoder memory. Output dim: (None, story_maxlen, EMBED_HIDDEN_SIZE) 42 | story_encoder_m = Sequential() 43 | story_encoder_m.add(Embedding(input_dim=vocab_size, 44 | output_dim=EMBED_HIDDEN_SIZE, 45 | input_length=story_maxlen)) 46 | story_encoder_m.add(Dropout(0.3)) 47 | 48 | # question encoder. Output dim: (None, query_maxlen, EMBED_HIDDEN_SIZE) 49 | question_encoder = Sequential() 50 | question_encoder.add(Embedding(input_dim=vocab_size, 51 | output_dim=EMBED_HIDDEN_SIZE, 52 | input_length=question_maxlen)) 53 | question_encoder.add(Dropout(0.3)) 54 | 55 | # compute match between story and question. 56 | # Output dim: (None, story_maxlen, question_maxlen) 57 | match = Sequential() 58 | match.add(Merge([story_encoder_m, question_encoder], 59 | mode="dot", dot_axes=[2, 2])) 60 | 61 | # encode story into vector space of question 62 | # output dim: (None, story_maxlen, query_maxlen) 63 | story_encoder_c = Sequential() 64 | story_encoder_c.add(Embedding(input_dim=vocab_size, 65 | output_dim=question_maxlen, 66 | input_length=story_maxlen)) 67 | story_encoder_c.add(Dropout(0.3)) 68 | 69 | # combine match and story vectors. 70 | # Output dim: (None, query_maxlen, story_maxlen) 71 | response = Sequential() 72 | response.add(Merge([match, story_encoder_c], mode="sum")) 73 | response.add(Permute((2, 1))) 74 | 75 | ## combine response and question vectors and do logistic regression 76 | answer = Sequential() 77 | answer.add(Merge([response, question_encoder], mode="concat", concat_axis=-1)) 78 | answer.add(LSTM(LSTM_OUTPUT_SIZE)) 79 | answer.add(Dropout(0.3)) 80 | answer.add(Dense(vocab_size)) 81 | answer.add(Activation("softmax")) 82 | 83 | answer.compile(optimizer="rmsprop", loss="categorical_crossentropy", 84 | metrics=["accuracy"]) 85 | 86 | answer.fit([Xs_train, Xq_train, Xs_train], Y_train, 87 | batch_size=BATCH_SIZE, nb_epoch=NBR_EPOCHS, 88 | validation_data=([Xs_test, Xq_test, Xs_test], Y_test)) 89 | 90 | -------------------------------------------------------------------------------- /src/babi.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.preprocessing.sequence import pad_sequences 4 | import collections 5 | import re 6 | import nltk 7 | import numpy as np 8 | import os 9 | 10 | def get_files_for_task(task_nbr, babi_dir): 11 | filenames = os.listdir(babi_dir) 12 | task_files = filter(lambda x: re.search("qa%d_" % (task_nbr), x), filenames) 13 | assert(len(task_files) == 2) 14 | train_file = filter(lambda x: re.search("_train.txt", x), task_files)[0] 15 | test_file = filter(lambda x: re.search("_test.txt", x), task_files)[0] 16 | return train_file, test_file 17 | 18 | def get_stories(taskfile, only_support=False): 19 | data = [] 20 | story_sents = [] 21 | ftask = open(taskfile, "rb") 22 | for line in ftask: 23 | line = line.strip() 24 | nid, line = line.split(" ", 1) 25 | if int(nid) == 1: 26 | # new story 27 | story_sents = [] 28 | if "\t" in line: 29 | # capture question, answer and support 30 | q, a, support = line.split("\t") 31 | q = nltk.word_tokenize(q) 32 | if only_support: 33 | # only select supporting sentences 34 | support_idxs = [int(x)-1 for x in support.split(" ")] 35 | story_so_far = [] 36 | for support_idx in support_idxs: 37 | story_so_far.append(story_sents[support_idx]) 38 | else: 39 | story_so_far = [x for x in story_sents] 40 | story = reduce(lambda a, b: a + b, story_so_far) 41 | data.append((story, q, a)) 42 | else: 43 | # only capture story 44 | story_sents.append(nltk.word_tokenize(line)) 45 | ftask.close() 46 | return data 47 | 48 | def build_vocab(daten): 49 | counter = collections.Counter() 50 | for data in daten: 51 | for story, question, answer in data: 52 | for w in story: 53 | counter[w] += 1 54 | for w in question: 55 | counter[w] += 1 56 | for w in [answer]: 57 | counter[w] += 1 58 | # don't throw away anything because we don't have many words 59 | # in the synthetic dataset. 60 | # also we want to reserve 0 for pad character, so we offset the 61 | # indexes by 1. 62 | words = [wordcount[0] for wordcount in counter.most_common()] 63 | word2idx = {w: i+1 for i, w in enumerate(words)} 64 | return word2idx 65 | 66 | def get_maxlens(daten): 67 | """ Return the max number of words in story and question """ 68 | data_comb = [] 69 | for data in daten: 70 | data_comb.extend(data) 71 | story_maxlen = max([len(x) for x, _, _ in data_comb]) 72 | question_maxlen = max([len(x) for _, x, _ in data_comb]) 73 | return story_maxlen, question_maxlen 74 | 75 | def vectorize(data, word2idx, story_maxlen, question_maxlen): 76 | """ Create the story and question vectors and the label """ 77 | Xs, Xq, Y = [], [], [] 78 | for story, question, answer in data: 79 | xs = [word2idx[word] for word in story] 80 | xq = [word2idx[word] for word in question] 81 | y = np.zeros(len(word2idx) + 1) 82 | y[word2idx[answer]] = 1 83 | Xs.append(xs) 84 | Xq.append(xq) 85 | Y.append(y) 86 | return (pad_sequences(Xs, maxlen=story_maxlen), 87 | pad_sequences(Xq, maxlen=question_maxlen), 88 | np.array(Y)) 89 | 90 | -------------------------------------------------------------------------------- /src/deploy-model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.models import model_from_json 4 | from keras.preprocessing.sequence import pad_sequences 5 | import matplotlib.pyplot as plt 6 | import nltk 7 | import numpy as np 8 | import os 9 | 10 | import kaggle 11 | 12 | MODEL_DIR = "../data/models" 13 | #MODEL_ARCH = "qa-lstm.json" 14 | #MODEL_WEIGHTS = "qa-lstm-model-best.hdf5" 15 | MODEL_ARCH = "qa-lstm-fem-attn.json" 16 | MODEL_WEIGHTS = "qa-lstm-fem-attn-final.h5" 17 | 18 | DATA_DIR = "../data/comp_data" 19 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 20 | QA_TEST_FILE = "8thGr-NDMC-Test.csv" 21 | 22 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 23 | WORD2VEC_EMBED_SIZE = 300 24 | 25 | LSTM_SEQLEN = 196 # from original model 26 | NUM_CHOICES = 4 # number of choices for multiple choice 27 | 28 | #### Load up the vectorizer 29 | qapairs = kaggle.get_question_answer_pairs( 30 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 31 | tqapairs = kaggle.get_question_answer_pairs( 32 | os.path.join(DATA_DIR, QA_TEST_FILE), is_test=True) 33 | 34 | word2idx = kaggle.build_vocab([], qapairs, tqapairs) 35 | vocab_size = len(word2idx) + 1 # include mask character 0 36 | 37 | #### Load up the model 38 | with open(os.path.join(MODEL_DIR, MODEL_ARCH), "rb") as fjson: 39 | json = fjson.read() 40 | model = model_from_json(json) 41 | model.load_weights(os.path.join(MODEL_DIR, MODEL_WEIGHTS)) 42 | 43 | #### read in the data #### 44 | #### correct_answer = "B" 45 | question = "Which is a distinction between an epidemic and a pandemic?" 46 | answers = ["the symptoms of the disease", 47 | "the geographical area affected", 48 | "the species of organisms infected", 49 | "the season in which the disease spreads"] 50 | qwords = nltk.word_tokenize(question) 51 | awords_list = [nltk.word_tokenize(answer) for answer in answers] 52 | Xq, Xa = [], [] 53 | for idx, awords in enumerate(awords_list): 54 | Xq.append([word2idx[qword] for qword in qwords]) 55 | Xa.append([word2idx[aword] for aword in awords]) 56 | Xq = pad_sequences(Xq, maxlen=LSTM_SEQLEN) 57 | Xa = pad_sequences(Xa, maxlen=LSTM_SEQLEN) 58 | 59 | #model.compile(optimizer="adam", loss="categorical_crossentropy", 60 | # metrics=["accuracy"]) 61 | model.compile(optimizer="rmsprop", loss="mse", metrics=["accuracy"]) 62 | Y = model.predict([Xq, Xa]) 63 | 64 | # calculate the softmax 65 | probs = np.exp(1.0 - (Y[:, 1] - Y[:, 0])) 66 | probs = probs / np.sum(probs) 67 | 68 | print(probs) 69 | 70 | plt.bar(np.arange(len(probs)), probs) 71 | plt.xticks(np.arange(len(probs))+0.35, ["A", "B", "C", "D"]) 72 | plt.xlabel("choice (x)") 73 | plt.ylabel("probability p(x)") 74 | plt.show() 75 | 76 | -------------------------------------------------------------------------------- /src/es-load-flashcards.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | import elasticsearch 4 | import nltk 5 | import os 6 | 7 | DATA_DIR = "../data/comp_data" 8 | STORY_FILE = "studystack_qa_cleaner_no_qm.txt" 9 | STORY_INDEX = "flashcards-idx" 10 | 11 | es = elasticsearch.Elasticsearch(hosts=[{ 12 | "host": "localhost", 13 | "port": "9200" 14 | }]) 15 | 16 | if es.indices.exists(STORY_INDEX): 17 | print("deleting index: %s" % (STORY_INDEX)) 18 | resp = es.indices.delete(index=STORY_INDEX) 19 | print(resp) 20 | 21 | body = { 22 | "settings": { 23 | "number_of_shards": 5, 24 | "number_of_replicas": 0 25 | } 26 | } 27 | print("creating index: %s" % (STORY_INDEX)) 28 | resp = es.indices.create(index=STORY_INDEX, body=body) 29 | print(resp) 30 | 31 | fstory = open(os.path.join(DATA_DIR, STORY_FILE), "rb") 32 | lno = 1 33 | for line in fstory: 34 | if lno % 1000 == 0: 35 | print("# stories read: %d" % (lno)) 36 | line = line.strip() 37 | line = line.decode("utf8").encode("ascii", "ignore") 38 | fcid, sent, ans = line.split("\t") 39 | story = " ".join(nltk.word_tokenize(" ".join([sent, ans]))) 40 | doc = { "story": story } 41 | resp = es.index(index=STORY_INDEX, doc_type="stories", id=lno, body=doc) 42 | # print(resp["created"]) 43 | lno += 1 44 | print("# stories read and indexed: %d" % (lno)) 45 | fstory.close() 46 | es.indices.refresh(index=STORY_INDEX) 47 | 48 | query = """ { "query": { "match_all": {} } }""" 49 | resp = es.search(index=STORY_INDEX, doc_type="stories", body=query) 50 | print("# of records in index: %d" % (resp["hits"]["total"])) -------------------------------------------------------------------------------- /src/flashcards-embedding.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models.word2vec import Word2Vec, LineSentence 4 | import logging 5 | import multiprocessing 6 | import nltk 7 | import os 8 | 9 | DATA_DIR = "../data/comp_data" 10 | FLASHCARD_SENTS = "studystack_qa_cleaner_no_qm.txt" 11 | FLASHCARD_MODEL = "studystack.bin" 12 | EMBED_SIZE = 300 # so we can reuse code using word2vec embeddings 13 | 14 | logger = logging.getLogger("flashcards-embedding") 15 | logging.basicConfig(format="%(asctime)s : %(levelname)s : %(message)s") 16 | logging.root.setLevel(level=logging.DEBUG) 17 | 18 | class FlashcardSentences(object): 19 | def __init__(self, filename): 20 | self.filename = filename 21 | 22 | def __iter__(self): 23 | for line in open(self.filename, "rb"): 24 | line = line.strip() 25 | line = line.decode("utf8").encode("ascii", "ignore") 26 | _, question, answer = line.split("\t") 27 | qwords = nltk.word_tokenize(question) 28 | awords = nltk.word_tokenize(answer) 29 | yield qwords + awords 30 | 31 | # build model from sentences (CBOW w/negative sampling) 32 | model = Word2Vec(size=EMBED_SIZE, window=5, min_count=5, 33 | workers=multiprocessing.cpu_count()) 34 | sentences = FlashcardSentences(os.path.join(DATA_DIR, FLASHCARD_SENTS)) 35 | model.build_vocab(sentences) 36 | sentences = FlashcardSentences(os.path.join(DATA_DIR, FLASHCARD_SENTS)) 37 | model.train(sentences) 38 | 39 | model.init_sims(replace=True) 40 | 41 | model.save(os.path.join(DATA_DIR, FLASHCARD_MODEL)) 42 | 43 | # test model 44 | model = Word2Vec.load(os.path.join(DATA_DIR, FLASHCARD_MODEL)) 45 | print(model.similarity("man", "woman"), model.similarity("cat", "rock")) 46 | print(model.most_similar("exercise")) -------------------------------------------------------------------------------- /src/kaggle.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.models import model_from_json 5 | from keras.preprocessing.sequence import pad_sequences 6 | import nltk 7 | import numpy as np 8 | import collections 9 | import os 10 | 11 | def get_stories(story_file, debug=False): 12 | stories = [] 13 | lno = 0 14 | fin = open(story_file, "rb") 15 | for line in fin: 16 | if debug == True and lno % 100 == 0: 17 | print("# stories read: %d" % (lno)) 18 | line = line.strip() 19 | line = line.decode("utf8").encode("ascii", "ignore") 20 | fcid, sent, ans = line.split("\t") 21 | stories.append(nltk.word_tokenize(" ".join([sent, ans]))) 22 | lno += 1 23 | fin.close() 24 | return stories 25 | 26 | def get_question_answer_pairs(question_file, is_test=False): 27 | qapairs = [] 28 | fqa = open(question_file, "rb") 29 | for line in fqa: 30 | if line.startswith("#"): 31 | continue 32 | line = line.strip().decode("utf8").encode("ascii", "ignore") 33 | cols = line.split("\t") 34 | question = cols[1] 35 | qwords = nltk.word_tokenize(question) 36 | if not is_test: 37 | correct_ans = cols[2] 38 | answers = cols[3:] 39 | # training file parsing 40 | correct_ans_idx = ord(correct_ans) - ord('A') 41 | for idx, answer in enumerate(answers): 42 | awords = nltk.word_tokenize(answer) 43 | qapairs.append((qwords, awords, idx == correct_ans_idx)) 44 | else: 45 | # test file parsing (no correct answer) 46 | answers = cols[2:] 47 | for answer in answers: 48 | awords = nltk.word_tokenize(answer) 49 | qapairs.append((qwords, awords, None)) 50 | fqa.close() 51 | return qapairs 52 | 53 | def get_story_question_answer_triples(sqa_file): 54 | sqatriples = [] 55 | fsqa = open(sqa_file, "rb") 56 | for line in fsqa: 57 | line = line.strip().decode("utf8").encode("ascii", "ignore") 58 | if line.startswith("#"): 59 | continue 60 | story, question, answer, correct = line.split("\t") 61 | swords = [] 62 | story_sents = nltk.sent_tokenize(story) 63 | for story_sent in story_sents: 64 | swords.extend(nltk.word_tokenize(story_sent)) 65 | qwords = nltk.word_tokenize(question) 66 | awords = nltk.word_tokenize(answer) 67 | is_correct = int(correct) == 1 68 | sqatriples.append((swords, qwords, awords, is_correct)) 69 | fsqa.close() 70 | return sqatriples 71 | 72 | def build_vocab(stories, qapairs, testqs): 73 | wordcounts = collections.Counter() 74 | for story in stories: 75 | for sword in story: 76 | wordcounts[sword] += 1 77 | for qapair in qapairs: 78 | for qword in qapair[0]: 79 | wordcounts[qword] += 1 80 | for aword in qapair[1]: 81 | wordcounts[aword] += 1 82 | for testq in testqs: 83 | for qword in testq[0]: 84 | wordcounts[qword] += 1 85 | for aword in testq[1]: 86 | wordcounts[aword] += 1 87 | words = [wordcount[0] for wordcount in wordcounts.most_common()] 88 | word2idx = {w: i+1 for i, w in enumerate(words)} # 0 = mask 89 | return word2idx 90 | 91 | def build_vocab_from_sqa_triples(sqatriples): 92 | wordcounts = collections.Counter() 93 | for sqatriple in sqatriples: 94 | for sword in sqatriple[0]: 95 | wordcounts[sword] += 1 96 | for qword in sqatriple[1]: 97 | wordcounts[qword] += 1 98 | for aword in sqatriple[2]: 99 | wordcounts[aword] += 1 100 | words = [wordcount[0] for wordcount in wordcounts.most_common()] 101 | word2idx = {w: i+1 for i, w in enumerate(words)} # 0 = mask 102 | return word2idx 103 | 104 | def vectorize_stories(stories, word2idx, story_maxlen): 105 | Xs = [] 106 | for story in stories: 107 | Xs.append([word2idx[word] for word in story]) 108 | return pad_sequences(Xs, maxlen=story_maxlen) 109 | 110 | def vectorize_qapairs(qapairs, word2idx, seq_maxlen): 111 | Xq, Xa, Y = [], [], [] 112 | for qapair in qapairs: 113 | Xq.append([word2idx[qword] for qword in qapair[0]]) 114 | Xa.append([word2idx[aword] for aword in qapair[1]]) 115 | Y.append(np.array([1, 0]) if qapair[2] else np.array([0, 1])) 116 | return (pad_sequences(Xq, maxlen=seq_maxlen), 117 | pad_sequences(Xa, maxlen=seq_maxlen), 118 | np.array(Y)) 119 | 120 | def vectorize_sqatriples(sqatriples, word2idx, story_maxlen, 121 | question_maxlen, answer_maxlen): 122 | Xs, Xq, Xa, Y = [], [], [], [] 123 | for sqatriple in sqatriples: 124 | Xs.append([word2idx[sword] for sword in sqatriple[0]]) 125 | Xq.append([word2idx[qword] for qword in sqatriple[1]]) 126 | Xa.append([word2idx[aword] for aword in sqatriple[2]]) 127 | Y.append(np.array([1, 0]) if sqatriple[3] else np.array([0, 1])) 128 | return (pad_sequences(Xs, maxlen=story_maxlen), 129 | pad_sequences(Xq, maxlen=question_maxlen), 130 | pad_sequences(Xa, maxlen=answer_maxlen), 131 | np.array(Y)) 132 | 133 | def get_weights_word2vec(word2idx, w2vfile, w2v_embed_size=300, 134 | is_custom=False): 135 | word2vec = None 136 | if is_custom: 137 | word2vec = Word2Vec.load(w2vfile) 138 | else: 139 | word2vec = Word2Vec.load_word2vec_format(w2vfile, binary=True) 140 | vocab_size = len(word2idx) + 1 141 | embedding_weights = np.zeros((vocab_size, w2v_embed_size)) 142 | for word, index in word2idx.items(): 143 | try: 144 | embedding_weights[index, :] = word2vec[word.lower()] 145 | except KeyError: 146 | pass # keep as zero (not ideal, but what else can we do?) 147 | return embedding_weights 148 | 149 | def get_model_filename(caller, model_type): 150 | caller = os.path.basename(caller) 151 | caller = caller[0:caller.rindex(".")] 152 | if model_type == "json": 153 | return "%s.%s" % (caller, model_type) 154 | else: 155 | return "%s-%s.h5" % (caller, model_type) 156 | 157 | def save_model(model, json_filename, weights_filename): 158 | model.save_weights(weights_filename) 159 | with open(json_filename, "wb") as fjson: 160 | fjson.write(model.to_json()) 161 | 162 | def load_model(json_filename, weights_filename): 163 | with open(json_filename, "rb") as fjson: 164 | model = model_from_json(fjson.read()) 165 | model.load_weights(filepath=weights_filename) 166 | return model 167 | 168 | 169 | ##### main #### 170 | # 171 | #import os 172 | # 173 | #DATA_DIR = "../data/comp_data" 174 | #QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 175 | #STORY_FILE = "studystack_qa_cleaner_no_qm.txt" 176 | # 177 | #stories = get_stories(os.path.join(DATA_DIR, STORY_FILE)) 178 | #story_maxlen = max([len(words) for words in stories]) 179 | #print("story maxlen=", story_maxlen) 180 | # 181 | #qapairs = get_question_answer_pairs(os.path.join(DATA_DIR, QA_TRAIN_FILE)) 182 | #question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 183 | #answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 184 | #print("q=", question_maxlen, "a=", answer_maxlen) 185 | # 186 | #word2idx = build_vocab(stories, qapairs) 187 | #w2v = get_weights_word2vec(word2idx, 188 | # os.path.join(DATA_DIR, "studystack.bin"), 189 | # is_custom=True) 190 | #print(w2v.shape) 191 | # 192 | #Xs = vectorize_stories(stories, word2idx, story_maxlen) 193 | #Xq, Xa = vectorize_qapairs(qapairs, word2idx, question_maxlen, answer_maxlen) 194 | -------------------------------------------------------------------------------- /src/predict-testfile.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.preprocessing.sequence import pad_sequences 4 | import nltk 5 | import numpy as np 6 | import os 7 | 8 | import kaggle 9 | 10 | DATA_DIR = "../data/comp_data" 11 | TRAIN_FILE = "8thGr-NDMC-Train.csv" 12 | TEST_FILE = "8thGr-NDMC-Test.csv" 13 | SUBMIT_FILE = "submission.csv" 14 | 15 | MODEL_DIR = "../data/models" 16 | MODEL_JSON = "qa-lstm-fem-attn.json" 17 | MODEL_WEIGHTS = "qa-lstm-fem-attn-best.h5" 18 | LSTM_SEQLEN = 196 # seq_maxlen from original model 19 | 20 | print("Loading model..") 21 | model = kaggle.load_model(os.path.join(MODEL_DIR, MODEL_JSON), 22 | os.path.join(MODEL_DIR, MODEL_WEIGHTS)) 23 | model.compile(optimizer="adam", loss="categorical_crossentropy", 24 | metrics=["accuracy"]) 25 | 26 | print("Loading vocabulary...") 27 | qapairs = kaggle.get_question_answer_pairs(os.path.join(DATA_DIR, TRAIN_FILE)) 28 | tqapairs = kaggle.get_question_answer_pairs(os.path.join(DATA_DIR, TEST_FILE), 29 | is_test=True) 30 | word2idx = kaggle.build_vocab([], qapairs, tqapairs) 31 | vocab_size = len(word2idx) + 1 # include mask character 0 32 | 33 | ftest = open(os.path.join(DATA_DIR, TEST_FILE), "rb") 34 | fsub = open(os.path.join(DATA_DIR, SUBMIT_FILE), "wb") 35 | fsub.write("id,correctAnswer\n") 36 | line_nbr = 0 37 | for line in ftest: 38 | line = line.strip().decode("utf8").encode("ascii", "ignore") 39 | if line.startswith("#"): 40 | continue 41 | if line_nbr % 10 == 0: 42 | print("Processed %d questions..." % (line_nbr)) 43 | cols = line.split("\t") 44 | qid = cols[0] 45 | question = cols[1] 46 | answers = cols[2:] 47 | # create batch of question 48 | qword_ids = [word2idx[qword] for qword in nltk.word_tokenize(question)] 49 | Xq, Xa = [], [] 50 | for answer in answers: 51 | Xq.append(qword_ids) 52 | Xa.append([word2idx[aword] for aword in nltk.word_tokenize(answer)]) 53 | Xq = pad_sequences(Xq, maxlen=LSTM_SEQLEN) 54 | Xa = pad_sequences(Xa, maxlen=LSTM_SEQLEN) 55 | Y = model.predict([Xq, Xa]) 56 | probs = np.exp(1.0 - (Y[:, 1] - Y[:, 0])) 57 | correct_answer = chr(ord('A') + np.argmax(probs)) 58 | fsub.write("%s,%s\n" % (qid, correct_answer)) 59 | line_nbr += 1 60 | print("Processed %d questions..." % (line_nbr)) 61 | fsub.close() 62 | ftest.close() 63 | -------------------------------------------------------------------------------- /src/qa-blstm-attn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Reshape, Flatten 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.layers.wrappers import Bidirectional 9 | from keras.models import Sequential 10 | from sklearn.cross_validation import train_test_split 11 | import numpy as np 12 | import os 13 | 14 | import kaggle 15 | 16 | DATA_DIR = "../data/comp_data" 17 | MODEL_DIR = "../data/models" 18 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 19 | WORD2VEC_EMBED_SIZE = 300 20 | 21 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 22 | 23 | QA_EMBED_SIZE = 64 24 | BATCH_SIZE = 32 25 | NBR_EPOCHS = 20 26 | 27 | ## extract data 28 | 29 | print("Loading and formatting data...") 30 | qapairs = kaggle.get_question_answer_pairs( 31 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 32 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 33 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 34 | seq_maxlen = max([question_maxlen, answer_maxlen]) 35 | 36 | word2idx = kaggle.build_vocab([], qapairs, []) 37 | vocab_size = len(word2idx) + 1 # include mask character 0 38 | 39 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 40 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 41 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 42 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 43 | Ytrain.shape, Ytest.shape) 44 | 45 | # get embeddings from word2vec 46 | # see https://github.com/fchollet/keras/issues/853 47 | print("Loading Word2Vec model and generating embedding matrix...") 48 | word2vec = Word2Vec.load_word2vec_format( 49 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 50 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 51 | for word, index in word2idx.items(): 52 | try: 53 | embedding_weights[index, :] = word2vec[word.lower()] 54 | except KeyError: 55 | pass # keep as zero (not ideal, but what else can we do?) 56 | 57 | print("Building model...") 58 | qenc = Sequential() 59 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 60 | input_length=seq_maxlen, 61 | weights=[embedding_weights])) 62 | qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 63 | merge_mode="sum")) 64 | qenc.add(Dropout(0.3)) 65 | 66 | aenc = Sequential() 67 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 68 | input_length=seq_maxlen, 69 | weights=[embedding_weights])) 70 | aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 71 | merge_mode="sum")) 72 | aenc.add(Dropout(0.3)) 73 | 74 | # attention model 75 | attn = Sequential() 76 | attn.add(Merge([qenc, aenc], mode="dot", dot_axes=[1, 1])) 77 | attn.add(Flatten()) 78 | attn.add(Dense((seq_maxlen * QA_EMBED_SIZE))) 79 | attn.add(Reshape((seq_maxlen, QA_EMBED_SIZE))) 80 | 81 | model = Sequential() 82 | model.add(Merge([qenc, attn], mode="sum")) 83 | model.add(Flatten()) 84 | model.add(Dense(2, activation="softmax")) 85 | 86 | model.compile(optimizer="adam", loss="categorical_crossentropy", 87 | metrics=["accuracy"]) 88 | 89 | print("Training...") 90 | checkpoint = ModelCheckpoint( 91 | filepath=os.path.join(MODEL_DIR, "qa-blstm-attn-best.hdf5"), 92 | verbose=1, save_best_only=True) 93 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 94 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 95 | callbacks=[checkpoint]) 96 | 97 | print("Evaluation...") 98 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 99 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 100 | 101 | model.save_weights(os.path.join(MODEL_DIR, "qa-blstm-attn-final.hdf5")) 102 | with open(os.path.join(MODEL_DIR, "qa-blstm-attn.json"), "wb") as fjson: 103 | fjson.write(model.to_json()) 104 | 105 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-blstm-attn-best.hdf5")) 106 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 107 | print("\nTest loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 108 | -------------------------------------------------------------------------------- /src/qa-blstm-fem-attn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Reshape, Flatten 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.layers.wrappers import Bidirectional 9 | from keras.models import Sequential 10 | from sklearn.cross_validation import train_test_split 11 | import numpy as np 12 | import os 13 | 14 | import kaggle 15 | 16 | DATA_DIR = "../data/comp_data" 17 | MODEL_DIR = "../data/models" 18 | WORD2VEC_BIN = "studystack.bin" 19 | WORD2VEC_EMBED_SIZE = 300 20 | 21 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 22 | 23 | QA_EMBED_SIZE = 64 24 | BATCH_SIZE = 32 25 | NBR_EPOCHS = 20 26 | 27 | ## extract data 28 | 29 | print("Loading and formatting data...") 30 | qapairs = kaggle.get_question_answer_pairs( 31 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 32 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 33 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 34 | seq_maxlen = max([question_maxlen, answer_maxlen]) 35 | 36 | word2idx = kaggle.build_vocab([], qapairs, []) 37 | vocab_size = len(word2idx) + 1 # include mask character 0 38 | 39 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 40 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 41 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 42 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 43 | Ytrain.shape, Ytest.shape) 44 | 45 | # get embeddings from word2vec 46 | # see https://github.com/fchollet/keras/issues/853 47 | print("Loading Word2Vec model and generating embedding matrix...") 48 | word2vec = Word2Vec.load(os.path.join(DATA_DIR, WORD2VEC_BIN)) 49 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 50 | for word, index in word2idx.items(): 51 | try: 52 | embedding_weights[index, :] = word2vec[word.lower()] 53 | except KeyError: 54 | pass # keep as zero (not ideal, but what else can we do?) 55 | 56 | print("Building model...") 57 | qenc = Sequential() 58 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 59 | input_length=seq_maxlen, 60 | weights=[embedding_weights])) 61 | qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 62 | merge_mode="sum")) 63 | qenc.add(Dropout(0.3)) 64 | 65 | aenc = Sequential() 66 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 67 | input_length=seq_maxlen, 68 | weights=[embedding_weights])) 69 | aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 70 | merge_mode="sum")) 71 | aenc.add(Dropout(0.3)) 72 | 73 | # attention model 74 | attn = Sequential() 75 | attn.add(Merge([qenc, aenc], mode="dot", dot_axes=[1, 1])) 76 | attn.add(Flatten()) 77 | attn.add(Dense((seq_maxlen * QA_EMBED_SIZE))) 78 | attn.add(Reshape((seq_maxlen, QA_EMBED_SIZE))) 79 | 80 | model = Sequential() 81 | model.add(Merge([qenc, attn], mode="sum")) 82 | model.add(Flatten()) 83 | model.add(Dense(2, activation="softmax")) 84 | 85 | model.compile(optimizer="adam", loss="categorical_crossentropy", 86 | metrics=["accuracy"]) 87 | 88 | print("Training...") 89 | checkpoint = ModelCheckpoint( 90 | filepath=os.path.join(MODEL_DIR, "qa-blstm-fem-attn-best.hdf5"), 91 | verbose=1, save_best_only=True) 92 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 93 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 94 | callbacks=[checkpoint]) 95 | 96 | print("Evaluation...") 97 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 98 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 99 | 100 | model.save_weights(os.path.join(MODEL_DIR, "qa-blstm-fem-attn-final.hdf5")) 101 | with open(os.path.join(MODEL_DIR, "qa-blstm-fem-attn.json"), "wb") as fjson: 102 | fjson.write(model.to_json()) 103 | 104 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-blstm-fem-attn-best.hdf5")) 105 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 106 | print("\nTest loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 107 | -------------------------------------------------------------------------------- /src/qa-blstm-story.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Flatten 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.layers.wrappers import Bidirectional 9 | from keras.models import Sequential 10 | from sklearn.cross_validation import train_test_split 11 | import numpy as np 12 | import os 13 | 14 | import kaggle 15 | 16 | DATA_DIR = "../data/comp_data" 17 | MODEL_DIR = "../data/models" 18 | 19 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 20 | WORD2VEC_EMBED_SIZE = 300 21 | 22 | SQA_TRAIN_FILE = "SQA-Train.csv" 23 | 24 | QA_EMBED_SIZE = 64 25 | BATCH_SIZE = 32 26 | NBR_EPOCHS = 20 27 | 28 | ## extract data 29 | 30 | print("Loading and formatting data...") 31 | sqatriples = kaggle.get_story_question_answer_triples( 32 | os.path.join(DATA_DIR, SQA_TRAIN_FILE)) 33 | story_maxlen = max([len(sqatriple[0]) for sqatriple in sqatriples]) 34 | question_maxlen = max([len(sqatriple[1]) for sqatriple in sqatriples]) 35 | answer_maxlen = max([len(sqatriple[2]) for sqatriple in sqatriples]) 36 | 37 | word2idx = kaggle.build_vocab_from_sqa_triples(sqatriples) 38 | vocab_size = len(word2idx) + 1 # include mask character 0 39 | 40 | Xs, Xq, Xa, Y = kaggle.vectorize_sqatriples(sqatriples, word2idx, story_maxlen, 41 | question_maxlen, answer_maxlen) 42 | Xstrain, Xstest, Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 43 | train_test_split(Xs, Xq, Xa, Y, test_size=0.3, random_state=42) 44 | print(Xstrain.shape, Xstest.shape, Xqtrain.shape, Xqtest.shape, 45 | Xatrain.shape, Xatest.shape, Ytrain.shape, Ytest.shape) 46 | 47 | # get embeddings from word2vec 48 | # see https://github.com/fchollet/keras/issues/853 49 | print("Loading Word2Vec model and generating embedding matrix...") 50 | word2vec = Word2Vec.load_word2vec_format( 51 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 52 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 53 | for word, index in word2idx.items(): 54 | try: 55 | embedding_weights[index, :] = word2vec[word.lower()] 56 | except KeyError: 57 | pass # keep as zero (not ideal, but what else can we do?) 58 | 59 | print("Building model...") 60 | 61 | # story encoder. 62 | # output shape: (None, story_maxlen, QA_EMBED_SIZE) 63 | senc = Sequential() 64 | senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 65 | input_length=story_maxlen, 66 | weights=[embedding_weights], mask_zero=True)) 67 | senc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 68 | merge_mode="sum")) 69 | senc.add(Dropout(0.3)) 70 | 71 | # question encoder 72 | # output shape: (None, question_maxlen, QA_EMBED_SIZE) 73 | qenc = Sequential() 74 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 75 | input_length=question_maxlen, 76 | weights=[embedding_weights], mask_zero=True)) 77 | qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, return_sequences=True), 78 | merge_mode="sum")) 79 | qenc.add(Dropout(0.3)) 80 | 81 | # answer encoder 82 | # output shape: (None, answer_maxlen, QA_EMBED_SIZE) 83 | aenc = Sequential() 84 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 85 | input_length=answer_maxlen, 86 | weights=[embedding_weights], mask_zero=True)) 87 | aenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 88 | aenc.add(Dropout(0.3)) 89 | 90 | # merge story and question => facts 91 | # output shape: (None, story_maxlen, question_maxlen) 92 | facts = Sequential() 93 | facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2])) 94 | 95 | # merge question and answer => attention 96 | # output shape: (None, answer_maxlen, question_maxlen) 97 | attn = Sequential() 98 | attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2])) 99 | 100 | # merge facts and attention => model 101 | # output shape: (None, story+answer_maxlen, question_maxlen) 102 | model = Sequential() 103 | model.add(Merge([facts, attn], mode="concat", concat_axis=1)) 104 | model.add(Flatten()) 105 | model.add(Dense(2, activation="softmax")) 106 | 107 | model.compile(optimizer="adam", loss="categorical_crossentropy", 108 | metrics=["accuracy"]) 109 | 110 | print("Training...") 111 | checkpoint = ModelCheckpoint( 112 | filepath=os.path.join(MODEL_DIR, "qa-blstm-story-best.hdf5"), 113 | verbose=1, save_best_only=True) 114 | model.fit([Xstrain, Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 115 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 116 | callbacks=[checkpoint]) 117 | 118 | print("Evaluation") 119 | loss, acc = model.evaluate([Xstest, Xqtest, Xatest], Ytest, 120 | batch_size=BATCH_SIZE) 121 | print("Test loss/accuracy final model: %.4f, %.4f" % (loss, acc)) 122 | 123 | model.save_weights(os.path.join(MODEL_DIR, "qa-blstm-story-final.hdf5")) 124 | with open(os.path.join(MODEL_DIR, "qa-blstm-story.json"), "wb") as fjson: 125 | fjson.write(model.to_json()) 126 | 127 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-blstm-story-best.hdf5")) 128 | loss, acc = model.evaluate([Xstest, Xqtest, Xatest], Ytest, 129 | batch_size=BATCH_SIZE) 130 | print("Test loss/accuracy best model: %.4f, %.4f" % (loss, acc)) 131 | 132 | -------------------------------------------------------------------------------- /src/qa-blstm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.layers.wrappers import Bidirectional 9 | from keras.models import Sequential 10 | from sklearn.cross_validation import train_test_split 11 | import numpy as np 12 | import os 13 | 14 | import kaggle 15 | 16 | DATA_DIR = "../data/comp_data" 17 | MODEL_DIR = "../data/models" 18 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 19 | WORD2VEC_EMBED_SIZE = 300 20 | 21 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 22 | 23 | QA_EMBED_SIZE = 64 24 | BATCH_SIZE = 32 25 | NBR_EPOCHS = 20 26 | 27 | ## extract data 28 | 29 | print("Loading and formatting data...") 30 | qapairs = kaggle.get_question_answer_pairs( 31 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 32 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 33 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 34 | seq_maxlen = max([question_maxlen, answer_maxlen]) 35 | 36 | word2idx = kaggle.build_vocab([], qapairs, []) 37 | vocab_size = len(word2idx) + 1 # include mask character 0 38 | 39 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 40 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 41 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 42 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 43 | Ytrain.shape, Ytest.shape) 44 | 45 | # get embeddings from word2vec 46 | print("Loading Word2Vec model and generating embedding matrix...") 47 | word2vec = Word2Vec.load_word2vec_format( 48 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 49 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 50 | for word, index in word2idx.items(): 51 | try: 52 | embedding_weights[index, :] = word2vec[word.lower()] 53 | except KeyError: 54 | pass # keep as zero (not ideal, but what else can we do?) 55 | 56 | print("Building model...") 57 | qenc = Sequential() 58 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 59 | weights=[embedding_weights], mask_zero=True)) 60 | qenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, 61 | return_sequences=False), merge_mode="sum")) 62 | qenc.add(Dropout(0.3)) 63 | 64 | aenc = Sequential() 65 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 66 | weights=[embedding_weights], mask_zero=True)) 67 | aenc.add(Bidirectional(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, 68 | return_sequences=False), merge_mode="sum")) 69 | aenc.add(Dropout(0.3)) 70 | 71 | model = Sequential() 72 | model.add(Merge([qenc, aenc], mode="sum")) 73 | model.add(Dense(2, activation="softmax")) 74 | 75 | model.compile(optimizer="adam", loss="categorical_crossentropy", 76 | metrics=["accuracy"]) 77 | 78 | print("Training...") 79 | checkpoint = ModelCheckpoint( 80 | filepath=os.path.join(MODEL_DIR, "qa-blstm-best.hdf5"), 81 | verbose=1, save_best_only=True) 82 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 83 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 84 | callbacks=[checkpoint]) 85 | 86 | print("Evaluation...") 87 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 88 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 89 | 90 | model.save_weights(os.path.join(MODEL_DIR, "qa-blstm-final.hdf5")) 91 | with open(os.path.join(MODEL_DIR, "qa-blstm-model.json"), "wb") as fjson: 92 | fjson.write(model.to_json()) 93 | 94 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-blstm-best.hdf5")) 95 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 96 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 97 | -------------------------------------------------------------------------------- /src/qa-dense-autoencoder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.layers import Input, Dense 4 | from keras.models import Model 5 | from sklearn.cross_validation import train_test_split 6 | import numpy as np 7 | import os 8 | 9 | import kaggle 10 | 11 | DATA_DIR = "../data/comp_data" 12 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 13 | STORY_FILE = "studystack_qa_cleaner_no_qm.txt" 14 | STORY_WEIGHTS = "dense-story-weights.txt" 15 | STORY_BIAS = "dense-story-bias.txt" 16 | 17 | EMBED_SIZE = 64 18 | BATCH_SIZE = 256 19 | NBR_EPOCHS = 20 20 | 21 | stories = kaggle.get_stories(os.path.join(DATA_DIR, STORY_FILE)) 22 | story_maxlen = max([len(words) for words in stories]) 23 | 24 | # this part is only required to get the maximum sequence length 25 | qapairs = kaggle.get_question_answer_pairs( 26 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 27 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 28 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 29 | seq_maxlen = max([story_maxlen, question_maxlen, answer_maxlen]) 30 | 31 | word2idx = kaggle.build_vocab(stories, qapairs, []) 32 | vocab_size = len(word2idx) 33 | 34 | Xs = kaggle.vectorize_stories(stories, word2idx, seq_maxlen) 35 | Xstrain, Xstest = train_test_split(Xs, test_size=0.3, random_state=42) 36 | print(Xstrain.shape, Xstest.shape) 37 | 38 | signal = Input(shape=(seq_maxlen,)) 39 | encoded = Dense(EMBED_SIZE, init="glorot_uniform", activation="relu")(signal) 40 | decoded = Dense(seq_maxlen, init="glorot_uniform", activation="sigmoid")(encoded) 41 | autoencoder = Model(input=signal, output=decoded) 42 | 43 | autoencoder.compile("adadelta", loss="binary_crossentropy") 44 | 45 | autoencoder.fit(Xstrain, Xstrain, nb_epoch=NBR_EPOCHS, batch_size=BATCH_SIZE, 46 | shuffle=True, validation_data=(Xstest, Xstest)) 47 | 48 | # save weight matrix for embedding (transforms from seq_maxlen to EMBED_SIZE) 49 | weight_matrix, bias_vector = autoencoder.layers[1].get_weights() 50 | np.savetxt(os.path.join(DATA_DIR, STORY_WEIGHTS), weight_matrix) 51 | np.savetxt(os.path.join(DATA_DIR, STORY_BIAS), bias_vector) 52 | -------------------------------------------------------------------------------- /src/qa-lstm-attn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Reshape, Flatten 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.models import Sequential 9 | from sklearn.cross_validation import train_test_split 10 | import numpy as np 11 | import os 12 | 13 | import kaggle 14 | 15 | DATA_DIR = "../data/comp_data" 16 | MODEL_DIR = "../data/models" 17 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 18 | WORD2VEC_EMBED_SIZE = 300 19 | 20 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 21 | 22 | QA_EMBED_SIZE = 64 23 | BATCH_SIZE = 32 24 | NBR_EPOCHS = 20 25 | 26 | ## extract data 27 | 28 | print("Loading and formatting data...") 29 | qapairs = kaggle.get_question_answer_pairs( 30 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 31 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 32 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 33 | seq_maxlen = max([question_maxlen, answer_maxlen]) 34 | 35 | word2idx = kaggle.build_vocab([], qapairs, []) 36 | vocab_size = len(word2idx) + 1 # include mask character 0 37 | 38 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 39 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 40 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 41 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 42 | Ytrain.shape, Ytest.shape) 43 | 44 | # get embeddings from word2vec 45 | # see https://github.com/fchollet/keras/issues/853 46 | print("Loading Word2Vec model and generating embedding matrix...") 47 | word2vec = Word2Vec.load_word2vec_format( 48 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 49 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 50 | for word, index in word2idx.items(): 51 | try: 52 | embedding_weights[index, :] = word2vec[word.lower()] 53 | except KeyError: 54 | pass # keep as zero (not ideal, but what else can we do?) 55 | 56 | print("Building model...") 57 | qenc = Sequential() 58 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 59 | input_length=seq_maxlen, 60 | weights=[embedding_weights])) 61 | qenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 62 | qenc.add(Dropout(0.3)) 63 | 64 | aenc = Sequential() 65 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 66 | input_length=seq_maxlen, 67 | weights=[embedding_weights])) 68 | aenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 69 | aenc.add(Dropout(0.3)) 70 | 71 | # attention model 72 | attn = Sequential() 73 | attn.add(Merge([qenc, aenc], mode="dot", dot_axes=[1, 1])) 74 | attn.add(Flatten()) 75 | attn.add(Dense((seq_maxlen * QA_EMBED_SIZE))) 76 | attn.add(Reshape((seq_maxlen, QA_EMBED_SIZE))) 77 | 78 | model = Sequential() 79 | model.add(Merge([qenc, attn], mode="sum")) 80 | model.add(Flatten()) 81 | model.add(Dense(2, activation="softmax")) 82 | 83 | model.compile(optimizer="adam", loss="categorical_crossentropy", 84 | metrics=["accuracy"]) 85 | 86 | print("Training...") 87 | checkpoint = ModelCheckpoint( 88 | filepath=os.path.join(MODEL_DIR, "qa-lstm-attn-best.hdf5"), 89 | verbose=1, save_best_only=True) 90 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 91 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 92 | callbacks=[checkpoint]) 93 | 94 | print("Evaluation...") 95 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 96 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 97 | 98 | model.save_weights(os.path.join(MODEL_DIR, "qa-lstm-attn-final.hdf5")) 99 | with open(os.path.join(MODEL_DIR, "qa-lstm-attn.json"), "wb") as fjson: 100 | fjson.write(model.to_json()) 101 | 102 | model.load_weights(filepath=os.path.join(MODEL_DIR, 103 | "qa-lstm-attn-best.hdf5")) 104 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 105 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 106 | 107 | -------------------------------------------------------------------------------- /src/qa-lstm-autoencoder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.layers import Input, RepeatVector 4 | from keras.models import Model 5 | from keras.layers.recurrent import LSTM 6 | from sklearn.cross_validation import train_test_split 7 | import numpy as np 8 | import os 9 | 10 | import kaggle 11 | 12 | DATA_DIR = "../data/comp_data" 13 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 14 | STORY_FILE = "studystack_qa_cleaner_no_qm.txt" 15 | STORY_WEIGHTS = "lstm-story-weights.txt" 16 | STORY_BIAS = "lstm-story-bias.txt" 17 | 18 | EMBED_SIZE = 64 19 | BATCH_SIZE = 256 20 | NBR_EPOCHS = 20 21 | 22 | stories = kaggle.get_stories(os.path.join(DATA_DIR, STORY_FILE)) 23 | story_maxlen = max([len(words) for words in stories]) 24 | 25 | # this part is only required to get the maximum sequence length 26 | qapairs = kaggle.get_question_answer_pairs( 27 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 28 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 29 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 30 | seq_maxlen = max([story_maxlen, question_maxlen, answer_maxlen]) 31 | 32 | word2idx = kaggle.build_vocab(stories, qapairs, []) 33 | vocab_size = len(word2idx) 34 | 35 | Xs = kaggle.vectorize_stories(stories, word2idx, seq_maxlen) 36 | Xstrain, Xstest = train_test_split(Xs, test_size=0.3, random_state=42) 37 | print(Xstrain.shape, Xstest.shape) 38 | 39 | inputs = Input(shape=(seq_maxlen, vocab_size)) 40 | encoded = LSTM(EMBED_SIZE)(inputs) 41 | decoded = RepeatVector(seq_maxlen)(encoded) 42 | decoded = LSTM(vocab_size, return_sequences=True)(decoded) 43 | autoencoder = Model(inputs, decoded) 44 | 45 | autoencoder.compile("adadelta", loss="binary_crossentropy") 46 | 47 | autoencoder.fit(Xstrain, Xstrain, nb_epoch=NBR_EPOCHS, batch_size=BATCH_SIZE, 48 | shuffle=True, validation_data=(Xstest, Xstest)) 49 | 50 | # save weight matrix for embedding (transforms from seq_maxlen to EMBED_SIZE) 51 | weight_matrix, bias_vector = autoencoder.layers[1].get_weights() 52 | np.savetxt(os.path.join(DATA_DIR, STORY_WEIGHTS), weight_matrix) 53 | np.savetxt(os.path.join(DATA_DIR, STORY_BIAS), bias_vector) 54 | -------------------------------------------------------------------------------- /src/qa-lstm-cnn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Flatten 6 | from keras.layers.convolutional import Convolution1D, MaxPooling1D 7 | from keras.layers.embeddings import Embedding 8 | from keras.layers.recurrent import LSTM 9 | from keras.models import Sequential 10 | from sklearn.cross_validation import train_test_split 11 | import numpy as np 12 | import os 13 | 14 | import kaggle 15 | 16 | DATA_DIR = "../data/comp_data" 17 | MODEL_DIR = "../data/models" 18 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 19 | WORD2VEC_EMBED_SIZE = 300 20 | 21 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 22 | STORY_FILE = "studystack_qa_cleaner_no_qm.txt" 23 | 24 | QA_EMBED_SIZE = 64 25 | BATCH_SIZE = 32 26 | NBR_EPOCHS = 20 27 | 28 | ## extract data 29 | 30 | print("Loading and formatting data...") 31 | qapairs = kaggle.get_question_answer_pairs( 32 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 33 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 34 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 35 | seq_maxlen = max([question_maxlen, answer_maxlen]) 36 | 37 | word2idx = kaggle.build_vocab([], qapairs, []) 38 | vocab_size = len(word2idx) + 1 # include mask character 0 39 | 40 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 41 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 42 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 43 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 44 | Ytrain.shape, Ytest.shape) 45 | 46 | # get embeddings from word2vec 47 | # see https://github.com/fchollet/keras/issues/853 48 | print("Loading Word2Vec model and generating embedding matrix...") 49 | word2vec = Word2Vec.load_word2vec_format( 50 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 51 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 52 | for word, index in word2idx.items(): 53 | try: 54 | embedding_weights[index, :] = word2vec[word.lower()] 55 | except KeyError: 56 | pass # keep as zero (not ideal, but what else can we do?) 57 | 58 | print("Building model...") 59 | qenc = Sequential() 60 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 61 | input_length=seq_maxlen, 62 | weights=[embedding_weights])) 63 | qenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 64 | qenc.add(Dropout(0.3)) 65 | qenc.add(Convolution1D(QA_EMBED_SIZE // 2, 5, border_mode="valid")) 66 | qenc.add(MaxPooling1D(pool_length=2, border_mode="valid")) 67 | qenc.add(Dropout(0.3)) 68 | qenc.add(Flatten()) 69 | 70 | aenc = Sequential() 71 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 72 | input_length=seq_maxlen, 73 | weights=[embedding_weights])) 74 | aenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 75 | aenc.add(Dropout(0.3)) 76 | aenc.add(Convolution1D(QA_EMBED_SIZE // 2, 3, border_mode="valid")) 77 | aenc.add(MaxPooling1D(pool_length=2, border_mode="valid")) 78 | aenc.add(Dropout(0.3)) 79 | aenc.add(Flatten()) 80 | 81 | model = Sequential() 82 | model.add(Merge([qenc, aenc], mode="concat", concat_axis=-1)) 83 | model.add(Dense(2, activation="softmax")) 84 | 85 | model.compile(optimizer="adam", loss="categorical_crossentropy", 86 | metrics=["accuracy"]) 87 | 88 | print("Training...") 89 | checkpoint = ModelCheckpoint( 90 | filepath=os.path.join(MODEL_DIR, "qa-lstm-cnn-best.hdf5"), 91 | verbose=1, save_best_only=True) 92 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 93 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 94 | callbacks=[checkpoint]) 95 | 96 | print("Evaluation...") 97 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 98 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 99 | 100 | model.save_weights(os.path.join(MODEL_DIR, "qa-lstm-cnn-final.hdf5")) 101 | with open(os.path.join(MODEL_DIR, "qa-lstm-cnn.json"), "wb") as fjson: 102 | fjson.write(model.to_json()) 103 | 104 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-lstm-cnn-best.hdf5")) 105 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 106 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 107 | -------------------------------------------------------------------------------- /src/qa-lstm-fem-attn.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from keras.callbacks import ModelCheckpoint 4 | from keras.layers import Input, Dense, Dropout, Reshape, Flatten, merge 5 | from keras.layers.embeddings import Embedding 6 | from keras.layers.recurrent import LSTM 7 | from keras.models import Model 8 | from sklearn.cross_validation import train_test_split 9 | import os 10 | import sys 11 | 12 | import kaggle 13 | 14 | DATA_DIR = "../data/comp_data" 15 | MODEL_DIR = "../data/models" 16 | WORD2VEC_BIN = "studystack.bin" 17 | WORD2VEC_EMBED_SIZE = 300 18 | 19 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 20 | QA_TEST_FILE = "8thGr-NDMC-Test.csv" 21 | 22 | QA_EMBED_SIZE = 64 23 | BATCH_SIZE = 128 24 | NBR_EPOCHS = 20 25 | 26 | ## extract data 27 | print("Loading and formatting data...") 28 | qapairs = kaggle.get_question_answer_pairs( 29 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 30 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 31 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 32 | 33 | # Even though we don't use the test set for classification, we still need 34 | # to consider any additional vocabulary words from it for when we use the 35 | # model for prediction (against the test set). 36 | tqapairs = kaggle.get_question_answer_pairs( 37 | os.path.join(DATA_DIR, QA_TEST_FILE), is_test=True) 38 | tq_maxlen = max([len(qapair[0]) for qapair in tqapairs]) 39 | ta_maxlen = max([len(qapair[1]) for qapair in tqapairs]) 40 | 41 | seq_maxlen = max([question_maxlen, answer_maxlen, tq_maxlen, ta_maxlen]) 42 | 43 | word2idx = kaggle.build_vocab([], qapairs, tqapairs) 44 | vocab_size = len(word2idx) + 1 # include mask character 0 45 | 46 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 47 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 48 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 49 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 50 | Ytrain.shape, Ytest.shape) 51 | 52 | # get embeddings from word2vec 53 | print("Loading Word2Vec model and generating embedding matrix...") 54 | embedding_weights = kaggle.get_weights_word2vec(word2idx, 55 | os.path.join(DATA_DIR, WORD2VEC_BIN), is_custom=True) 56 | 57 | print("Building model...") 58 | 59 | # output: (None, QA_EMBED_SIZE, seq_maxlen) 60 | qin = Input(shape=(seq_maxlen,), dtype="int32") 61 | qenc = Embedding(input_dim=vocab_size, 62 | output_dim=WORD2VEC_EMBED_SIZE, 63 | input_length=seq_maxlen, 64 | weights=[embedding_weights])(qin) 65 | qenc = LSTM(QA_EMBED_SIZE, return_sequences=True)(qenc) 66 | qenc = Dropout(0.3)(qenc) 67 | 68 | # output: (None, QA_EMBED_SIZE, seq_maxlen) 69 | ain = Input(shape=(seq_maxlen,), dtype="int32") 70 | aenc = Embedding(input_dim=vocab_size, 71 | output_dim=WORD2VEC_EMBED_SIZE, 72 | input_length=seq_maxlen, 73 | weights=[embedding_weights])(ain) 74 | aenc = LSTM(QA_EMBED_SIZE, return_sequences=True)(aenc) 75 | aenc = Dropout(0.3)(aenc) 76 | 77 | # attention model 78 | attn = merge([qenc, aenc], mode="dot", dot_axes=[1, 1]) 79 | attn = Flatten()(attn) 80 | attn = Dense(seq_maxlen * QA_EMBED_SIZE)(attn) 81 | attn = Reshape((seq_maxlen, QA_EMBED_SIZE))(attn) 82 | 83 | qenc_attn = merge([qenc, attn], mode="sum") 84 | qenc_attn = Flatten()(qenc_attn) 85 | 86 | output = Dense(2, activation="softmax")(qenc_attn) 87 | 88 | model = Model(input=[qin, ain], output=[output]) 89 | 90 | print("Compiling model...") 91 | model.compile(optimizer="adam", loss="categorical_crossentropy", 92 | metrics=["accuracy"]) 93 | 94 | print("Training...") 95 | best_model_filename = os.path.join(MODEL_DIR, 96 | kaggle.get_model_filename(sys.argv[0], "best")) 97 | checkpoint = ModelCheckpoint(filepath=best_model_filename, 98 | verbose=1, save_best_only=True) 99 | model.fit([Xqtrain, Xatrain], [Ytrain], batch_size=BATCH_SIZE, 100 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 101 | callbacks=[checkpoint]) 102 | 103 | print("Evaluation...") 104 | loss, acc = model.evaluate([Xqtest, Xatest], [Ytest], batch_size=BATCH_SIZE) 105 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 106 | 107 | final_model_filename = os.path.join(MODEL_DIR, 108 | kaggle.get_model_filename(sys.argv[0], "final")) 109 | json_model_filename = os.path.join(MODEL_DIR, 110 | kaggle.get_model_filename(sys.argv[0], "json")) 111 | kaggle.save_model(model, json_model_filename, final_model_filename) 112 | 113 | best_model = kaggle.load_model(json_model_filename, best_model_filename) 114 | best_model.compile(optimizer="adam", loss="categorical_crossentropy", 115 | metrics=["accuracy"]) 116 | loss, acc = best_model.evaluate([Xqtest, Xatest], [Ytest], batch_size=BATCH_SIZE) 117 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 118 | 119 | -------------------------------------------------------------------------------- /src/qa-lstm-fem.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.models import Sequential 9 | from sklearn.cross_validation import train_test_split 10 | import numpy as np 11 | import os 12 | 13 | import kaggle 14 | 15 | DATA_DIR = "../data/comp_data" 16 | MODEL_DIR = "../data/models" 17 | WORD2VEC_MODEL = "studystack.bin" 18 | WORD2VEC_EMBED_SIZE = 300 19 | 20 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 21 | 22 | QA_EMBED_SIZE = 64 23 | BATCH_SIZE = 32 24 | NBR_EPOCHS = 20 25 | 26 | ## extract data 27 | 28 | print("Loading and formatting data...") 29 | qapairs = kaggle.get_question_answer_pairs( 30 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 31 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 32 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 33 | seq_maxlen = max([question_maxlen, answer_maxlen]) 34 | 35 | word2idx = kaggle.build_vocab([], qapairs, []) 36 | vocab_size = len(word2idx) + 1 # include mask character 0 37 | 38 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 39 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 40 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 41 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 42 | Ytrain.shape, Ytest.shape) 43 | 44 | print("Loading flashcard Word2Vec model and generating embedding matrix...") 45 | word2vec = Word2Vec.load(os.path.join(DATA_DIR, WORD2VEC_MODEL)) 46 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 47 | for word, index in word2idx.items(): 48 | try: 49 | embedding_weights[index, :] = word2vec[word.lower()] 50 | except KeyError: 51 | pass # keep as zero (not ideal, but what else can we do?) 52 | 53 | print("Building model...") 54 | qenc = Sequential() 55 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 56 | weights=[embedding_weights], mask_zero=True)) 57 | qenc.add(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, return_sequences=False)) 58 | qenc.add(Dropout(0.3)) 59 | 60 | aenc = Sequential() 61 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 62 | weights=[embedding_weights], mask_zero=True)) 63 | aenc.add(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, return_sequences=False)) 64 | aenc.add(Dropout(0.3)) 65 | 66 | model = Sequential() 67 | model.add(Merge([qenc, aenc], mode="sum")) 68 | model.add(Dense(2, activation="softmax")) 69 | 70 | model.compile(optimizer="adam", loss="categorical_crossentropy", 71 | metrics=["accuracy"]) 72 | 73 | print("Training...") 74 | checkpoint = ModelCheckpoint( 75 | filepath=os.path.join(MODEL_DIR, "qa-lstm-fem-best.hdf5"), 76 | verbose=1, save_best_only=True) 77 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 78 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 79 | callbacks=[checkpoint]) 80 | 81 | print("Evaluation...") 82 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 83 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 84 | 85 | model.save_weights(os.path.join(MODEL_DIR, "qa-lstm-fem-final.hdf5")) 86 | with open(os.path.join(MODEL_DIR, "qa-lstm-fem.json"), "wb") as fjson: 87 | fjson.write(model.to_json()) 88 | 89 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-lstm-fem-best.hdf5")) 90 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 91 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 92 | -------------------------------------------------------------------------------- /src/qa-lstm-story.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout, Flatten 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.models import Sequential 9 | from sklearn.cross_validation import train_test_split 10 | import numpy as np 11 | import os 12 | 13 | import kaggle 14 | 15 | DATA_DIR = "../data/comp_data" 16 | MODEL_DIR = "../data/models" 17 | 18 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 19 | WORD2VEC_EMBED_SIZE = 300 20 | 21 | SQA_TRAIN_FILE = "SQA-Train.csv" 22 | 23 | QA_EMBED_SIZE = 64 24 | BATCH_SIZE = 32 25 | NBR_EPOCHS = 20 26 | 27 | ## extract data 28 | 29 | print("Loading and formatting data...") 30 | sqatriples = kaggle.get_story_question_answer_triples( 31 | os.path.join(DATA_DIR, SQA_TRAIN_FILE)) 32 | story_maxlen = max([len(sqatriple[0]) for sqatriple in sqatriples]) 33 | question_maxlen = max([len(sqatriple[1]) for sqatriple in sqatriples]) 34 | answer_maxlen = max([len(sqatriple[2]) for sqatriple in sqatriples]) 35 | 36 | word2idx = kaggle.build_vocab_from_sqa_triples(sqatriples) 37 | vocab_size = len(word2idx) + 1 # include mask character 0 38 | 39 | Xs, Xq, Xa, Y = kaggle.vectorize_sqatriples(sqatriples, word2idx, story_maxlen, 40 | question_maxlen, answer_maxlen) 41 | Xstrain, Xstest, Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 42 | train_test_split(Xs, Xq, Xa, Y, test_size=0.3, random_state=42) 43 | print(Xstrain.shape, Xstest.shape, Xqtrain.shape, Xqtest.shape, 44 | Xatrain.shape, Xatest.shape, Ytrain.shape, Ytest.shape) 45 | 46 | # get embeddings from word2vec 47 | # see https://github.com/fchollet/keras/issues/853 48 | print("Loading Word2Vec model and generating embedding matrix...") 49 | word2vec = Word2Vec.load_word2vec_format( 50 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 51 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 52 | for word, index in word2idx.items(): 53 | try: 54 | embedding_weights[index, :] = word2vec[word.lower()] 55 | except KeyError: 56 | pass # keep as zero (not ideal, but what else can we do?) 57 | 58 | print("Building model...") 59 | 60 | # story encoder. 61 | # output shape: (None, story_maxlen, QA_EMBED_SIZE) 62 | senc = Sequential() 63 | senc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 64 | input_length=story_maxlen, 65 | weights=[embedding_weights], mask_zero=True)) 66 | senc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 67 | senc.add(Dropout(0.3)) 68 | 69 | # question encoder 70 | # output shape: (None, question_maxlen, QA_EMBED_SIZE) 71 | qenc = Sequential() 72 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 73 | input_length=question_maxlen, 74 | weights=[embedding_weights], mask_zero=True)) 75 | qenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 76 | qenc.add(Dropout(0.3)) 77 | 78 | # answer encoder 79 | # output shape: (None, answer_maxlen, QA_EMBED_SIZE) 80 | aenc = Sequential() 81 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 82 | input_length=answer_maxlen, 83 | weights=[embedding_weights], mask_zero=True)) 84 | aenc.add(LSTM(QA_EMBED_SIZE, return_sequences=True)) 85 | aenc.add(Dropout(0.3)) 86 | 87 | # merge story and question => facts 88 | # output shape: (None, story_maxlen, question_maxlen) 89 | facts = Sequential() 90 | facts.add(Merge([senc, qenc], mode="dot", dot_axes=[2, 2])) 91 | 92 | # merge question and answer => attention 93 | # output shape: (None, answer_maxlen, question_maxlen) 94 | attn = Sequential() 95 | attn.add(Merge([aenc, qenc], mode="dot", dot_axes=[2, 2])) 96 | 97 | # merge facts and attention => model 98 | # output shape: (None, story+answer_maxlen, question_maxlen) 99 | model = Sequential() 100 | model.add(Merge([facts, attn], mode="concat", concat_axis=1)) 101 | model.add(Flatten()) 102 | model.add(Dense(2, activation="softmax")) 103 | 104 | model.compile(optimizer="adam", loss="categorical_crossentropy", 105 | metrics=["accuracy"]) 106 | 107 | print("Training...") 108 | checkpoint = ModelCheckpoint( 109 | filepath=os.path.join(MODEL_DIR, "qa-lstm-story-best.hdf5"), 110 | verbose=1, save_best_only=True) 111 | model.fit([Xstrain, Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 112 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 113 | callbacks=[checkpoint]) 114 | 115 | print("Evaluation") 116 | loss, acc = model.evaluate([Xstest, Xqtest, Xatest], Ytest, 117 | batch_size=BATCH_SIZE) 118 | print("Test loss/accuracy final model: %.4f, %.4f" % (loss, acc)) 119 | 120 | model.save_weights(os.path.join(MODEL_DIR, "qa-lstm-story-final.hdf5")) 121 | with open(os.path.join(MODEL_DIR, "qa-lstm-story.json"), "wb") as fjson: 122 | fjson.write(model.to_json()) 123 | 124 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-lstm-story-best.hdf5")) 125 | loss, acc = model.evaluate([Xstest, Xqtest, Xatest], Ytest, 126 | batch_size=BATCH_SIZE) 127 | print("Test loss/accuracy best model: %.4f, %.4f" % (loss, acc)) 128 | -------------------------------------------------------------------------------- /src/qa-lstm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import division, print_function 3 | from gensim.models import Word2Vec 4 | from keras.callbacks import ModelCheckpoint 5 | from keras.layers import Dense, Merge, Dropout 6 | from keras.layers.embeddings import Embedding 7 | from keras.layers.recurrent import LSTM 8 | from keras.models import Sequential 9 | from sklearn.cross_validation import train_test_split 10 | import numpy as np 11 | import os 12 | 13 | import kaggle 14 | 15 | DATA_DIR = "../data/comp_data" 16 | MODEL_DIR = "../data/models" 17 | WORD2VEC_BIN = "GoogleNews-vectors-negative300.bin.gz" 18 | WORD2VEC_EMBED_SIZE = 300 19 | 20 | QA_TRAIN_FILE = "8thGr-NDMC-Train.csv" 21 | 22 | QA_EMBED_SIZE = 64 23 | BATCH_SIZE = 32 24 | NBR_EPOCHS = 20 25 | 26 | ## extract data 27 | 28 | print("Loading and formatting data...") 29 | qapairs = kaggle.get_question_answer_pairs( 30 | os.path.join(DATA_DIR, QA_TRAIN_FILE)) 31 | question_maxlen = max([len(qapair[0]) for qapair in qapairs]) 32 | answer_maxlen = max([len(qapair[1]) for qapair in qapairs]) 33 | seq_maxlen = max([question_maxlen, answer_maxlen]) 34 | 35 | word2idx = kaggle.build_vocab([], qapairs, []) 36 | vocab_size = len(word2idx) + 1 # include mask character 0 37 | 38 | Xq, Xa, Y = kaggle.vectorize_qapairs(qapairs, word2idx, seq_maxlen) 39 | Xqtrain, Xqtest, Xatrain, Xatest, Ytrain, Ytest = \ 40 | train_test_split(Xq, Xa, Y, test_size=0.3, random_state=42) 41 | print(Xqtrain.shape, Xqtest.shape, Xatrain.shape, Xatest.shape, 42 | Ytrain.shape, Ytest.shape) 43 | 44 | # get embeddings from word2vec 45 | # see https://github.com/fchollet/keras/issues/853 46 | print("Loading Word2Vec model and generating embedding matrix...") 47 | word2vec = Word2Vec.load_word2vec_format( 48 | os.path.join(DATA_DIR, WORD2VEC_BIN), binary=True) 49 | embedding_weights = np.zeros((vocab_size, WORD2VEC_EMBED_SIZE)) 50 | for word, index in word2idx.items(): 51 | try: 52 | embedding_weights[index, :] = word2vec[word.lower()] 53 | except KeyError: 54 | pass # keep as zero (not ideal, but what else can we do?) 55 | 56 | del word2vec 57 | del word2idx 58 | 59 | print("Building model...") 60 | qenc = Sequential() 61 | qenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 62 | weights=[embedding_weights], mask_zero=True)) 63 | qenc.add(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, return_sequences=False)) 64 | qenc.add(Dropout(0.3)) 65 | 66 | aenc = Sequential() 67 | aenc.add(Embedding(output_dim=WORD2VEC_EMBED_SIZE, input_dim=vocab_size, 68 | weights=[embedding_weights], mask_zero=True)) 69 | aenc.add(LSTM(QA_EMBED_SIZE, input_length=seq_maxlen, return_sequences=False)) 70 | aenc.add(Dropout(0.3)) 71 | 72 | model = Sequential() 73 | model.add(Merge([qenc, aenc], mode="sum")) 74 | model.add(Dense(2, activation="softmax")) 75 | 76 | model.compile(optimizer="adam", loss="categorical_crossentropy", 77 | metrics=["accuracy"]) 78 | 79 | print("Training...") 80 | checkpoint = ModelCheckpoint( 81 | filepath=os.path.join(MODEL_DIR, "qa-lstm-best.hdf5"), 82 | verbose=1, save_best_only=True) 83 | model.fit([Xqtrain, Xatrain], Ytrain, batch_size=BATCH_SIZE, 84 | nb_epoch=NBR_EPOCHS, validation_split=0.1, 85 | callbacks=[checkpoint]) 86 | 87 | print("Evaluation...") 88 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 89 | print("Test loss/accuracy final model = %.4f, %.4f" % (loss, acc)) 90 | 91 | model.save_weights(os.path.join(MODEL_DIR, "qa-lstm-final.hdf5")) 92 | with open(os.path.join(MODEL_DIR, "qa-lstm.json"), "wb") as fjson: 93 | fjson.write(model.to_json()) 94 | 95 | model.load_weights(filepath=os.path.join(MODEL_DIR, "qa-lstm-best.hdf5")) 96 | loss, acc = model.evaluate([Xqtest, Xatest], Ytest, batch_size=BATCH_SIZE) 97 | print("Test loss/accuracy best model = %.4f, %.4f" % (loss, acc)) 98 | --------------------------------------------------------------------------------