├── .gitignore ├── Algorithm.png ├── LICENSE ├── README.md ├── conversation.py ├── conversation_discriminator.py ├── get_train_data.py ├── model_graph.png ├── split_qa.py ├── train_bot.py └── vocabulary_movie /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /Algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oswaldoludwig/Seq2seq-Chatbot-for-Keras/759943732082cc02931bd9b5f6462af9140a98ad/Algorithm.png -------------------------------------------------------------------------------- /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 | # Seq2seq Chatbot for Keras 2 | This repository contains a new generative model of chatbot based on seq2seq modeling. Further details on this model can be found in Section 3 of the paper [End-to-end Adversarial Learning for Generative Conversational Agents](https://www.researchgate.net/publication/321347271_End-to-end_Adversarial_Learning_for_Generative_Conversational_Agents). In the case of publication using ideas or pieces of code from this repository, please kindly cite this paper. 3 | 4 | The trained model available here used a small dataset composed of ~8K pairs of context (the last two utterances of the dialogue up to the current point) and respective response. The data were collected from dialogues of English courses online. This trained model can be fine-tuned using a closed domain dataset to real-world applications. 5 | 6 | The canonical seq2seq model became popular in neural machine translation, a task that has different prior probability distributions for the words belonging to the input and output sequences, since the input and output utterances are written in different languages. The architecture presented here assumes the same prior distributions for input and output words. Therefore, it shares an embedding layer (Glove pre-trained word embedding) between the encoding and decoding processes through the adoption of a new model. To improve the context sensitivity, the thought vector (i.e. the encoder output) encodes the last two utterances of the conversation up to the current point. To avoid forgetting the context during the answer generation, the thought vector is concatenated to a dense vector that encodes the incomplete answer generated up to the current point. The resulting vector is provided to dense layers that predict the current token of the answer. See Section 3.1 of our paper for a better insight into the advantages of our model. 7 | 8 | The algorithm iterates by including the predicted token into the incomplete answer and feeding it back to the right-hand side input layer of the model shown below. 9 | 10 | ![alt tag](https://github.com/oswaldoludwig/Seq2seq-Chatbot-for-Keras/blob/master/model_graph.png) 11 | 12 | As can be seen in the figure above, the two LSTMs are arranged in parallel, while the canonical seq2seq has the recurrent layers of encoder and decoder arranged in series. Recurrent layers are unfolded during backpropagation through time, resulting in a large number of nested functions and, therefore, a higher risk of vanishing gradient, which is worsened by the cascade of recurrent layers of the canonical seq2seq model, even in the case of gated architectures such as the LSTMs. I believe this is one of the reasons why my model behaves better during training than the canonical seq2seq. 13 | 14 | The following pseudocode explains the algorithm. 15 | 16 | ![alt tag](https://github.com/oswaldoludwig/Seq2seq-Chatbot-for-Keras/blob/master/Algorithm.png) 17 | 18 | The training of this new model converges in few epochs. Using our dataset of 8K training examples, it was required only 100 epochs to reach categorical cross-entropy loss of 0.0318, at the cost of 139 s/epoch running in a GPU GTX980. The performance of this trained model (provided in this repository) seems as convincing as the performance of a vanilla seq2seq model trained on the ~300K training examples of the Cornell Movie Dialogs Corpus, but requires much less computational effort to train. 19 | 20 | **To chat with the pre-trained model:** 21 | 22 | 1. Download the python file "conversation.py", the vocabulary file "vocabulary_movie", and the net weights "my_model_weights20", which can be found [here](https://www.dropbox.com/sh/o0rze9dulwmon8b/AAA6g6QoKM8hBEHGst6W4JGDa?dl=0) ; 23 | 2. Run conversation.py. 24 | 25 | **To chat with the new model trained by our [new GAN-based training algorithm](https://github.com/oswaldoludwig/Adversarial-Learning-for-Generative-Conversational-Agents):** 26 | 27 | 1. Download the python file "conversation_discriminator.py", the vocabulary file "vocabulary_movie", and the net weights "my_model_weights20.h5", "my_model_weights.h5", and "my_model_weights_discriminator.h5", which can be found [here](https://www.dropbox.com/sh/o0rze9dulwmon8b/AAA6g6QoKM8hBEHGst6W4JGDa?dl=0) ; 28 | 2. Run conversation_discriminator.py. 29 | 30 | This model has a better performance using the same training data. The discriminator of the GAN-based model is used to select the best answer between two models, one trained by teacher forcing and another trained by our new GAN-like training method, whose details can be found in [this paper](https://www.researchgate.net/publication/321347271_End-to-end_Adversarial_Learning_for_Generative_Conversational_Agents). 31 | 32 | **To train a new model or to fine tune on your own data:** 33 | 34 | 1. If you want to train from the scratch, delete the file my_model_weights20.h5. To fine tune on your data, keep this file; 35 | 2. Download the Glove folder 'glove.6B' and include this folder in the directory of the chatbot (you can find this folder [here](https://nlp.stanford.edu/projects/glove/)). This algorithm applies transfer learning by using a pre-trained word embedding, which is fine tuned during the training; 36 | 3. Run split_qa.py to split the content of your training data into two files: 'context' and 'answers' and get_train_data.py to store the padded sentences into the files 'Padded_context' and 'Padded_answers'; 37 | 4. Run train_bot.py to train the chatbot (it is recommended the use of GPU, to do so type: THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32,exception_verbosity=high python train_bot.py); 38 | 39 | Name your training data as "data.txt". This file must contain one dialogue utterance per line. If your dataset is big, set the variable num_subsets (in line 29 of train_bot.py) to a larger number. 40 | 41 | weights_file = 'my_model_weights20.h5' 42 | weights_file_GAN = 'my_model_weights.h5' 43 | weights_file_discrim = 'my_model_weights_discriminator.h5' 44 | 45 | A nice overview of the current implementations of neural conversational models for different frameworks (along with some results) can be found [here](https://github.com/nicolas-ivanov/seq2seq_chatbot_links). 46 | 47 | Our model can be applied to other NLP tasks, such as text summarization, see for example [Alternate 2: Recursive Model A](https://machinelearningmastery.com/encoder-decoder-models-text-summarization-keras/). We encourage the application of our model in other tasks, in this case, we kindly ask you to cite our work as can be seen in [this document](https://zenodo.org/record/825303/export/hx#.WiwV81WnGUk), registered in July 2017. 48 | 49 | These codes can run in Ubuntu 14.04.3 LTS, Python 2.7.6, Theano 0.9.0, and Keras 2.0.4. The use of another configuration may require some minor adaptations. 50 | -------------------------------------------------------------------------------- /conversation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Oswaldo Ludwig' 4 | __version__ = '1.01' 5 | 6 | from keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Dropout, merge 7 | from keras.optimizers import Adam 8 | from keras.models import Model 9 | from keras.models import Sequential 10 | from keras.layers import Activation, Dense 11 | from keras.preprocessing import sequence 12 | from keras.layers import concatenate 13 | 14 | import keras.backend as K 15 | import numpy as np 16 | np.random.seed(1234) # for reproducibility 17 | import cPickle 18 | import theano 19 | import os.path 20 | import sys 21 | import nltk 22 | import re 23 | import time 24 | 25 | from keras.utils import plot_model 26 | 27 | word_embedding_size = 100 28 | sentence_embedding_size = 300 29 | dictionary_size = 7000 30 | maxlen_input = 50 31 | 32 | vocabulary_file = 'vocabulary_movie' 33 | weights_file = 'my_model_weights20.h5' 34 | unknown_token = 'something' 35 | file_saved_context = 'saved_context' 36 | file_saved_answer = 'saved_answer' 37 | name_of_computer = 'john' 38 | 39 | def greedy_decoder(input): 40 | 41 | flag = 0 42 | prob = 1 43 | ans_partial = np.zeros((1,maxlen_input)) 44 | ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence) 45 | for k in range(maxlen_input - 1): 46 | ye = model.predict([input, ans_partial]) 47 | yel = ye[0,:] 48 | p = np.max(yel) 49 | mp = np.argmax(ye) 50 | ans_partial[0, 0:-1] = ans_partial[0, 1:] 51 | ans_partial[0, -1] = mp 52 | if mp == 3: # he index of the symbol EOS (end of sentence) 53 | flag = 1 54 | if flag == 0: 55 | prob = prob * p 56 | text = '' 57 | for k in ans_partial[0]: 58 | k = k.astype(int) 59 | if k < (dictionary_size-2): 60 | w = vocabulary[k] 61 | text = text + w[0] + ' ' 62 | return(text, prob) 63 | 64 | 65 | def preprocess(raw_word, name): 66 | 67 | l1 = ['won’t','won\'t','wouldn’t','wouldn\'t','’m', '’re', '’ve', '’ll', '’s','’d', 'n’t', '\'m', '\'re', '\'ve', '\'ll', '\'s', '\'d', 'can\'t', 'n\'t', 'B: ', 'A: ', ',', ';', '.', '?', '!', ':', '. ?', ', .', '. ,', 'EOS', 'BOS', 'eos', 'bos'] 68 | l2 = ['will not','will not','would not','would not',' am', ' are', ' have', ' will', ' is', ' had', ' not', ' am', ' are', ' have', ' will', ' is', ' had', 'can not', ' not', '', '', ' ,', ' ;', ' .', ' ?', ' !', ' :', '? ', '.', ',', '', '', '', ''] 69 | l3 = ['-', '_', ' *', ' /', '* ', '/ ', '\"', ' \\"', '\\ ', '--', '...', '. . .'] 70 | l4 = ['jeffrey','fred','benjamin','paula','walter','rachel','andy','helen','harrington','kathy','ronnie','carl','annie','cole','ike','milo','cole','rick','johnny','loretta','cornelius','claire','romeo','casey','johnson','rudy','stanzi','cosgrove','wolfi','kevin','paulie','cindy','paulie','enzo','mikey','i\97','davis','jeffrey','norman','johnson','dolores','tom','brian','bruce','john','laurie','stella','dignan','elaine','jack','christ','george','frank','mary','amon','david','tom','joe','paul','sam','charlie','bob','marry','walter','james','jimmy','michael','rose','jim','peter','nick','eddie','johnny','jake','ted','mike','billy','louis','ed','jerry','alex','charles','tommy','bobby','betty','sid','dave','jeffrey','jeff','marty','richard','otis','gale','fred','bill','jones','smith','mickey'] 71 | 72 | raw_word = raw_word.lower() 73 | raw_word = raw_word.replace(', ' + name_of_computer, '') 74 | raw_word = raw_word.replace(name_of_computer + ' ,', '') 75 | 76 | for j, term in enumerate(l1): 77 | raw_word = raw_word.replace(term,l2[j]) 78 | 79 | for term in l3: 80 | raw_word = raw_word.replace(term,' ') 81 | 82 | for term in l4: 83 | raw_word = raw_word.replace(', ' + term, ', ' + name) 84 | raw_word = raw_word.replace(' ' + term + ' ,' ,' ' + name + ' ,') 85 | raw_word = raw_word.replace('i am ' + term, 'i am ' + name_of_computer) 86 | raw_word = raw_word.replace('my name is' + term, 'my name is ' + name_of_computer) 87 | 88 | for j in range(30): 89 | raw_word = raw_word.replace('. .', '') 90 | raw_word = raw_word.replace('. .', '') 91 | raw_word = raw_word.replace('..', '') 92 | 93 | for j in range(5): 94 | raw_word = raw_word.replace(' ', ' ') 95 | 96 | if raw_word[-1] <> '!' and raw_word[-1] <> '?' and raw_word[-1] <> '.' and raw_word[-2:] <> '! ' and raw_word[-2:] <> '? ' and raw_word[-2:] <> '. ': 97 | raw_word = raw_word + ' .' 98 | 99 | if raw_word == ' !' or raw_word == ' ?' or raw_word == ' .' or raw_word == ' ! ' or raw_word == ' ? ' or raw_word == ' . ': 100 | raw_word = 'what ?' 101 | 102 | if raw_word == ' .' or raw_word == ' .' or raw_word == ' . ': 103 | raw_word = 'i do not want to talk about it .' 104 | 105 | return raw_word 106 | 107 | def tokenize(sentences): 108 | 109 | # Tokenizing the sentences into words: 110 | tokenized_sentences = nltk.word_tokenize(sentences.decode('utf-8')) 111 | index_to_word = [x[0] for x in vocabulary] 112 | word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)]) 113 | tokenized_sentences = [w if w in word_to_index else unknown_token for w in tokenized_sentences] 114 | X = np.asarray([word_to_index[w] for w in tokenized_sentences]) 115 | s = X.size 116 | Q = np.zeros((1,maxlen_input)) 117 | if s < (maxlen_input + 1): 118 | Q[0,- s:] = X 119 | else: 120 | Q[0,:] = X[- maxlen_input:] 121 | 122 | return Q 123 | 124 | # Open files to save the conversation for further training: 125 | qf = open(file_saved_context, 'w') 126 | af = open(file_saved_answer, 'w') 127 | 128 | print('Starting the model...') 129 | 130 | # ******************************************************************* 131 | # Keras model of the chatbot: 132 | # ******************************************************************* 133 | 134 | ad = Adam(lr=0.00005) 135 | 136 | input_context = Input(shape=(maxlen_input,), dtype='int32', name='the context text') 137 | input_answer = Input(shape=(maxlen_input,), dtype='int32', name='the answer text up to the current token') 138 | LSTM_encoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode context') 139 | LSTM_decoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode answer up to the current token') 140 | if os.path.isfile(weights_file): 141 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, name='Shared') 142 | else: 143 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, weights=[embedding_matrix], input_length=maxlen_input, name='Shared') 144 | word_embedding_context = Shared_Embedding(input_context) 145 | context_embedding = LSTM_encoder(word_embedding_context) 146 | 147 | word_embedding_answer = Shared_Embedding(input_answer) 148 | answer_embedding = LSTM_decoder(word_embedding_answer) 149 | 150 | merge_layer = concatenate([context_embedding, answer_embedding], axis=1, name='concatenate the embeddings of the context and the answer up to current token') 151 | out = Dense(dictionary_size/2, activation="relu", name='relu activation')(merge_layer) 152 | out = Dense(dictionary_size, activation="softmax", name='likelihood of the current token using softmax activation')(out) 153 | 154 | model = Model(inputs=[input_context, input_answer], outputs = [out]) 155 | 156 | model.compile(loss='categorical_crossentropy', optimizer=ad) 157 | 158 | plot_model(model, to_file='model_graph.png') 159 | 160 | if os.path.isfile(weights_file): 161 | model.load_weights(weights_file) 162 | 163 | 164 | # Loading the data: 165 | vocabulary = cPickle.load(open(vocabulary_file, 'rb')) 166 | 167 | print("\n \n \n \n CHAT: \n \n") 168 | 169 | # Processing the user query: 170 | prob = 0 171 | que = '' 172 | last_query = ' ' 173 | last_last_query = '' 174 | text = ' ' 175 | last_text = '' 176 | print('computer: hi ! please type your name.\n') 177 | name = raw_input('user: ') 178 | print('computer: hi , ' + name +' ! My name is ' + name_of_computer + '.\n') 179 | 180 | 181 | while que <> 'exit .': 182 | 183 | que = raw_input('user: ') 184 | que = preprocess(que, name_of_computer) 185 | # Collecting data for training: 186 | q = last_query + ' ' + text 187 | a = que 188 | qf.write(q + '\n') 189 | af.write(a + '\n') 190 | # Composing the context: 191 | if prob > 0.2: 192 | query = text + ' ' + que 193 | else: 194 | query = que 195 | 196 | last_text = text 197 | 198 | Q = tokenize(query) 199 | 200 | # Using the trained model to predict the answer: 201 | 202 | predout, prob = greedy_decoder(Q[0:1]) 203 | start_index = predout.find('EOS') 204 | text = preprocess(predout[0:start_index], name) 205 | print ('computer: ' + text + ' (with probability of %f)'%prob) 206 | 207 | last_last_query = last_query 208 | last_query = que 209 | 210 | qf.close() 211 | af.close() 212 | -------------------------------------------------------------------------------- /conversation_discriminator.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Oswaldo Ludwig' 4 | __version__ = '1.01' 5 | 6 | from keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Dropout, merge 7 | from keras.optimizers import Adam 8 | from keras.models import Model 9 | from keras.models import Sequential 10 | from keras.layers import Activation, Dense 11 | from keras.preprocessing import sequence 12 | from keras.layers import concatenate 13 | 14 | import keras.backend as K 15 | import numpy as np 16 | np.random.seed(1234) # for reproducibility 17 | import cPickle 18 | import theano 19 | import os.path 20 | import sys 21 | import nltk 22 | import re 23 | import time 24 | 25 | from keras.utils import plot_model 26 | 27 | word_embedding_size = 100 28 | sentence_embedding_size = 300 29 | dictionary_size = 7000 30 | maxlen_input = 50 31 | learning_rate = 0.000001 32 | 33 | vocabulary_file = 'vocabulary_movie' 34 | weights_file = 'my_model_weights20.h5' 35 | weights_file_GAN = 'my_model_weights.h5' 36 | weights_file_discrim = 'my_model_weights_discriminator.h5' 37 | unknown_token = 'something' 38 | file_saved_context = 'saved_context' 39 | file_saved_answer = 'saved_answer' 40 | name_of_computer = 'john' 41 | 42 | def greedy_decoder(input): 43 | 44 | flag = 0 45 | prob = 1 46 | ans_partial = np.zeros((1,maxlen_input)) 47 | ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence) 48 | for k in range(maxlen_input - 1): 49 | ye = model.predict([input, ans_partial]) 50 | yel = ye[0,:] 51 | p = np.max(yel) 52 | mp = np.argmax(ye) 53 | ans_partial[0, 0:-1] = ans_partial[0, 1:] 54 | ans_partial[0, -1] = mp 55 | if mp == 3: # he index of the symbol EOS (end of sentence) 56 | flag = 1 57 | if flag == 0: 58 | prob = prob * p 59 | text = '' 60 | for k in ans_partial[0]: 61 | k = k.astype(int) 62 | if k < (dictionary_size-2): 63 | w = vocabulary[k] 64 | text = text + w[0] + ' ' 65 | return(text, prob) 66 | 67 | 68 | def preprocess(raw_word, name): 69 | 70 | l1 = ['won’t','won\'t','wouldn’t','wouldn\'t','’m', '’re', '’ve', '’ll', '’s','’d', 'n’t', '\'m', '\'re', '\'ve', '\'ll', '\'s', '\'d', 'can\'t', 'n\'t', 'B: ', 'A: ', ',', ';', '.', '?', '!', ':', '. ?', ', .', '. ,', 'EOS', 'BOS', 'eos', 'bos'] 71 | l2 = ['will not','will not','would not','would not',' am', ' are', ' have', ' will', ' is', ' had', ' not', ' am', ' are', ' have', ' will', ' is', ' had', 'can not', ' not', '', '', ' ,', ' ;', ' .', ' ?', ' !', ' :', '? ', '.', ',', '', '', '', ''] 72 | l3 = ['-', '_', ' *', ' /', '* ', '/ ', '\"', ' \\"', '\\ ', '--', '...', '. . .'] 73 | l4 = ['jeffrey','fred','benjamin','paula','walter','rachel','andy','helen','harrington','kathy','ronnie','carl','annie','cole','ike','milo','cole','rick','johnny','loretta','cornelius','claire','romeo','casey','johnson','rudy','stanzi','cosgrove','wolfi','kevin','paulie','cindy','paulie','enzo','mikey','i\97','davis','jeffrey','norman','johnson','dolores','tom','brian','bruce','john','laurie','stella','dignan','elaine','jack','christ','george','frank','mary','amon','david','tom','joe','paul','sam','charlie','bob','marry','walter','james','jimmy','michael','rose','jim','peter','nick','eddie','johnny','jake','ted','mike','billy','louis','ed','jerry','alex','charles','tommy','bobby','betty','sid','dave','jeffrey','jeff','marty','richard','otis','gale','fred','bill','jones','smith','mickey'] 74 | 75 | raw_word = raw_word.lower() 76 | raw_word = raw_word.replace(', ' + name_of_computer, '') 77 | raw_word = raw_word.replace(name_of_computer + ' ,', '') 78 | 79 | for j, term in enumerate(l1): 80 | raw_word = raw_word.replace(term,l2[j]) 81 | 82 | for term in l3: 83 | raw_word = raw_word.replace(term,' ') 84 | 85 | for term in l4: 86 | raw_word = raw_word.replace(', ' + term, ', ' + name) 87 | raw_word = raw_word.replace(' ' + term + ' ,' ,' ' + name + ' ,') 88 | raw_word = raw_word.replace('i am ' + term, 'i am ' + name_of_computer) 89 | raw_word = raw_word.replace('my name is' + term, 'my name is ' + name_of_computer) 90 | 91 | for j in range(30): 92 | raw_word = raw_word.replace('. .', '') 93 | raw_word = raw_word.replace('. .', '') 94 | raw_word = raw_word.replace('..', '') 95 | 96 | for j in range(5): 97 | raw_word = raw_word.replace(' ', ' ') 98 | 99 | if raw_word[-1] <> '!' and raw_word[-1] <> '?' and raw_word[-1] <> '.' and raw_word[-2:] <> '! ' and raw_word[-2:] <> '? ' and raw_word[-2:] <> '. ': 100 | raw_word = raw_word + ' .' 101 | 102 | if raw_word == ' !' or raw_word == ' ?' or raw_word == ' .' or raw_word == ' ! ' or raw_word == ' ? ' or raw_word == ' . ': 103 | raw_word = 'what ?' 104 | 105 | if raw_word == ' .' or raw_word == ' .' or raw_word == ' . ': 106 | raw_word = 'i do not want to talk about it .' 107 | 108 | return raw_word 109 | 110 | def tokenize(sentences): 111 | 112 | # Tokenizing the sentences into words: 113 | tokenized_sentences = nltk.word_tokenize(sentences.decode('utf-8')) 114 | index_to_word = [x[0] for x in vocabulary] 115 | word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)]) 116 | tokenized_sentences = [w if w in word_to_index else unknown_token for w in tokenized_sentences] 117 | X = np.asarray([word_to_index[w] for w in tokenized_sentences]) 118 | s = X.size 119 | Q = np.zeros((1,maxlen_input)) 120 | if s < (maxlen_input + 1): 121 | Q[0,- s:] = X 122 | else: 123 | Q[0,:] = X[- maxlen_input:] 124 | 125 | return Q 126 | 127 | # Open files to save the conversation for further training: 128 | qf = open(file_saved_context, 'w') 129 | af = open(file_saved_answer, 'w') 130 | 131 | 132 | def init_model(): 133 | 134 | # ******************************************************************* 135 | # Keras model of the discriminator: 136 | # ******************************************************************* 137 | 138 | ad = Adam(lr=learning_rate) 139 | 140 | input_context = Input(shape=(maxlen_input,), dtype='int32', name='input context') 141 | input_answer = Input(shape=(maxlen_input,), dtype='int32', name='input answer') 142 | input_current_token = Input(shape=(dictionary_size,), name='input_current_token') 143 | 144 | LSTM_encoder_discriminator = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name = 'encoder discriminator') 145 | LSTM_decoder_discriminator = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name = 'decoder discriminator') 146 | 147 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, trainable=False, name = 'shared') 148 | word_embedding_context = Shared_Embedding(input_context) 149 | word_embedding_answer = Shared_Embedding(input_answer) 150 | context_embedding_discriminator = LSTM_encoder_discriminator(word_embedding_context) 151 | answer_embedding_discriminator = LSTM_decoder_discriminator(word_embedding_answer) 152 | loss = concatenate([context_embedding_discriminator, answer_embedding_discriminator, input_current_token], axis=1, name = 'concatenation discriminator') 153 | loss = Dense(1, activation="sigmoid", name = 'discriminator output')(loss) 154 | 155 | model_discrim = Model(inputs=[input_context, input_answer, input_current_token], outputs = [loss]) 156 | 157 | model_discrim.compile(loss='binary_crossentropy', optimizer=ad) 158 | 159 | if os.path.isfile(weights_file_discrim): 160 | model_discrim.load_weights(weights_file_discrim) 161 | 162 | return model_discrim 163 | 164 | def run_discriminator(q, a): 165 | 166 | sa = (a != 0).sum() 167 | 168 | # ************************************************************************* 169 | # running discriminator: 170 | # ************************************************************************* 171 | 172 | p = 1 173 | m = 0 174 | model_discrim = init_model() 175 | count = 0 176 | 177 | for i, sent in enumerate(a): 178 | l = np.where(sent==3) # the position od the symbol EOS 179 | limit = l[0][0] 180 | count += limit + 1 181 | 182 | Q = np.zeros((count,maxlen_input)) 183 | A = np.zeros((count,maxlen_input)) 184 | Y = np.zeros((count,dictionary_size)) 185 | 186 | # Loop over the training examples: 187 | count = 0 188 | for i, sent in enumerate(a): 189 | ans_partial = np.zeros((1,maxlen_input)) 190 | 191 | # Loop over the positions of the current target output (the current output sequence): 192 | l = np.where(sent==3) # the position of the symbol EOS 193 | limit = l[0][0] 194 | 195 | for k in range(1,limit+1): 196 | # Mapping the target output (the next output word) for one-hot codding: 197 | y = np.zeros((1, dictionary_size)) 198 | y[0, int(sent[k])] = 1 199 | 200 | # preparing the partial answer to input: 201 | ans_partial[0,-k:] = sent[0:k] 202 | 203 | # training the model for one epoch using teacher forcing: 204 | Q[count, :] = q[i:i+1] 205 | A[count, :] = ans_partial 206 | Y[count, :] = y 207 | count += 1 208 | 209 | p = model_discrim.predict([ Q, A, Y]) 210 | p = p[-sa:-1] 211 | P = np.sum(np.log(p))/sa 212 | 213 | return P 214 | 215 | print('Starting the model...') 216 | 217 | # ******************************************************************* 218 | # Keras model of the chatbot: 219 | # ******************************************************************* 220 | 221 | ad = Adam(lr=learning_rate) 222 | 223 | input_context = Input(shape=(maxlen_input,), dtype='int32', name='the context text') 224 | input_answer = Input(shape=(maxlen_input,), dtype='int32', name='the answer text up to the current token') 225 | LSTM_encoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode context') 226 | LSTM_decoder = LSTM(sentence_embedding_size, kernel_initializer= 'lecun_uniform', name='Encode answer up to the current token') 227 | 228 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input, name='Shared') 229 | word_embedding_context = Shared_Embedding(input_context) 230 | context_embedding = LSTM_encoder(word_embedding_context) 231 | 232 | word_embedding_answer = Shared_Embedding(input_answer) 233 | answer_embedding = LSTM_decoder(word_embedding_answer) 234 | 235 | merge_layer = concatenate([context_embedding, answer_embedding], axis=1, name='concatenate the embeddings of the context and the answer up to current token') 236 | out = Dense(dictionary_size/2, activation="relu", name='relu activation')(merge_layer) 237 | out = Dense(dictionary_size, activation="softmax", name='likelihood of the current token using softmax activation')(out) 238 | 239 | model = Model(inputs=[input_context, input_answer], outputs = [out]) 240 | 241 | model.compile(loss='categorical_crossentropy', optimizer=ad) 242 | 243 | # Loading the data: 244 | vocabulary = cPickle.load(open(vocabulary_file, 'rb')) 245 | 246 | print("\n \n \n \n CHAT: \n \n") 247 | 248 | # Processing the user query: 249 | prob = 0 250 | que = '' 251 | last_query = ' ' 252 | last_last_query = '' 253 | text = ' ' 254 | last_text = '' 255 | print('computer: hi ! please type your name.\n') 256 | name = raw_input('user: ') 257 | print('computer: hi , ' + name +' ! My name is ' + name_of_computer + '.\n') 258 | 259 | 260 | while que <> 'exit .': 261 | 262 | que = raw_input('user: ') 263 | que = preprocess(que, name_of_computer) 264 | # Collecting data for training: 265 | q = last_query + ' ' + text 266 | a = que 267 | qf.write(q + '\n') 268 | af.write(a + '\n') 269 | # Composing the context: 270 | if prob > 0.2: 271 | query = text + ' ' + que 272 | else: 273 | query = que 274 | 275 | last_text = text 276 | 277 | Q = tokenize(query) 278 | 279 | # Using the trained model to predict the answer: 280 | model.load_weights(weights_file) 281 | predout, prob = greedy_decoder(Q[0:1]) 282 | start_index = predout.find('EOS') 283 | text = preprocess(predout[0:start_index], name) + ' EOS' 284 | 285 | model.load_weights(weights_file_GAN) 286 | predout, prob2 = greedy_decoder(Q[0:1]) 287 | start_index = predout.find('EOS') 288 | text2 = preprocess(predout[0:start_index], name) + ' EOS' 289 | 290 | p1 = run_discriminator(Q, tokenize(text)) 291 | p2 = run_discriminator(Q, tokenize(text2)) 292 | 293 | if max([prob, prob2]) > .9: 294 | if prob > prob2: 295 | best = text[0 : -4] 296 | else: 297 | best = text2[0 : -4] 298 | else: 299 | if p1 > p2: 300 | best = text[0 : -4] 301 | else: 302 | best = text2[0 : -4] 303 | init = '' 304 | 305 | print('\n' + 'computer: ' + best) 306 | 307 | last_last_query = last_query 308 | last_query = que 309 | 310 | qf.close() 311 | af.close() 312 | -------------------------------------------------------------------------------- /get_train_data.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Oswaldo Ludwig' 4 | __version__ = '1.01' 5 | 6 | import numpy as np 7 | np.random.seed(1234) # for reproducibility 8 | import pandas as pd 9 | import os 10 | import csv 11 | import nltk 12 | import itertools 13 | import operator 14 | import pickle 15 | import numpy as np 16 | from keras.preprocessing import sequence 17 | from scipy import sparse, io 18 | from numpy.random import permutation 19 | import re 20 | 21 | questions_file = 'context' 22 | answers_file = 'answers' 23 | vocabulary_file = 'vocabulary_movie' 24 | padded_questions_file = 'Padded_context' 25 | padded_answers_file = 'Padded_answers' 26 | unknown_token = 'something' 27 | 28 | vocabulary_size = 7000 29 | max_features = vocabulary_size 30 | maxlen_input = 50 31 | maxlen_output = 50 # cut texts after this number of words 32 | 33 | print ("Reading the context data...") 34 | q = open(questions_file, 'r') 35 | questions = q.read() 36 | print ("Reading the answer data...") 37 | a = open(answers_file, 'r') 38 | answers = a.read() 39 | all = answers + questions 40 | print ("Tokenazing the answers...") 41 | paragraphs_a = [p for p in answers.split('\n')] 42 | paragraphs_b = [p for p in all.split('\n')] 43 | paragraphs_a = ['BOS '+p+' EOS' for p in paragraphs_a] 44 | paragraphs_b = ['BOS '+p+' EOS' for p in paragraphs_b] 45 | paragraphs_b = ' '.join(paragraphs_b) 46 | tokenized_text = paragraphs_b.split() 47 | paragraphs_q = [p for p in questions.split('\n') ] 48 | tokenized_answers = [p.split() for p in paragraphs_a] 49 | tokenized_questions = [p.split() for p in paragraphs_q] 50 | 51 | ### Counting the word frequencies: 52 | ##word_freq = nltk.FreqDist(itertools.chain(tokenized_text)) 53 | ##print ("Found %d unique words tokens." % len(word_freq.items())) 54 | ## 55 | ### Getting the most common words and build index_to_word and word_to_index vectors: 56 | ##vocab = word_freq.most_common(vocabulary_size-1) 57 | ## 58 | ### Saving vocabulary: 59 | ##with open(vocabulary_file, 'w') as v: 60 | ## pickle.dump(vocab, v) 61 | 62 | vocab = pickle.load(open(vocabulary_file, 'rb')) 63 | 64 | 65 | index_to_word = [x[0] for x in vocab] 66 | index_to_word.append(unknown_token) 67 | word_to_index = dict([(w,i) for i,w in enumerate(index_to_word)]) 68 | 69 | print ("Using vocabulary of size %d." % vocabulary_size) 70 | print ("The least frequent word in our vocabulary is '%s' and appeared %d times." % (vocab[-1][0], vocab[-1][1])) 71 | 72 | # Replacing all words not in our vocabulary with the unknown token: 73 | for i, sent in enumerate(tokenized_answers): 74 | tokenized_answers[i] = [w if w in word_to_index else unknown_token for w in sent] 75 | 76 | for i, sent in enumerate(tokenized_questions): 77 | tokenized_questions[i] = [w if w in word_to_index else unknown_token for w in sent] 78 | 79 | # Creating the training data: 80 | X = np.asarray([[word_to_index[w] for w in sent] for sent in tokenized_questions]) 81 | Y = np.asarray([[word_to_index[w] for w in sent] for sent in tokenized_answers]) 82 | 83 | Q = sequence.pad_sequences(X, maxlen=maxlen_input) 84 | A = sequence.pad_sequences(Y, maxlen=maxlen_output, padding='post') 85 | 86 | with open(padded_questions_file, 'w') as q: 87 | pickle.dump(Q, q) 88 | 89 | with open(padded_answers_file, 'w') as a: 90 | pickle.dump(A, a) -------------------------------------------------------------------------------- /model_graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oswaldoludwig/Seq2seq-Chatbot-for-Keras/759943732082cc02931bd9b5f6462af9140a98ad/model_graph.png -------------------------------------------------------------------------------- /split_qa.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Oswaldo Ludwig' 4 | __version__ = '1.01' 5 | 6 | import numpy as np 7 | 8 | text = open('dialog_simple', 'r') 9 | q = open('context', 'w') 10 | a = open('answers', 'w') 11 | pre_pre_previous_raw='' 12 | pre_previous_raw='' 13 | previous_raw='' 14 | person = ' ' 15 | previous_person=' ' 16 | 17 | l1 = ['won’t','won\'t','wouldn’t','wouldn\'t','’m', '’re', '’ve', '’ll', '’s','’d', 'n’t', '\'m', '\'re', '\'ve', '\'ll', '\'s', '\'d', 'can\'t', 'n\'t', 'B: ', 'A: ', ',', ';', '.', '?', '!', ':', '. ?', ', .', '. ,', 'EOS', 'BOS', 'eos', 'bos'] 18 | l2 = ['will not','will not','would not','would not',' am', ' are', ' have', ' will', ' is', ' had', ' not', ' am', ' are', ' have', ' will', ' is', ' had', 'can not', ' not', '', '', ' ,', ' ;', ' .', ' ?', ' !', ' :', '? ', '.', ',', '', '', '', ''] 19 | l3 = ['-', '_', ' *', ' /', '* ', '/ ', '\"', ' \\"', '\\ ', '--', '...', '. . .'] 20 | 21 | for i, raw_word in enumerate(text): 22 | pos = raw_word.find('+++$+++') 23 | 24 | if pos > -1: 25 | person = raw_word[pos+7:pos+10] 26 | raw_word = raw_word[pos+8:] 27 | while pos > -1: 28 | pos = raw_word.find('+++$+++') 29 | raw_word = raw_word[pos+2:] 30 | 31 | raw_word = raw_word.replace('$+++','') 32 | previous_person = person 33 | 34 | for j, term in enumerate(l1): 35 | raw_word = raw_word.replace(term,l2[j]) 36 | 37 | for term in l3: 38 | raw_word = raw_word.replace(term,' ') 39 | 40 | raw_word = raw_word.lower() 41 | 42 | if i>0: 43 | q.write(pre_previous_raw[:-1] + ' ' + previous_raw[:-1]+ '\n') # python will convert \n to os.linese 44 | a.write(raw_word[:-1]+ '\n') 45 | 46 | pre_pre_previous_raw = pre_previous_raw 47 | pre_previous_raw = previous_raw 48 | previous_raw = raw_word 49 | 50 | q.close() 51 | a.close() 52 | -------------------------------------------------------------------------------- /train_bot.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | __author__ = 'Oswaldo Ludwig' 4 | __version__ = '1.01' 5 | 6 | from keras.layers import Input, Embedding, LSTM, Dense, RepeatVector, Bidirectional, Dropout, merge 7 | from keras.optimizers import Adam, SGD 8 | from keras.models import Model 9 | from keras.models import Sequential 10 | from keras.layers import Activation, Dense 11 | from keras.callbacks import EarlyStopping 12 | from keras.preprocessing import sequence 13 | 14 | import keras.backend as K 15 | import numpy as np 16 | np.random.seed(1234) # for reproducibility 17 | import cPickle 18 | import theano.tensor as T 19 | import os 20 | import pandas as pd 21 | import sys 22 | import matplotlib.pyplot as plt 23 | 24 | word_embedding_size = 100 25 | sentence_embedding_size = 300 26 | dictionary_size = 7000 27 | maxlen_input = 50 28 | maxlen_output = 50 29 | num_subsets = 1 30 | Epochs = 100 31 | BatchSize = 128 # Check the capacity of your GPU 32 | Patience = 0 33 | dropout = .25 34 | n_test = 100 35 | 36 | vocabulary_file = 'vocabulary_movie' 37 | questions_file = 'Padded_context' 38 | answers_file = 'Padded_answers' 39 | weights_file = 'my_model_weights20.h5' 40 | GLOVE_DIR = './glove.6B/' 41 | 42 | early_stopping = EarlyStopping(monitor='val_loss', patience=Patience) 43 | 44 | 45 | 46 | def print_result(input): 47 | 48 | ans_partial = np.zeros((1,maxlen_input)) 49 | ans_partial[0, -1] = 2 # the index of the symbol BOS (begin of sentence) 50 | for k in range(maxlen_input - 1): 51 | ye = model.predict([input, ans_partial]) 52 | mp = np.argmax(ye) 53 | ans_partial[0, 0:-1] = ans_partial[0, 1:] 54 | ans_partial[0, -1] = mp 55 | text = '' 56 | for k in ans_partial[0]: 57 | k = k.astype(int) 58 | if k < (dictionary_size-2): 59 | w = vocabulary[k] 60 | text = text + w[0] + ' ' 61 | return(text) 62 | 63 | 64 | # ********************************************************************** 65 | # Reading a pre-trained word embedding and addapting to our vocabulary: 66 | # ********************************************************************** 67 | 68 | embeddings_index = {} 69 | f = open(os.path.join(GLOVE_DIR, 'glove.6B.100d.txt')) 70 | for line in f: 71 | values = line.split() 72 | word = values[0] 73 | coefs = np.asarray(values[1:], dtype='float32') 74 | embeddings_index[word] = coefs 75 | f.close() 76 | 77 | print('Found %s word vectors.' % len(embeddings_index)) 78 | embedding_matrix = np.zeros((dictionary_size, word_embedding_size)) 79 | 80 | # Loading our vocabulary: 81 | vocabulary = cPickle.load(open(vocabulary_file, 'rb')) 82 | 83 | # Using the Glove embedding: 84 | i = 0 85 | for word in vocabulary: 86 | embedding_vector = embeddings_index.get(word[0]) 87 | 88 | if embedding_vector is not None: 89 | # words not found in embedding index will be all-zeros. 90 | embedding_matrix[i] = embedding_vector 91 | i += 1 92 | 93 | # ******************************************************************* 94 | # Keras model of the chatbot: 95 | # ******************************************************************* 96 | 97 | ad = Adam(lr=0.00005) 98 | 99 | input_context = Input(shape=(maxlen_input,), dtype='int32', name='input_context') 100 | input_answer = Input(shape=(maxlen_input,), dtype='int32', name='input_answer') 101 | LSTM_encoder = LSTM(sentence_embedding_size, init= 'lecun_uniform') 102 | LSTM_decoder = LSTM(sentence_embedding_size, init= 'lecun_uniform') 103 | if os.path.isfile(weights_file): 104 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, input_length=maxlen_input) 105 | else: 106 | Shared_Embedding = Embedding(output_dim=word_embedding_size, input_dim=dictionary_size, weights=[embedding_matrix], input_length=maxlen_input) 107 | word_embedding_context = Shared_Embedding(input_context) 108 | context_embedding = LSTM_encoder(word_embedding_context) 109 | 110 | word_embedding_answer = Shared_Embedding(input_answer) 111 | answer_embedding = LSTM_decoder(word_embedding_answer) 112 | 113 | merge_layer = merge([context_embedding, answer_embedding], mode='concat', concat_axis=1) 114 | out = Dense(dictionary_size/2, activation="relu")(merge_layer) 115 | out = Dense(dictionary_size, activation="softmax")(out) 116 | 117 | model = Model(input=[input_context, input_answer], output = [out]) 118 | 119 | model.compile(loss='categorical_crossentropy', optimizer=ad) 120 | 121 | if os.path.isfile(weights_file): 122 | model.load_weights(weights_file) 123 | 124 | # ************************************************************************ 125 | # Loading the data: 126 | # ************************************************************************ 127 | 128 | q = cPickle.load(open(questions_file, 'rb')) 129 | a = cPickle.load(open(answers_file, 'rb')) 130 | n_exem, n_words = a.shape 131 | 132 | qt = q[0:n_test,:] 133 | at = a[0:n_test,:] 134 | q = q[n_test + 1:,:] 135 | a = a[n_test + 1:,:] 136 | 137 | print('Number of exemples = %d'%(n_exem - n_test)) 138 | step = np.around((n_exem - n_test)/num_subsets) 139 | round_exem = step * num_subsets 140 | 141 | # ************************************************************************* 142 | # Bot training: 143 | # ************************************************************************* 144 | 145 | x = range(0,Epochs) 146 | valid_loss = np.zeros(Epochs) 147 | train_loss = np.zeros(Epochs) 148 | for m in range(Epochs): 149 | 150 | # Loop over training batches due to memory constraints: 151 | for n in range(0,round_exem,step): 152 | 153 | q2 = q[n:n+step] 154 | s = q2.shape 155 | count = 0 156 | for i, sent in enumerate(a[n:n+step]): 157 | l = np.where(sent==3) # the position od the symbol EOS 158 | limit = l[0][0] 159 | count += limit + 1 160 | 161 | Q = np.zeros((count,maxlen_input)) 162 | A = np.zeros((count,maxlen_input)) 163 | Y = np.zeros((count,dictionary_size)) 164 | 165 | # Loop over the training examples: 166 | count = 0 167 | for i, sent in enumerate(a[n:n+step]): 168 | ans_partial = np.zeros((1,maxlen_input)) 169 | 170 | # Loop over the positions of the current target output (the current output sequence): 171 | l = np.where(sent==3) # the position of the symbol EOS 172 | limit = l[0][0] 173 | 174 | for k in range(1,limit+1): 175 | # Mapping the target output (the next output word) for one-hot codding: 176 | y = np.zeros((1, dictionary_size)) 177 | y[0, sent[k]] = 1 178 | 179 | # preparing the partial answer to input: 180 | 181 | ans_partial[0,-k:] = sent[0:k] 182 | 183 | # training the model for one epoch using teacher forcing: 184 | 185 | Q[count, :] = q2[i:i+1] 186 | A[count, :] = ans_partial 187 | Y[count, :] = y 188 | count += 1 189 | 190 | print('Training epoch: %d, training examples: %d - %d'%(m,n, n + step)) 191 | model.fit([Q, A], Y, batch_size=BatchSize, epochs=1) 192 | 193 | test_input = qt[41:42] 194 | print(print_result(test_input)) 195 | train_input = q[41:42] 196 | print(print_result(train_input)) 197 | 198 | model.save_weights(weights_file, overwrite=True) 199 | --------------------------------------------------------------------------------