├── .gitignore ├── 01-Phonemes-to-words.ipynb ├── 03-Twitter-chatbot.ipynb ├── 03-Twitter-chatbot.py ├── 04-Cornell-Movie-Dialog-Bot.ipynb ├── 04-Cornell-Movie-Dialog-Bot.py ├── LICENSE ├── README.markdown ├── ckpt ├── cmudict │ └── pull └── twitter │ └── pull ├── data_utils.py ├── datasets ├── cmudict │ ├── cmudict-processed.tar.gz │ ├── data.py │ └── data_ctl.pkl ├── cornell_corpus │ └── data.py └── twitter │ ├── data.py │ ├── pull │ ├── pull_raw_data │ └── seq2seq.twitter.tar.gz ├── img ├── phoneme.png ├── twitter01.png └── twitter02.png └── seq2seq_wrapper.py /.gitignore: -------------------------------------------------------------------------------- 1 | .*swp 2 | __pycache__ 3 | *.npy 4 | .ipynb_checkpoints 5 | checkpoint 6 | ckpt/*/*.* 7 | ignore/ 8 | *.pkl 9 | *.tar.gz 10 | -------------------------------------------------------------------------------- /01-Phonemes-to-words.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Demonstrate Seq2Seq Wrapper with CMUDict dataset" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "import tensorflow as tf\n", 19 | "import numpy as np\n", 20 | "\n", 21 | "# preprocessed data\n", 22 | "from datasets.cmudict import data\n", 23 | "import data_utils" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 2, 29 | "metadata": { 30 | "collapsed": false 31 | }, 32 | "outputs": [], 33 | "source": [ 34 | "# load data from pickle and npy files\n", 35 | "data_ctl, idx_words, idx_phonemes = data.load_data(PATH='datasets/cmudict/')\n", 36 | "(trainX, trainY), (testX, testY), (validX, validY) = data_utils.split_dataset(idx_phonemes, idx_words)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 3, 42 | "metadata": { 43 | "collapsed": false 44 | }, 45 | "outputs": [], 46 | "source": [ 47 | "# parameters \n", 48 | "xseq_len = trainX.shape[-1]\n", 49 | "yseq_len = trainY.shape[-1]\n", 50 | "batch_size = 128\n", 51 | "xvocab_size = len(data_ctl['idx2pho'].keys()) \n", 52 | "yvocab_size = len(data_ctl['idx2alpha'].keys())\n", 53 | "emb_dim = 128" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "## Create an instance of the Wrapper" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 4, 66 | "metadata": { 67 | "collapsed": false 68 | }, 69 | "outputs": [], 70 | "source": [ 71 | "import seq2seq_wrapper" 72 | ] 73 | }, 74 | { 75 | "cell_type": "code", 76 | "execution_count": 6, 77 | "metadata": { 78 | "collapsed": false 79 | }, 80 | "outputs": [ 81 | { 82 | "data": { 83 | "text/plain": [ 84 | "" 85 | ] 86 | }, 87 | "execution_count": 6, 88 | "metadata": {}, 89 | "output_type": "execute_result" 90 | } 91 | ], 92 | "source": [ 93 | "import importlib\n", 94 | "importlib.reload(seq2seq_wrapper)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 7, 100 | "metadata": { 101 | "collapsed": false 102 | }, 103 | "outputs": [ 104 | { 105 | "name": "stdout", 106 | "output_type": "stream", 107 | "text": [ 108 | " Building Graph " 109 | ] 110 | } 111 | ], 112 | "source": [ 113 | "model = seq2seq_wrapper.Seq2Seq(xseq_len=xseq_len,\n", 114 | " yseq_len=yseq_len,\n", 115 | " xvocab_size=xvocab_size,\n", 116 | " yvocab_size=yvocab_size,\n", 117 | " ckpt_path='ckpt/cmudict/',\n", 118 | " emb_dim=emb_dim,\n", 119 | " num_layers=3\n", 120 | " )" 121 | ] 122 | }, 123 | { 124 | "cell_type": "markdown", 125 | "metadata": {}, 126 | "source": [ 127 | "## Create data generators\n", 128 | "\n", 129 | "Read *data_utils.py* for more information" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 8, 135 | "metadata": { 136 | "collapsed": true 137 | }, 138 | "outputs": [], 139 | "source": [ 140 | "val_batch_gen = data_utils.rand_batch_gen(validX, validY, 16)\n", 141 | "train_batch_gen = data_utils.rand_batch_gen(trainX, trainY, 128)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "markdown", 146 | "metadata": {}, 147 | "source": [ 148 | "- Computational graph was built when the model was instantiated\n", 149 | "- Now all we need to do is train the model using processed CMUdict dataset, via data generators\n", 150 | "- Internally a loop is run for *epochs* times for training\n", 151 | "- Evaluation is done periodically." 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": {}, 157 | "source": [ 158 | "## Train" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 16, 164 | "metadata": { 165 | "collapsed": false 166 | }, 167 | "outputs": [ 168 | { 169 | "name": "stdout", 170 | "output_type": "stream", 171 | "text": [ 172 | "\n", 173 | "Model saved to disk at iteration #5000\n", 174 | "val loss : 0.428838\n", 175 | "\n", 176 | "Model saved to disk at iteration #10000\n", 177 | "val loss : 0.352279\n", 178 | "\n", 179 | "Model saved to disk at iteration #15000\n", 180 | "val loss : 0.302959\n", 181 | "\n", 182 | "Model saved to disk at iteration #20000\n", 183 | "val loss : 0.290396\n", 184 | "\n", 185 | "Model saved to disk at iteration #25000\n", 186 | "val loss : 0.250649\n", 187 | "\n", 188 | "Model saved to disk at iteration #30000\n", 189 | "val loss : 0.239168\n", 190 | "\n", 191 | "Model saved to disk at iteration #35000\n", 192 | "val loss : 0.198182\n", 193 | "\n", 194 | "Model saved to disk at iteration #40000\n", 195 | "val loss : 0.203086\n", 196 | "\n", 197 | "Model saved to disk at iteration #45000\n", 198 | "val loss : 0.213277\n", 199 | "\n", 200 | "Model saved to disk at iteration #50000\n", 201 | "val loss : 0.208600\n", 202 | "\n", 203 | "Model saved to disk at iteration #55000\n", 204 | "val loss : 0.228991\n", 205 | "\n", 206 | "Model saved to disk at iteration #60000\n", 207 | "val loss : 0.205643\n", 208 | "Interrupted by user at iteration 60001\n" 209 | ] 210 | } 211 | ], 212 | "source": [ 213 | "sess = model.train(train_batch_gen, val_batch_gen, sess=sess1)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "markdown", 218 | "metadata": {}, 219 | "source": [ 220 | "## Restore last saved session from disk" 221 | ] 222 | }, 223 | { 224 | "cell_type": "code", 225 | "execution_count": 9, 226 | "metadata": { 227 | "collapsed": false 228 | }, 229 | "outputs": [], 230 | "source": [ 231 | "sess = model.restore_last_session()" 232 | ] 233 | }, 234 | { 235 | "cell_type": "markdown", 236 | "metadata": {}, 237 | "source": [ 238 | "## Predict" 239 | ] 240 | }, 241 | { 242 | "cell_type": "code", 243 | "execution_count": 10, 244 | "metadata": { 245 | "collapsed": false 246 | }, 247 | "outputs": [ 248 | { 249 | "name": "stdout", 250 | "output_type": "stream", 251 | "text": [ 252 | "(16, 16)\n" 253 | ] 254 | } 255 | ], 256 | "source": [ 257 | "output = model.predict(sess, val_batch_gen.__next__()[0])\n", 258 | "print(output.shape)" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": 11, 264 | "metadata": { 265 | "collapsed": false 266 | }, 267 | "outputs": [ 268 | { 269 | "data": { 270 | "text/plain": [ 271 | "array([[12, 15, 14, 7, 23, 5, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0],\n", 272 | " [ 8, 15, 12, 19, 23, 15, 18, 20, 8, 0, 0, 0, 0, 0, 0, 0],\n", 273 | " [ 3, 1, 22, 1, 12, 9, 5, 18, 9, 0, 0, 0, 0, 0, 0, 0],\n", 274 | " [16, 18, 15, 19, 5, 12, 9, 20, 9, 26, 5, 0, 0, 0, 0, 0],\n", 275 | " [ 8, 9, 7, 1, 19, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 276 | " [ 4, 9, 19, 2, 9, 12, 5, 9, 6, 0, 0, 0, 0, 0, 0, 0],\n", 277 | " [11, 9, 19, 13, 5, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 278 | " [21, 14, 3, 15, 20, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 279 | " [19, 21, 3, 8, 9, 1, 11, 9, 0, 0, 0, 0, 0, 0, 0, 0],\n", 280 | " [13, 5, 20, 18, 15, 3, 15, 12, 0, 0, 0, 0, 0, 0, 0, 0],\n", 281 | " [ 4, 21, 18, 21, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 282 | " [13, 1, 7, 14, 15, 12, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0],\n", 283 | " [12, 5, 20, 20, 1, 18, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 284 | " [ 7, 1, 12, 12, 1, 23, 1, 25, 0, 0, 0, 0, 0, 0, 0, 0],\n", 285 | " [ 2, 18, 9, 1, 14, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n", 286 | " [ 8, 15, 18, 16, 9, 6, 9, 14, 9, 0, 0, 0, 0, 0, 0, 0]])" 287 | ] 288 | }, 289 | "execution_count": 11, 290 | "metadata": {}, 291 | "output_type": "execute_result" 292 | } 293 | ], 294 | "source": [ 295 | "output" 296 | ] 297 | }, 298 | { 299 | "cell_type": "markdown", 300 | "metadata": {}, 301 | "source": [ 302 | "## Let us decode and see the words" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": 12, 308 | "metadata": { 309 | "collapsed": false 310 | }, 311 | "outputs": [ 312 | { 313 | "name": "stdout", 314 | "output_type": "stream", 315 | "text": [ 316 | "longwell\n", 317 | "holsworth\n", 318 | "cavalieri\n", 319 | "proselitize\n", 320 | "higashi\n", 321 | "disbileif\n", 322 | "kismet\n", 323 | "uncoted\n", 324 | "suchiaki\n", 325 | "metrocol\n", 326 | "durus\n", 327 | "magnolia\n", 328 | "lettart\n", 329 | "gallaway\n", 330 | "briane\n", 331 | "horpifini\n" 332 | ] 333 | } 334 | ], 335 | "source": [ 336 | "for oi in output:\n", 337 | " print(data_utils.decode(sequence=oi, lookup=data_ctl['idx2alpha'],\n", 338 | " separator=''))" 339 | ] 340 | } 341 | ], 342 | "metadata": { 343 | "kernelspec": { 344 | "display_name": "Python 3", 345 | "language": "python", 346 | "name": "python3" 347 | }, 348 | "language_info": { 349 | "codemirror_mode": { 350 | "name": "ipython", 351 | "version": 3 352 | }, 353 | "file_extension": ".py", 354 | "mimetype": "text/x-python", 355 | "name": "python", 356 | "nbconvert_exporter": "python", 357 | "pygments_lexer": "ipython3", 358 | "version": "3.5.2" 359 | } 360 | }, 361 | "nbformat": 4, 362 | "nbformat_minor": 0 363 | } 364 | -------------------------------------------------------------------------------- /03-Twitter-chatbot.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Demonstrate Seq2Seq Wrapper with twitter chat log" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "import tensorflow as tf\n", 19 | "import numpy as np\n", 20 | "\n", 21 | "# preprocessed data\n", 22 | "from datasets.twitter import data\n", 23 | "import data_utils" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 2, 29 | "metadata": { 30 | "collapsed": false 31 | }, 32 | "outputs": [], 33 | "source": [ 34 | "# load data from pickle and npy files\n", 35 | "metadata, idx_q, idx_a = data.load_data(PATH='datasets/twitter/')\n", 36 | "(trainX, trainY), (testX, testY), (validX, validY) = data_utils.split_dataset(idx_q, idx_a)" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 3, 42 | "metadata": { 43 | "collapsed": false 44 | }, 45 | "outputs": [], 46 | "source": [ 47 | "# parameters \n", 48 | "xseq_len = trainX.shape[-1]\n", 49 | "yseq_len = trainY.shape[-1]\n", 50 | "batch_size = 16\n", 51 | "xvocab_size = len(metadata['idx2w']) \n", 52 | "yvocab_size = xvocab_size\n", 53 | "emb_dim = 1024" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": 4, 59 | "metadata": { 60 | "collapsed": true 61 | }, 62 | "outputs": [], 63 | "source": [ 64 | "import seq2seq_wrapper" 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": 6, 70 | "metadata": { 71 | "collapsed": false 72 | }, 73 | "outputs": [ 74 | { 75 | "data": { 76 | "text/plain": [ 77 | "" 78 | ] 79 | }, 80 | "execution_count": 6, 81 | "metadata": {}, 82 | "output_type": "execute_result" 83 | } 84 | ], 85 | "source": [ 86 | "import importlib\n", 87 | "importlib.reload(seq2seq_wrapper)" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 5, 93 | "metadata": { 94 | "collapsed": false 95 | }, 96 | "outputs": [ 97 | { 98 | "name": "stdout", 99 | "output_type": "stream", 100 | "text": [ 101 | " Building Graph " 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "model = seq2seq_wrapper.Seq2Seq(xseq_len=xseq_len,\n", 107 | " yseq_len=yseq_len,\n", 108 | " xvocab_size=xvocab_size,\n", 109 | " yvocab_size=yvocab_size,\n", 110 | " ckpt_path='ckpt/twitter/',\n", 111 | " emb_dim=emb_dim,\n", 112 | " num_layers=3\n", 113 | " )" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 6, 119 | "metadata": { 120 | "collapsed": true 121 | }, 122 | "outputs": [], 123 | "source": [ 124 | "val_batch_gen = data_utils.rand_batch_gen(validX, validY, 256)\n", 125 | "test_batch_gen = data_utils.rand_batch_gen(testX, testY, 256)\n", 126 | "train_batch_gen = data_utils.rand_batch_gen(trainX, trainY, batch_size)" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 9, 132 | "metadata": { 133 | "collapsed": false 134 | }, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "\n", 141 | " Training started \n", 142 | "\n", 143 | "Model saved to disk at iteration #500\n", 144 | "val loss : 3.370399\n", 145 | "Interrupted by user at iteration 565\n" 146 | ] 147 | } 148 | ], 149 | "source": [ 150 | "sess = model.train(train_batch_gen, val_batch_gen)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "code", 155 | "execution_count": 7, 156 | "metadata": { 157 | "collapsed": true 158 | }, 159 | "outputs": [], 160 | "source": [ 161 | "sess = model.restore_last_session()" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": 10, 167 | "metadata": { 168 | "collapsed": false 169 | }, 170 | "outputs": [ 171 | { 172 | "name": "stdout", 173 | "output_type": "stream", 174 | "text": [ 175 | "(256, 20)\n" 176 | ] 177 | } 178 | ], 179 | "source": [ 180 | "input_ = test_batch_gen.__next__()[0]\n", 181 | "output = model.predict(sess, input_)\n", 182 | "print(output.shape)" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 11, 188 | "metadata": { 189 | "collapsed": false 190 | }, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "q : [go see them]; a : [i was thinking of that]\n", 197 | "q : [a unk of the before we say goodnight from last at unk state park in maine]; a : [this is a great idea to be a great day for a while]\n", 198 | "q : [unless you want this ]; a : [what is he]\n", 199 | "q : [my fav moment from the debate last night]; a : [wait for the first time]\n", 200 | "q : [ok i dont see any catholic terrorist]; a : [not even to be a threat to the point]\n", 201 | "q : [thats your sister]; a : [i dont know what i was talking about]\n", 202 | "q : [radical islam unk a threat to the united states and our leaders need to realize this before its too late]; a : [is that a joke]\n", 203 | "q : [literally the same thing happened to me ]; a : [thats what i said]\n", 204 | "q : [last chance to win vip passes to new york comic con amp meet the walking dead cast go]; a : [if you were in the same place i dont have to see it]\n", 205 | "q : [4 correction that video is from a few years ago]; a : [its been a fan of my life but i dont know what to do]\n", 206 | "q : [we are doing band there are many unk in the band]; a : [i have to be a good job]\n", 207 | "q : [im sure it does but i doubt ill see a unk amount of money from it]; a : [i think its a good idea]\n", 208 | "q : [which report did this graph come from the unk unk data is really interesting and hard to find]; a : [is this a lot of times from the world of the world of the year]\n", 209 | "q : [thats pretty cool but now i am dying to find out what s first tweet will be]; a : [it was a good time for the first time]\n", 210 | "q : [great debate poll numbers i will be on at 700 to discuss enjoy]; a : [dont have to be a president]\n", 211 | "q : [yooo me too]; a : [ahh i know i was just thinking about this]\n", 212 | "q : [the ladies of could not be more idiotic or blind they should invite on for a talk]; a : [they are not sarcastic]\n", 213 | "q : [clothes that dont fit me no more]; a : [ur so cute]\n", 214 | "q : [good evening unk]; a : [good morning all]\n", 215 | "q : [so pretty much she didnt want him so u were is 2nd choice ]; a : [lol i dont know what to say about it ]\n", 216 | "q : [another reminder of my favorite quote people sell what they need and buy what they dont need thanks]; a : [this is a joke]\n", 217 | "q : [the point is there is unk to a hate and fear unk campaign]; a : [you dont care about the debate that is not a fact that you are not a racist]\n", 218 | "q : [which one is he]; a : [hes a good one]\n", 219 | "q : [our diversity is our strength is the most dangerous statement do not be fooled diversity destroys nations]; a : [is this a new yorker of the world terrorism]\n", 220 | "q : [i just want to set up a casual fuck buddy situation that slowly but surely unk into a wedding marriage]; a : [have to be a good day and ill be able to be able to help]\n", 221 | "q : [me amp bae tryna get back to us ]; a : [cant wait to see you]\n", 222 | "q : [probably not]; a : [you dont know what to do with you]\n", 223 | "q : [fuck that shit lol]; a : [lol i know that was a joke]\n", 224 | "q : [jumping the shark]; a : [so much the way to the game]\n", 225 | "q : [my fave when you wake up]; a : [omg this is so cute]\n", 226 | "q : [lol all of you guys are idiots over 2 million people live here teams in smaller markets still support]; a : [not have to be a good place]\n", 227 | "q : [as long as nobody who ever had a mother votes for him we should be ok]; a : [what about the media is not in the us terrorism and not not the right]\n", 228 | "q : [nice running into you]; a : [not a good time]\n", 229 | "q : [its taking over lol]; a : [lol i dont even know what to say]\n", 230 | "q : [part 4 on exclusive investigation into unk minister in the unk]; a : [why is this a joke]\n", 231 | "q : [heres the unk its unk]; a : [i think the same thing is there]\n", 232 | "q : [hillary clinton needs to be arrested she has committed more crimes than the majority of those in our unk]; a : [are you going to be a liar for a landslide]\n", 233 | "q : [who you talking abt sis]; a : [dont be a bitch]\n", 234 | "q : [get your facts straight youre the one that should feel guilty]; a : [its not a joke but its a threat to the point of the planet]\n", 235 | "q : [i received my passport im ready to vote for my country for you for my daughter for women workers]; a : [good luck ]\n", 236 | "q : [you need to unk that woman with her past expose for all of the crimes she committed against humanity]; a : [i dont think she was born in the middle of the middle of the middle of the debate]\n", 237 | "q : [what conservatives dont understand is i would have done the same for ]; a : [you are a fan of the same ones]\n", 238 | "q : [should i go medium or large if skinny but weirdly long arms or is there a size chart somewhere]; a : [maybe its been a fan of the game]\n", 239 | "q : [its okay sometimes i like to go back and delete a bunch of tweets that didnt get any favs]; a : [lmao i dont know what i feel about it i dont even know how to do]\n", 240 | "q : [whats really scary is that about a quarter of the unk actually think unk is sincere]; a : [not sure if it was a lot of people]\n", 241 | "q : [unk bring this back to the club ffs]; a : [did you know that cares about]\n", 242 | "q : [yep this is where ill be sunday because ]; a : [if you can find the same version of the game]\n", 243 | "q : [its not even your birthday stop trying to make it happen early]; a : [its not a good one]\n", 244 | "q : [ive now got the next unk]; a : [damn i was there]\n", 245 | "q : [i believe you were asking about something like this a while back]; a : [it was a joke but i dont think it was a lot of people]\n", 246 | "q : [so what its just the internet on a smaller screen]; a : [is it on the way]\n", 247 | "q : [im not white ]; a : [what are you talking about]\n", 248 | "q : [they want unk from responsibility]; a : [they are not a racist]\n", 249 | "q : [how when and where to vote for bernie]; a : [trump is a lying woman to get a wall in the country]\n", 250 | "q : [you know how retarded this is]; a : [it was a joke]\n", 251 | "q : [when unk kelly asked miss universe this question about donald trump she had no answer]; a : [and you dont know what to say about the debate is a fact]\n", 252 | "q : [happy unk day to my brother love you fam ]; a : [love you too much love you too ]\n", 253 | "q : [can anyone guess how little i care what a poll says about this subject]; a : [i think the same thing is that is the problem of the truth]\n", 254 | "q : [thats what i said it was the live]; a : [it was so good i was in the city]\n", 255 | "q : [unk your office]; a : [i think the same thing is that]\n", 256 | "q : [they have a travel course for the summer and i really want to go but its a lot of money]; a : [ill be there for a while to get a new one ]\n", 257 | "q : [can i get a big big thank you amp rt for our amazing unk today]; a : [love the love thank you ]\n", 258 | "q : [after bombing attempts around new york congress wants unk to secure unk buses via]; a : [ you need to get a chance to get a wall in the future]\n", 259 | "q : [smh i thought you meant crack cocaine]; a : [you know what the fuck is]\n", 260 | "q : [hillarys been failing for 30 years in not getting the job done it will never change]; a : [you are a moron]\n", 261 | "q : [5 unk to increase member engagement by ]; a : [and they are]\n", 262 | "q : [wow just woke up in phoenix and going to play with unk tonite]; a : [its a good time to get a pic of me]\n", 263 | "q : [its a hell of a lot of fun]; a : [i love it]\n", 264 | "q : [the girl in the back looks scary af]; a : [thats the cutest]\n", 265 | "q : [where did he go]; a : [just a good one]\n", 266 | "q : [wow you deserve a unk check your dms ]; a : [i love this]\n", 267 | "q : [i didnt have a very good first impression with her ]; a : [this is a good thing]\n", 268 | "q : [moves back to sj in november]; a : [hey i will be there]\n", 269 | "q : [why doesnt or anyone from get additional info]; a : [because i dont even know if you want to be a good one of the year]\n", 270 | "q : [damn im loving this track and so unk good lt3 lt3]; a : [happy birthday ]\n", 271 | "q : [that would be a terrible unk in their security]; a : [maybe he was]\n", 272 | "q : [have you seen the magnificent 7 yet]; a : [not heard it was a good idea]\n", 273 | "q : [dang it mike thats how the brexit happened]; a : [its a good thing to be a guy]\n", 274 | "q : [live on new bone ]; a : [this is so good]\n", 275 | "q : [hes from the old country its understandable]; a : [just even on the debate]\n", 276 | "q : [someone please give me better unk dramatic music to listen to]; a : [dont even know that it was a good thing]\n", 277 | "q : [got me as a wack unk im not following that shit]; a : [you dont know what you mean]\n", 278 | "q : [unk in new york are so fucking unk and extra]; a : [i know i know]\n", 279 | "q : [whats up man actually sold unk in july im working in the city now]; a : [what about the world]\n", 280 | "q : [when it comes to story easiest way to fix something is to cut it kind of like civil war surgery]; a : [they dont even be a fan of the game of the first time]\n", 281 | "q : [its in 8 months]; a : [its a good time to get a new phone]\n", 282 | "q : [lets unk the gender unk in tech]; a : [i need to get a new one]\n", 283 | "q : [haha someones enjoying sf a bit too much ]; a : [you know i was going to be a good day ]\n", 284 | "q : [real nigga hours coming soon]; a : [you got me cry ]\n", 285 | "q : [who the fuck are the anti unk league]; a : [heres a new yorker]\n", 286 | "q : [my cat is very comfortable me not so much]; a : [not like a lot of the time of the middle]\n", 287 | "q : [its very upsetting that i have to miss my first womens world championship for many reasons]; a : [did you have a good time to get a new phone]\n", 288 | "q : [i think it was pre filmed]; a : [ i dont know what to do]\n", 289 | "q : [guys i met this weekend and he told me the meaning of life]; a : [the best thing ever]\n", 290 | "q : [i dont bang people outside the industry]; a : [dont have to be a fan of the time]\n", 291 | "q : [hes a major league baseball player with three fucking rings not a 5 year old fucking idiot]; a : [probably even to be a fan of a joke]\n", 292 | "q : [rub my ass]; a : [are you coming to the gym]\n", 293 | "q : [im going to lady problems unk new york see you there via]; a : [did you have any other ideas to get the link to the next one]\n", 294 | "q : [oh hey insights from on amp at unk on cant wait]; a : [let me know if you get a new phone]\n", 295 | "q : [happy birthday unk you are beautiful inside and out i miss and love you very much ]; a : [thank you so much love you too ]\n", 296 | "q : [because he doesnt want to offend the actual enemy]; a : [no he has no idea what he wants]\n", 297 | "q : [go unk they said good for your health they said tell that to my broken unk ]; a : [i dont even know what i was thinking about it but i dont even know how to do it]\n", 298 | "q : [my heart gets so happy every time i think about unk starting this weekend]; a : [omg i was so happy to see that]\n", 299 | "q : [who has a drone they wanna bring to meet n cheat new york lol]; a : [ill be in the city room now]\n", 300 | "q : [so far im not too impressed with netflix original tv shows good thing i dont have to pay for it]; a : [i think they have a chance to get a better game of the game]\n", 301 | "q : [got my copy cant wait to pop my cherry cherry]; a : [did you get a new one of the world of the day ]\n", 302 | "q : [unk youre the one for me lets date cutie]; a : [hey i love you]\n", 303 | "q : [who is the keith in this video doesnt look anything like scott]; a : [this is my favorite tweet ever]\n", 304 | "q : [first time a celebrity came on and he wasnt the unk]; a : [lmfao im just thinking about that i was just thinking about it]\n", 305 | "q : [happy happy birthday unk ]; a : [thank you ]\n", 306 | "q : [my mom has 8 cats eight cats]; a : [damn shit is that a thing]\n", 307 | "q : [so is new music up to par with the new look and new attitude]; a : [this is so cute i love it]\n", 308 | "q : [i miss you so much it hurts]; a : [miss you too ]\n", 309 | "q : [thanks v much for invitation]; a : [thanks for the retweet i hope you had a great time to see you]\n", 310 | "q : [who do you think won last nights ]; a : [who cares about]\n", 311 | "q : [one of unk two is false and the other is unk the false i think the opposite of you]; a : [i think they were a fan of the world]\n", 312 | "q : [well know weve made it in life when our apartment has air conditioning]; a : [it was so good]\n", 313 | "q : [hey atleast he can talk to his audience clinton has some serious unk issues with unk and lying]; a : [and he said it before he was a good job]\n", 314 | "q : [unk heres that sharing word again i dunno chelsea clinton]; a : [if you have a chance of the debate of the debate]\n", 315 | "q : [cool im at work eating lunch ]; a : [you can i get a new phone ]\n", 316 | "q : [3000 miles away and he still unk to get me breakfast in bed on my bday ]; a : [lol i was just thinking about this i just got to go to my face ]\n", 317 | "q : [which one]; a : [the only one]\n", 318 | "q : [join us its an elite group]; a : [its a good thing]\n", 319 | "q : [unk morning joe put her on instead]; a : [you know what you mean]\n", 320 | "q : [my unk new thing is sending out a unk good morning text every fucking morning ]; a : [you got a good one]\n", 321 | "q : [want a gf but i enjoy not having someone else to spend money on]; a : [you can me be a good one]\n", 322 | "q : [whos an app developer i low key believe i have a great app idea and high key want to start]; a : [yes we can certainly help you in developing your dream app]\n", 323 | "q : [wtf deadass thats crazy]; a : [lol i know i was going to be a fan of my life]\n", 324 | "q : [how do you unk bullying like this]; a : [i was thinking of this]\n", 325 | "q : [wait where]; a : [not a joke]\n", 326 | "q : [unk the difference unk colin kaepernick has made via]; a : [the only thing is the only thing that matters is that]\n", 327 | "q : [missed the unk my life is better for it]; a : [its gonna be a good one]\n", 328 | "q : [hang on i have to get unk itll take me a minute to reply]; a : [ill be there for a while]\n", 329 | "q : [i think i did on sunday sorry ]; a : [did you have a chance]\n", 330 | "q : [this guy isnt very nice]; a : [it was not a good thing]\n", 331 | "q : [absolutely eliminate welfare good call on your part]; a : [very very good]\n", 332 | "q : [your office view ]; a : [this is so cute]\n", 333 | "q : [wait no wtf shes unk money from my checking to my own unk wtf nvm she still used my money]; a : [she needs to be a little girl ]\n", 334 | "q : [i didnt make it tho just go to a]; a : [dont you have to be a good one]\n", 335 | "q : [didnt you unfollow me jessica]; a : [no i dont know what to do]\n", 336 | "q : [please unfollow if you are unk to retweet this unk]; a : [no one is so good]\n", 337 | "q : [lol yea i bet everyone who works there is but im depressed i shouldve asked for her unk]; a : [ill be a good time to be a little bit ]\n", 338 | "q : [i do this all the time]; a : [you should be a little fan of you]\n", 339 | "q : [he might be the best actor ever but what the heck is all this mess about]; a : [the only one of the best things]\n", 340 | "q : [me unk through the rest of the week]; a : [love this pic ]\n", 341 | "q : [god im so sick of people thinking that theyre artists for putting some j unk beat over a jazz sample]; a : [oh ok i have to be a fan of the game]\n", 342 | "q : [either or i work my ass off to support my family and pay my taxes no food unk]; a : [its not a joke but its a good thing]\n", 343 | "q : [hard life today]; a : [i know its a good one of the day]\n", 344 | "q : [lauren is awful because of her shady af reaction gifs lmao]; a : [thats like he has a lot of money]\n", 345 | "q : [then theres me like]; a : [ you have to be a little fan ]\n", 346 | "q : [well now theyre saying that i not only won the nbc presidential forum but last night the big debate nice]; a : [are you gonna be a fan of the first time ]\n", 347 | "q : [your vote your chance to have a voice in this election register today ]; a : [you know what the hell is]\n", 348 | "q : [you gave uncle rudy unk deserved props i appreciate your honesty]; a : [you are a lot of people who are a little different man]\n", 349 | "q : [we ordered them so they should be coming soon]; a : [i am so excited to hear this]\n", 350 | "q : [where is bob]; a : [new york and 6th]\n", 351 | "q : [whenever i scroll thru facebook and see this ad i think its for a second]; a : [it was a joke but i dont even know what to do]\n", 352 | "q : [lol unk jackson u sold ya soul b]; a : [you dont know what you want]\n", 353 | "q : [she supports my congressman]; a : [she is so cute]\n", 354 | "q : [of course lol u dont know unk unk]; a : [dont know what to do]\n", 355 | "q : [you know nothing about your husband does she or doesnt she]; a : [she doesnt care about that]\n", 356 | "q : [sending you all the healing thoughts ]; a : [i am so excited for this]\n", 357 | "q : [see this recipe for russian unk ball soup calls for several garlic unk]; a : [ he is a big guy]\n", 358 | "q : [isnt that just unk tag and unk]; a : [good to know]\n", 359 | "q : [i found it challenging when i wanted to edit directions]; a : [i dont know that it was a good idea but i have a lot of people]\n", 360 | "q : [this sequel to what is code is no quick afternoon read]; a : [still a good idea]\n", 361 | "q : [yall both lowkey rich tho lol]; a : [you dont know what they say]\n", 362 | "q : [fill stop this is mine and unk thing]; a : [looks like it was a good thing]\n", 363 | "q : [how about people who take advantage of porn stars]; a : [yeah i think its not a good idea but its not a good thing]\n", 364 | "q : [when you hear a unk ring in your apt and you dont have a unk]; a : [who is that]\n", 365 | "q : [as a state worker id have no problem paying for my insurance and unk]; a : [if you have a chance to be in the city]\n", 366 | "q : [lt i was talking to her lol bigots i didnt think my spelling would be the part to offend u]; a : [she was so cute and she was so mad ]\n", 367 | "q : [knowing nothing about this at all this looks awesome]; a : [it was a great thing to be a good guy]\n", 368 | "q : [the sweet irony of trumps biggest campaign problems]; a : [dont think the same thing is that]\n", 369 | "q : [im overwhelmed couldnt imagine the hospitals doctors they must be on stress leave]; a : [wait i was just thinking about this]\n", 370 | "q : [your mom drives it everywhere ]; a : [she is so cute ]\n", 371 | "q : [this tweet makes me sad]; a : [i dont think so but i dont think so]\n", 372 | "q : [exclusive video donald trump claims his microphone was defective says its a conspiracy against him]; a : [i think he was born in the middle of the debate]\n", 373 | "q : [i was against going into iraq trump unk in florida not any unk today than it was yesterday]; a : [is that a joke that is a joke to the trump foundation and trump is not a racist]\n", 374 | "q : [i have studio in an hour and im hella unk oh god]; a : [its a good thing to get a pic of the time]\n", 375 | "q : [oct 6 until whenever shows up becomes a robot and cant thumbs]; a : [i can relate to the gym and i can get it]\n", 376 | "q : [with right around the corner i thought this very fitting safe travels everyone ]; a : [omg i love this pic i love you]\n", 377 | "q : [probably not a good idea to call people crooked unk when you look like a twisted troll]; a : [if you can say that i can get a pic of my life and a half months ago]\n", 378 | "q : [startups can take unk risk with indian money unk via]; a : [this is a great place to see]\n", 379 | "q : [celebrity styles unk unk]; a : [he was so cute]\n", 380 | "q : [and it never happened before ice age never happened nor unk just now give me a break]; a : [the whole thing is that the first thing i was]\n", 381 | "q : [lmao jus tryna enjoy the day off]; a : [lol i got to get a ticket ]\n", 382 | "q : [i prefer your unk feed]; a : [no no one is a joke]\n", 383 | "q : [also what kind of question is that]; a : [not sure the same thing]\n", 384 | "q : [the bikes are way better than the cars i think]; a : [are you all of the us]\n", 385 | "q : [rt to win black rose gold unk brush set must be following me so i can dm winner]; a : [i know right but i was just thinking about it]\n", 386 | "q : [playing holy spirit by unk]; a : [beautiful pic ]\n", 387 | "q : [ can pm share such messages over letter head]; a : [ and do you have to be a good job]\n", 388 | "q : [if you get this super unk joke lets be friends]; a : [ill be there for a few days ago]\n", 389 | "q : [it was so damn weird but i laughed my ass off hah]; a : [was a joke lol]\n", 390 | "q : [tell me more what does it do]; a : [just like the same thing to the end of the game]\n", 391 | "q : [uh i read something about this 2 days ago ill try to find the link]; a : [it was so good to me]\n", 392 | "q : [who will i be seeing at the this winter vip on sale today ga on sale this]; a : [you can be there in the city but i will be there]\n", 393 | "q : [many people are saying that s are the result of a cocaine problem many many people credible sources]; a : [what is the point of the truth]\n", 394 | "q : [i crashed it damnit lin when will you learn]; a : [if you dont have any other choice to do with you]\n", 395 | "q : [i am so proud and unk]; a : [you know that]\n", 396 | "q : [oh man this shit got me real emotional rip unk]; a : [you know what to say]\n", 397 | "q : [eric trump unk dads courage in not bringing up bill clintons unk]; a : [he is a lot of people who have a good job to get a man]\n", 398 | "q : [im watching with my daughter]; a : [youre so cute]\n", 399 | "q : [that is impressive how long did they take to prepare]; a : [looks like a lot of the game]\n", 400 | "q : [i think something else was defective what he said or rather unk]; a : [i dont know what to say about it]\n", 401 | "q : [roasted unk amp black unk 9]; a : [you should be so happy to see that]\n", 402 | "q : [shes really asking the hard hitting question chris]; a : [i think he was a lot of people who would have a better chance of the debate]\n", 403 | "q : [i was raised to always do that but honestly i think im done]; a : [that was so good]\n", 404 | "q : [think she slick aint no unk from this ass unk you got coming ]; a : [she told me to get a pic]\n", 405 | "q : [student 6 in critical condition after school shooting]; a : [maybe we need to get a better job for the debate]\n", 406 | "q : [you need promotion your music on soundcloud only unk promotion here more info in my twitter here prices unk]; a : [hey is the best thing ive seen it]\n", 407 | "q : [ash watch juan hes like actually unk and smiling too sweet]; a : [i know right]\n", 408 | "q : [thats good it was 2013 i think]; a : [and i was in the same place ]\n", 409 | "q : [ive came to the unk that sex really aint shit if you dont love the person]; a : [youre a joke]\n", 410 | "q : [when you want to laugh at americans for letting trump happen and then you remember unk and unk]; a : [who cares about this]\n", 411 | "q : [still make the same face]; a : [i dont even know what to do]\n", 412 | "q : [i think they played in on unk theater a few years back too]; a : [no i dont even know how to do it]\n", 413 | "q : [do it jess its protein that makes it okay]; a : [its not even a thing]\n", 414 | "q : [have a question for submit it below and she may answer it in the ]; a : [i dont think the same thing is the only one who would]\n", 415 | "q : [such a great honor final debate polls are in and the movement wins ]; a : [ we need to get rid of the debate]\n", 416 | "q : [some very promising unk 2 numbers for dropping only 02 from premiere to a 26 very decent hold]; a : [is it a great thing to be in the city]\n", 417 | "q : [lol im about to fire yall]; a : [im going to be a while fan ]\n", 418 | "q : [how can i come see you play tomorrow ]; a : [come to sf ]\n", 419 | "q : [take me back before the jump though unk]; a : [dont know what you mean about that shit lmao]\n", 420 | "q : [exactly also i would consider it a party and invite people over to watch unk unk actually play]; a : [its not a thing]\n", 421 | "q : [so glad you enjoyed it yes unk co unk dm me]; a : [glad i was there]\n", 422 | "q : [so i had to look it up unk and wig sold unk thats that bullshit right there]; a : [what is this]\n", 423 | "q : [in public space not on private unk these protesters are unk]; a : [i agree but the media is not a terrible choice]\n", 424 | "q : [wassup i got some rare shit unk have to bring the price up to 25 tho]; a : [i wish i could be there]\n", 425 | "q : [love watching unk too but almost feels painful to watch him pitch such unk]; a : [it was a good thing to be a good game]\n", 426 | "q : [ive never unk my sleep before but i think this is pretty alright]; a : [that is the most thing ive seen it]\n", 427 | "q : [unk and yourself have roughly the same level of credibility]; a : [what the fuck]\n", 428 | "q : [this should help him with women]; a : [did he get a good time to get a pic of him]\n", 429 | "q : [what the heck i just sent you a video link]; a : [i feel you so much i was gonna get a pic of my phone]\n", 430 | "q : [why you so perfect]; a : [i know i am so happy for you ]\n", 431 | "q : [unk someone block you again cause ur not supporting unk x xd]; a : [dont know what you mean ]\n", 432 | "q : [when you say black i take it you mean unk]; a : [who said that]\n", 433 | "q : [did you get tickets already]; a : [ i got to go to the airport]\n", 434 | "q : [you are such a unk all bullshit with no facts get over your stupid unk]; a : [you are a racist person who are you talking about your own business]\n", 435 | "q : [not sure what you meant by that]; a : [ i know right]\n" 436 | ] 437 | } 438 | ], 439 | "source": [ 440 | "replies = []\n", 441 | "for ii, oi in zip(input_.T, output):\n", 442 | " q = data_utils.decode(sequence=ii, lookup=metadata['idx2w'], separator=' ')\n", 443 | " decoded = data_utils.decode(sequence=oi, lookup=metadata['idx2w'], separator=' ').split(' ')\n", 444 | " if decoded.count('unk') == 0:\n", 445 | " if decoded not in replies:\n", 446 | " print('q : [{0}]; a : [{1}]'.format(q, ' '.join(decoded)))\n", 447 | " replies.append(decoded)" 448 | ] 449 | }, 450 | { 451 | "cell_type": "code", 452 | "execution_count": null, 453 | "metadata": { 454 | "collapsed": true 455 | }, 456 | "outputs": [], 457 | "source": [] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": null, 462 | "metadata": { 463 | "collapsed": true 464 | }, 465 | "outputs": [], 466 | "source": [] 467 | }, 468 | { 469 | "cell_type": "code", 470 | "execution_count": null, 471 | "metadata": { 472 | "collapsed": true 473 | }, 474 | "outputs": [], 475 | "source": [] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "metadata": { 481 | "collapsed": true 482 | }, 483 | "outputs": [], 484 | "source": [] 485 | }, 486 | { 487 | "cell_type": "code", 488 | "execution_count": null, 489 | "metadata": { 490 | "collapsed": true 491 | }, 492 | "outputs": [], 493 | "source": [] 494 | }, 495 | { 496 | "cell_type": "code", 497 | "execution_count": null, 498 | "metadata": { 499 | "collapsed": true 500 | }, 501 | "outputs": [], 502 | "source": [] 503 | } 504 | ], 505 | "metadata": { 506 | "kernelspec": { 507 | "display_name": "Python 3", 508 | "language": "python", 509 | "name": "python3" 510 | }, 511 | "language_info": { 512 | "codemirror_mode": { 513 | "name": "ipython", 514 | "version": 3 515 | }, 516 | "file_extension": ".py", 517 | "mimetype": "text/x-python", 518 | "name": "python", 519 | "nbconvert_exporter": "python", 520 | "pygments_lexer": "ipython3", 521 | "version": "3.5.2" 522 | } 523 | }, 524 | "nbformat": 4, 525 | "nbformat_minor": 0 526 | } 527 | -------------------------------------------------------------------------------- /03-Twitter-chatbot.py: -------------------------------------------------------------------------------- 1 | 2 | # In[1]: 3 | 4 | import tensorflow as tf 5 | import numpy as np 6 | 7 | # preprocessed data 8 | from datasets.twitter import data 9 | import data_utils 10 | 11 | # load data from pickle and npy files 12 | metadata, idx_q, idx_a = data.load_data(PATH='datasets/twitter/') 13 | (trainX, trainY), (testX, testY), (validX, validY) = data_utils.split_dataset(idx_q, idx_a) 14 | 15 | # parameters 16 | xseq_len = trainX.shape[-1] 17 | yseq_len = trainY.shape[-1] 18 | batch_size = 32 19 | xvocab_size = len(metadata['idx2w']) 20 | yvocab_size = xvocab_size 21 | emb_dim = 1024 22 | 23 | import seq2seq_wrapper 24 | 25 | # In[7]: 26 | 27 | model = seq2seq_wrapper.Seq2Seq(xseq_len=xseq_len, 28 | yseq_len=yseq_len, 29 | xvocab_size=xvocab_size, 30 | yvocab_size=yvocab_size, 31 | ckpt_path='ckpt/twitter/', 32 | emb_dim=emb_dim, 33 | num_layers=3 34 | ) 35 | 36 | 37 | # In[8]: 38 | 39 | val_batch_gen = data_utils.rand_batch_gen(validX, validY, 32) 40 | train_batch_gen = data_utils.rand_batch_gen(trainX, trainY, batch_size) 41 | 42 | 43 | # In[9]: 44 | sess = model.restore_last_session() 45 | sess = model.train(train_batch_gen, val_batch_gen) 46 | -------------------------------------------------------------------------------- /04-Cornell-Movie-Dialog-Bot.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Demonstrate Seq2Seq Wrapper with Cornell Movie Dialog Corpus" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": { 14 | "collapsed": true 15 | }, 16 | "outputs": [], 17 | "source": [ 18 | "import tensorflow as tf\n", 19 | "import numpy as np\n", 20 | "\n", 21 | "# preprocessed data\n", 22 | "from datasets.cornell_corpus import data\n", 23 | "import data_utils" 24 | ] 25 | }, 26 | { 27 | "cell_type": "code", 28 | "execution_count": 3, 29 | "metadata": { 30 | "collapsed": false 31 | }, 32 | "outputs": [ 33 | { 34 | "data": { 35 | "text/plain": [ 36 | "" 37 | ] 38 | }, 39 | "execution_count": 3, 40 | "metadata": {}, 41 | "output_type": "execute_result" 42 | } 43 | ], 44 | "source": [ 45 | "import importlib\n", 46 | "importlib.reload(data)" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 2, 52 | "metadata": { 53 | "collapsed": false 54 | }, 55 | "outputs": [], 56 | "source": [ 57 | "# load data from pickle and npy files\n", 58 | "metadata, idx_q, idx_a = data.load_data(PATH='datasets/cornell_corpus/')\n", 59 | "(trainX, trainY), (testX, testY), (validX, validY) = data_utils.split_dataset(idx_q, idx_a)" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 4, 65 | "metadata": { 66 | "collapsed": true 67 | }, 68 | "outputs": [], 69 | "source": [ 70 | "# parameters \n", 71 | "xseq_len = trainX.shape[-1]\n", 72 | "yseq_len = trainY.shape[-1]\n", 73 | "batch_size = 16\n", 74 | "xvocab_size = len(metadata['idx2w']) \n", 75 | "yvocab_size = xvocab_size\n", 76 | "emb_dim = 1024" 77 | ] 78 | }, 79 | { 80 | "cell_type": "code", 81 | "execution_count": 5, 82 | "metadata": { 83 | "collapsed": true 84 | }, 85 | "outputs": [], 86 | "source": [ 87 | "import seq2seq_wrapper" 88 | ] 89 | }, 90 | { 91 | "cell_type": "code", 92 | "execution_count": 6, 93 | "metadata": { 94 | "collapsed": false 95 | }, 96 | "outputs": [ 97 | { 98 | "name": "stdout", 99 | "output_type": "stream", 100 | "text": [ 101 | " Building Graph " 102 | ] 103 | } 104 | ], 105 | "source": [ 106 | "model = seq2seq_wrapper.Seq2Seq(xseq_len=xseq_len,\n", 107 | " yseq_len=yseq_len,\n", 108 | " xvocab_size=xvocab_size,\n", 109 | " yvocab_size=yvocab_size,\n", 110 | " ckpt_path='ckpt/cornell_corpus/',\n", 111 | " emb_dim=emb_dim,\n", 112 | " num_layers=3\n", 113 | " )" 114 | ] 115 | }, 116 | { 117 | "cell_type": "code", 118 | "execution_count": 7, 119 | "metadata": { 120 | "collapsed": true 121 | }, 122 | "outputs": [], 123 | "source": [ 124 | "val_batch_gen = data_utils.rand_batch_gen(validX, validY, 32)\n", 125 | "test_batch_gen = data_utils.rand_batch_gen(testX, testY, 256)\n", 126 | "train_batch_gen = data_utils.rand_batch_gen(trainX, trainY, batch_size)" 127 | ] 128 | }, 129 | { 130 | "cell_type": "code", 131 | "execution_count": 8, 132 | "metadata": { 133 | "collapsed": true 134 | }, 135 | "outputs": [], 136 | "source": [ 137 | "sess = model.restore_last_session()" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": 16, 143 | "metadata": { 144 | "collapsed": false 145 | }, 146 | "outputs": [ 147 | { 148 | "name": "stdout", 149 | "output_type": "stream", 150 | "text": [ 151 | "(256, 25)\n" 152 | ] 153 | } 154 | ], 155 | "source": [ 156 | "input_ = test_batch_gen.__next__()[0]\n", 157 | "output = model.predict(sess, input_)\n", 158 | "print(output.shape)" 159 | ] 160 | }, 161 | { 162 | "cell_type": "code", 163 | "execution_count": 17, 164 | "metadata": { 165 | "collapsed": false 166 | }, 167 | "outputs": [ 168 | { 169 | "name": "stdout", 170 | "output_type": "stream", 171 | "text": [ 172 | "q : [bill id like you to meet jack torrance]; a : [how much do you think]\n", 173 | "q : [and who are you to talk you were nothing you couldnt even sing i must have been out of my mind]; a : [i dont know what youre talking about]\n", 174 | "q : [by breaking up a companys assets]; a : [what are you talking about]\n", 175 | "q : [what is it]; a : [i dont know]\n", 176 | "q : [ill see you there]; a : [ill get out]\n", 177 | "q : [okay ill be talking to you]; a : [youre not going to get out]\n", 178 | "q : [i must be outta my mind buddy quit it]; a : [okay for a minute]\n", 179 | "q : [when are you going to let the police know]; a : [you dont know what youre talking about]\n", 180 | "q : [you can do it]; a : [yeah i think so]\n", 181 | "q : [like hell you know if you fellows stuck together stead of letting them walk all over you they might not try it]; a : [if you werent talking about me i dont know what youre talking about]\n", 182 | "q : [wait are you saying that i dont appreciate]; a : [i know you know what i mean]\n", 183 | "q : [no you just looked as if you did]; a : [well i didnt believe you]\n", 184 | "q : [youre terrible]; a : [yeah but im not]\n", 185 | "q : [you would take a pain n the arse full stop]; a : [dont worry about it]\n", 186 | "q : [yeah howd the kid hold up]; a : [whats that]\n", 187 | "q : [yes well miss ratched feels that youre a disturbing influence on the other patients]; a : [dont you tell me]\n", 188 | "q : [you leading a squad]; a : [what is it]\n", 189 | "q : [nah i dont think so]; a : [why not]\n", 190 | "q : [hes pissing in our faces again and were just taking it]; a : [i cant]\n", 191 | "q : [my lady]; a : [she said you were a little girl]\n", 192 | "q : [im sorry i dont know what else to say except im sorry]; a : [why would you like to be]\n", 193 | "q : [mr brandon couldnt be here he might have left something for you what would it look like]; a : [thats it i think i can get it out]\n", 194 | "q : [nobodys gonna get you now get inside]; a : [i cant go back]\n", 195 | "q : [i just turned 25 i was 24 for a whole year]; a : [well i dont think so]\n", 196 | "q : [make sure he doesnt leave]; a : [you sure]\n", 197 | "q : [do we need him]; a : [i dont know what to do]\n", 198 | "q : [youre terry unk arent you]; a : [what are you doing here]\n", 199 | "q : [so lets go]; a : [i dont think so]\n", 200 | "q : [ya owe me twentyfive bucks]; a : [its a good man]\n", 201 | "q : [shall i leave]; a : [of course]\n", 202 | "q : [unk unk probably asleep by now do you want him to see you like this]; a : [no way i dont want to get out of here]\n", 203 | "q : [well i really think hes got a chance]; a : [i know]\n", 204 | "q : [youd better be quiet sandy]; a : [shut up]\n", 205 | "q : [buddy that was pretty unk of you pushing me away like that just when it was interesting]; a : [what about you]\n", 206 | "q : [jesus christ you scared the shit out of me]; a : [whats going on]\n", 207 | "q : [well im sorry im really sorry ellie]; a : [its okay]\n", 208 | "q : [youre not a man because of a job duff]; a : [but i said that]\n", 209 | "q : [he didnt lose her he threw her away]; a : [hes not dead]\n", 210 | "q : [you unk have the gotta]; a : [what the hell are you talking about]\n", 211 | "q : [whoa whoa what do you expect them to say youre alan unk]; a : [im sorry i dont know]\n", 212 | "q : [doc what can i tell ya]; a : [go ahead]\n", 213 | "q : [my lady this play will end badly i will tell]; a : [lets get out of here]\n", 214 | "q : [what if i said goodbye]; a : [then why are you]\n", 215 | "q : [im going to miss you]; a : [no youre not]\n", 216 | "q : [well wed love to but were going to another party]; a : [what do you mean]\n", 217 | "q : [dog eat dog unk you fuck other man before he fuck you and you must fuck last]; a : [what do you think we can do]\n", 218 | "q : [not in the trunk]; a : [what about]\n", 219 | "q : [can we light the candles now on the cake]; a : [you want to go home]\n", 220 | "q : [you look frightened have i been saying something frightening]; a : [i dont know what you mean]\n", 221 | "q : [you want to hear the good news first or the bad news]; a : [what the hell is that]\n", 222 | "q : [ya gotta be a little soft to wanna be a unk its a racket where ya almost guaranteed to end up a bum]; a : [all right]\n", 223 | "q : [you werent going with her]; a : [well shes not a little girl]\n", 224 | "q : [i dont want land]; a : [you dont have to be a good man]\n", 225 | "q : [what do you want from me cotton]; a : [we dont know what youre talking about]\n", 226 | "q : [the hopes are perfect beautiful identical smooth and they are for something really amazing i feel it in my bones]; a : [youre not a fool]\n", 227 | "q : [get married]; a : [what do you think]\n", 228 | "q : [ha dear boy i do hope this doesnt unk a meeting in private]; a : [ill get out of here]\n", 229 | "q : [karl you up]; a : [yeah im not going to get out of here]\n", 230 | "q : [i just realized this is for television isnt it i cant swear up and down like i just did]; a : [its not that you know what youre talking about]\n", 231 | "q : [yes george]; a : [and what do you want]\n", 232 | "q : [hey eddie looks like you really stepped in it this time]; a : [thats right i dont know]\n", 233 | "q : [you dont want to go all the way to san francisco in a unk do you i dont]; a : [im not sure]\n", 234 | "q : [it can happen so sudden cant it being left out on your own]; a : [its not a good idea]\n", 235 | "q : [what do you mean]; a : [i dont know i dont know what i mean]\n", 236 | "q : [i want to]; a : [you want to go]\n", 237 | "q : [what do you want take my wife please]; a : [well i dont know what to do]\n", 238 | "q : [look at this the lock is totally unk]; a : [you know what it is]\n", 239 | "q : [he wont steal im tellin you hes a pretty good ol boy keeps to himself]; a : [thats right]\n", 240 | "q : [youre really pushing it bringing me here]; a : [what do you want me to do]\n", 241 | "q : [im not unk with armitage and his unk breathing down my neck]; a : [you mean you dont want to go]\n", 242 | "q : [my god these people are insane]; a : [we dont know what they are]\n", 243 | "q : [no it wasnt like that]; a : [yes you did]\n", 244 | "q : [dont you worry about that]; a : [dont worry about me]\n", 245 | "q : [well i just kept unk that dish maybe it doesnt sound very sexy but it was]; a : [yeah i dont know]\n", 246 | "q : [hey vaughan how are you karl]; a : [im fine]\n", 247 | "q : [this isnt your room youre in unk i fucked up]; a : [im sorry i dont know what to do]\n", 248 | "q : [r was worried about you you didnt even call youre always on my case if i dont call]; a : [i know you dont know what youre talking about]\n", 249 | "q : [something happened you got unk in the last quarter]; a : [what do you want to do]\n", 250 | "q : [if youre going to be unk i wish youd be a little more discreet about it rich men like unk love you and leave you]; a : [thats not what i mean]\n", 251 | "q : [how long would they let me sleep]; a : [i dont know i dont know what to do]\n", 252 | "q : [whats got billy so unk]; a : [i dont know what to do with it]\n", 253 | "q : [you fucking bastard]; a : [come on]\n", 254 | "q : [she used to call me mr right remember that buddy]; a : [how are you going to do]\n", 255 | "q : [my unk in miami its nice down there]; a : [thats what i said]\n", 256 | "q : [speak with my lawyer]; a : [you dont know what you mean]\n", 257 | "q : [mr unk because you love the theatre you must have a part in my play i am writing an unk a small but vital role]; a : [thats right i dont think so]\n", 258 | "q : [of course you dont know anything about it if you knew anything about it i wouldnt have to send you over there to cover it]; a : [thats not what you want]\n", 259 | "q : [does mom know]; a : [she said she was in love]\n", 260 | "q : [its okay tatum shes just doing her job right gale]; a : [shes not going to see her]\n", 261 | "q : [wanna keep goin]; a : [im sorry]\n", 262 | "q : [i thought so too unk a neat guy]; a : [hey i dont know what youre doing to do with it]\n", 263 | "q : [did i wake you]; a : [no you dont]\n", 264 | "q : [how could you do this]; a : [well i dont know what i mean]\n", 265 | "q : [that can wait till the weekend]; a : [are you kidding]\n", 266 | "q : [if you cant look anymore i understand]; a : [im not going to tell you that]\n", 267 | "q : [maybe i can change him]; a : [then he doesnt know what he is]\n", 268 | "q : [maybe if i kiss him ill feel it]; a : [then you should have to]\n", 269 | "q : [well youre a little early]; a : [i dont know what youre doing to get out of here]\n", 270 | "q : [i thought michael was picking me up]; a : [dont worry about it im not going to get out of here]\n", 271 | "q : [i dont believe he did sir i couldnt find a single track just doesnt make sense]; a : [shut up what do you mean]\n", 272 | "q : [he said that]; a : [he was here]\n", 273 | "q : [its unk unk the name of the character she plays in the movie]; a : [i know what i mean]\n", 274 | "q : [hes company]; a : [hes not going to see him]\n", 275 | "q : [youre so proud youre like some retarded kid comin home from school look dad i got an f]; a : [thats right thats what you want to do]\n", 276 | "q : [feels like theres a bullet still in my chest]; a : [right for me]\n", 277 | "q : [not now charlie ive got a headache get used to the word roll it around your tongue for a years]; a : [its the time i dont know what to do]\n", 278 | "q : [and the bookstore have you been working there long]; a : [i think so]\n", 279 | "q : [you sent for me]; a : [yes yes i am]\n", 280 | "q : [damour damour why do i know that name]; a : [well i dont know]\n", 281 | "q : [speaking of which you run that license plate for me]; a : [i cant believe you]\n", 282 | "q : [i dont know unk a unk]; a : [you know what i mean]\n", 283 | "q : [how shes even forgot her own language]; a : [long night she was a very nice person]\n", 284 | "q : [just that she got away]; a : [well i think so]\n", 285 | "q : [anything i dont care what it is just so its something]; a : [its not that i dont know]\n", 286 | "q : [at this hour]; a : [no problem]\n", 287 | "q : [i swear it he wants romeo for ned and the unk men]; a : [and how much do you think]\n", 288 | "q : [oh really i thought it was pretty good]; a : [its a good idea]\n", 289 | "q : [look fry company says were responsible for every one of those]; a : [dont be silly]\n", 290 | "q : [laser unk you cant get the code wrong it unk you i cant let you try it]; a : [ill take care of you]\n", 291 | "q : [what if we were to put bruce into the park as a guest]; a : [dont worry ill be fine if you want to get out of here]\n", 292 | "q : [could be]; a : [but what do you think]\n", 293 | "q : [i dont know i cant say]; a : [then what did you do]\n" 294 | ] 295 | } 296 | ], 297 | "source": [ 298 | "replies = []\n", 299 | "for ii, oi in zip(input_.T, output):\n", 300 | " q = data_utils.decode(sequence=ii, lookup=metadata['idx2w'], separator=' ')\n", 301 | " decoded = data_utils.decode(sequence=oi, lookup=metadata['idx2w'], separator=' ').split(' ')\n", 302 | " if decoded.count('unk') == 0:\n", 303 | " if decoded not in replies:\n", 304 | " print('q : [{0}]; a : [{1}]'.format(q, ' '.join(decoded)))\n", 305 | " replies.append(decoded)" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": null, 311 | "metadata": { 312 | "collapsed": true 313 | }, 314 | "outputs": [], 315 | "source": [] 316 | } 317 | ], 318 | "metadata": { 319 | "kernelspec": { 320 | "display_name": "Python 3", 321 | "language": "python", 322 | "name": "python3" 323 | }, 324 | "language_info": { 325 | "codemirror_mode": { 326 | "name": "ipython", 327 | "version": 3 328 | }, 329 | "file_extension": ".py", 330 | "mimetype": "text/x-python", 331 | "name": "python", 332 | "nbconvert_exporter": "python", 333 | "pygments_lexer": "ipython3", 334 | "version": "3.5.2" 335 | } 336 | }, 337 | "nbformat": 4, 338 | "nbformat_minor": 0 339 | } 340 | -------------------------------------------------------------------------------- /04-Cornell-Movie-Dialog-Bot.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | 4 | # preprocessed data 5 | from datasets.cornell_corpus import data 6 | import data_utils 7 | 8 | # load data from pickle and npy files 9 | metadata, idx_q, idx_a = data.load_data(PATH='datasets/cornell_corpus/') 10 | (trainX, trainY), (testX, testY), (validX, validY) = data_utils.split_dataset(idx_q, idx_a) 11 | 12 | # parameters 13 | xseq_len = trainX.shape[-1] 14 | yseq_len = trainY.shape[-1] 15 | batch_size = 32 16 | xvocab_size = len(metadata['idx2w']) 17 | yvocab_size = xvocab_size 18 | emb_dim = 1024 19 | 20 | import seq2seq_wrapper 21 | 22 | # In[7]: 23 | 24 | model = seq2seq_wrapper.Seq2Seq(xseq_len=xseq_len, 25 | yseq_len=yseq_len, 26 | xvocab_size=xvocab_size, 27 | yvocab_size=yvocab_size, 28 | ckpt_path='ckpt/cornell_corpus/', 29 | emb_dim=emb_dim, 30 | num_layers=3 31 | ) 32 | 33 | 34 | # In[8]: 35 | 36 | val_batch_gen = data_utils.rand_batch_gen(validX, validY, 32) 37 | train_batch_gen = data_utils.rand_batch_gen(trainX, trainY, batch_size) 38 | 39 | 40 | # In[9]: 41 | #sess = model.restore_last_session() 42 | sess = model.train(train_batch_gen, val_batch_gen) 43 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | # Seq2Seq Wrapper for Tensorflow 2 | 3 | ![](https://img.shields.io/badge/python-3-brightgreen.svg) ![](https://img.shields.io/badge/tensorflow-0.12.0-yellowgreen.svg) 4 | 5 | To make life easier for beginners looking to experiment with seq2seq model. Read the article I wrote on seq2seq - [**Practical seq2seq**](http://suriyadeepan.github.io/2016-12-31-practical-seq2seq/), for more details. 6 | 7 | 8 | ## Datasets 9 | 10 | - [x] [CMU Pronouncing Dictionary](https://github.com/suriyadeepan/datasets/tree/master/seq2seq/CMUdict) : Phoneme sequence to word (sequence of alphabets) 11 | ![](/img/phoneme.png) 12 | 13 | _______________________________________________________________ 14 | 15 | - [x] [Twitter Chat Log](https://github.com/suriyadeepan/datasets/tree/master/seq2seq/twitter) : Sentence to Sentence 16 | 17 | ![](/img/twitter01.png) 18 | ![](/img/twitter02.png) 19 | 20 | **Update** 21 | 22 | After tweaking the dataset to bring down the overall % of unknown tokens to 3%, increasing vocabulary to 8000, the [results](https://gist.github.com/suriyadeepan/5d4aaf96c7bd89b908921804c683fee8) are promising. 23 | 24 | | Query | Reply | 25 | | ------------- | ------------- | 26 | | donald trump won last nights presidential debate according to snap online polls | thought he was a joke | 27 | | trump campaign please never delete this | he was a joke | 28 | | s new scoop is unk the castro connection how trumps company violated the us embargo against cuba | trump is a disgrace to the debate and the media is not a liar | 29 | | who won the first presidential debate | trump will be a better time for a man | 30 | | just wanna live in unk everything is 10x better there | i was just on the same side and i was like it was a good time | 31 | | the lil girl i forgot her name scares the shit out of me n probably always will lmaooo | she was so cute and she was so cute and she was a bitch | 32 | | question of the day who do you think won last nights debate weigh in using | hillary is a trump supporter and a woman who has a better job than a woman | 33 | | trump is a total embarrassment hes like a unk child who happens to be a professional liar and con man | trump is a lot of money to get a great country | 34 | | chill the fuck out | thats what i said | 35 | | so fun to see what the special effects team created for | wow that is the best thing ive ever seen | 36 | | she was fine too unk voice | she is a good guy | 37 | | the important ones are still here | i dont think so | 38 | | been drinking pumpkin spice protein shake every morning for a week and now i literally cannot even | me too i just got it | 39 | | lmao i just lost my job and i cant even leave early to be in the unk video today | literally the same thing | 40 | | hey happy birthday have a nice day | thank you | 41 | 42 | _______________________________________________________________ 43 | 44 | - [x] [Cornell Movie Dialog Corpus](https://github.com/suriyadeepan/datasets/tree/master/seq2seq/cornell_movie_corpus) 45 | 46 | \~4% unknown tokens in dataset; vocabulary of 8000. 47 | 48 | | Query | Reply | 49 | | ------------- | ------------- | 50 | | when are you going to let the police know | you dont know what youre talking about | 51 | | you can do it | yeah i think so | 52 | | wait are you saying that i dont appreciate | i know you know what i mean | 53 | | youre terrible | yeah but im not | 54 | | nah i dont think so | why not | 55 | | hes pissing in our faces again and were just taking it | i cant | 56 | | im sorry i dont know what else to say except im sorry | why would you like to be | 57 | | nobodys gonna get you now get inside | i cant go back | 58 | | shall i leave | of course | 59 | | well i really think hes got a chance | i know | 60 | | youd better be quiet sandy | shut up | 61 | | jesus christ you scared the shit out of me | whats going on | 62 | | well im sorry im really sorry ellie | its okay | 63 | | my lady this play will end badly i will tell | lets get out of here | 64 | | im going to miss you | no youre not | 65 | | what do you mean | i dont know i dont know what i mean | 66 | | my god these people are insane | we dont know what they are | 67 | | this isnt a date | no what is it | 68 | | you ought to go home and take care of that | i cant do that | 69 | | is something wrong | no no no | 70 | 71 | 72 | ## Credits 73 | 74 | - Borrowed most of the code for [seq2seq_wrapper.py](/seq2seq_wrapper.py) from [mikesj-public](https://github.com/mikesj-public/rnn_spelling_bee/blob/master/spelling_bee_RNN.ipynb) 75 | - Borrowed the twitter dataset from this dude [Marsan-Ma](https://github.com/Marsan-Ma/) 76 | -------------------------------------------------------------------------------- /ckpt/cmudict/pull: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget -c 'https://www.dropbox.com/s/qfm0ugb9m3laenf/cmudict_ckpt.tar.gz?dl=0' -O cmudict_ckpt.tar.gz 4 | -------------------------------------------------------------------------------- /ckpt/twitter/pull: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget -c 'https://www.dropbox.com/s/vwu9if99rvv4dab/seq2seq_twitter_1024x3h_i43000.tar.gz?dl=0' -O seq2seq_twitter_1024x3h_i43000.tar.gz 4 | -------------------------------------------------------------------------------- /data_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from random import sample 3 | 4 | ''' 5 | split data into train (70%), test (15%) and valid(15%) 6 | return tuple( (trainX, trainY), (testX,testY), (validX,validY) ) 7 | 8 | ''' 9 | def split_dataset(x, y, ratio = [0.7, 0.15, 0.15] ): 10 | # number of examples 11 | data_len = len(x) 12 | lens = [ int(data_len*item) for item in ratio ] 13 | 14 | trainX, trainY = x[:lens[0]], y[:lens[0]] 15 | testX, testY = x[lens[0]:lens[0]+lens[1]], y[lens[0]:lens[0]+lens[1]] 16 | validX, validY = x[-lens[-1]:], y[-lens[-1]:] 17 | 18 | return (trainX,trainY), (testX,testY), (validX,validY) 19 | 20 | 21 | ''' 22 | generate batches from dataset 23 | yield (x_gen, y_gen) 24 | 25 | TODO : fix needed 26 | 27 | ''' 28 | def batch_gen(x, y, batch_size): 29 | # infinite while 30 | while True: 31 | for i in range(0, len(x), batch_size): 32 | if (i+1)*batch_size < len(x): 33 | yield x[i : (i+1)*batch_size ].T, y[i : (i+1)*batch_size ].T 34 | 35 | ''' 36 | generate batches, by random sampling a bunch of items 37 | yield (x_gen, y_gen) 38 | 39 | ''' 40 | def rand_batch_gen(x, y, batch_size): 41 | while True: 42 | sample_idx = sample(list(np.arange(len(x))), batch_size) 43 | yield x[sample_idx].T, y[sample_idx].T 44 | 45 | #''' 46 | # convert indices of alphabets into a string (word) 47 | # return str(word) 48 | # 49 | #''' 50 | #def decode_word(alpha_seq, idx2alpha): 51 | # return ''.join([ idx2alpha[alpha] for alpha in alpha_seq if alpha ]) 52 | # 53 | # 54 | #''' 55 | # convert indices of phonemes into list of phonemes (as string) 56 | # return str(phoneme_list) 57 | # 58 | #''' 59 | #def decode_phonemes(pho_seq, idx2pho): 60 | # return ' '.join( [ idx2pho[pho] for pho in pho_seq if pho ]) 61 | 62 | 63 | ''' 64 | a generic decode function 65 | inputs : sequence, lookup 66 | 67 | ''' 68 | def decode(sequence, lookup, separator=''): # 0 used for padding, is ignored 69 | return separator.join([ lookup[element] for element in sequence if element ]) 70 | -------------------------------------------------------------------------------- /datasets/cmudict/cmudict-processed.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/datasets/cmudict/cmudict-processed.tar.gz -------------------------------------------------------------------------------- /datasets/cmudict/data.py: -------------------------------------------------------------------------------- 1 | START_LINE = 126 2 | END_LINE = 133905 3 | FILENAME = 'data/cmudict-0.7b' 4 | ALPHA = '_abcdefghijklmnopqrstuvwxyz' 5 | 6 | limit = { 7 | 'maxw' : 16, 8 | 'minw' : 5, 9 | 'maxph' : 16, 10 | 'minph' : 5 11 | } 12 | 13 | import random 14 | import numpy as np 15 | import pickle 16 | 17 | 18 | ''' 19 | read lines from file 20 | return [list of lines] 21 | 22 | ''' 23 | def read_line(filename=FILENAME): 24 | return open(filename, 'r', encoding='utf-8', errors='ignore').read().split('\n')[START_LINE:END_LINE] 25 | 26 | 27 | ''' 28 | separate lines into lines of words and pronunciation 29 | return tuple( [words], [phoneme lists] ) 30 | 31 | ''' 32 | def split_data(lines): 33 | 34 | words, phoneme_lists = [], [] 35 | for line in lines: 36 | word, phonemes = line.split(' ') 37 | phoneme_lists.append(phonemes.split(' ')) 38 | words.append(word.lower()) 39 | return words, phoneme_lists 40 | 41 | 42 | ''' 43 | read the phoneme_lists, create index to phoneme, 44 | phoneme to index dictionaries 45 | return tuple( idx2pho, pho2idx ) 46 | 47 | ''' 48 | def index_phonemes(phoneme_lists): 49 | phoneme_vocab = set([phoneme for phonemes in phoneme_lists 50 | for phoneme in phonemes]) 51 | idx2pho = dict(enumerate(['_'] + sorted(list(phoneme_vocab)))) 52 | # we add an extra dummy element to make sure 53 | # we dont touch the zero index (zero padding) 54 | pho2idx = dict(zip(idx2pho.values(), idx2pho.keys())) 55 | return idx2pho, pho2idx 56 | 57 | 58 | ''' 59 | generate index english alphabets 60 | return tuple( idx2alpha, alpha2idx ) 61 | 62 | ''' 63 | def index_alphabets(alpha = ALPHA): 64 | idx2alpha = dict(enumerate(alpha)) 65 | alpha2idx = dict(zip(idx2alpha.values(), idx2alpha.keys())) 66 | return idx2alpha, alpha2idx 67 | 68 | 69 | ''' 70 | filter too long and too short sequences 71 | return tuple( filtered_words, filtered_phoneme_lists ) 72 | 73 | ''' 74 | def filter_data(words, phoneme_lists): 75 | # need a threshold 76 | # say max : 16, 16 77 | # min : 5, 5 78 | ''' 79 | limit = { 80 | 'maxw' : 16, 81 | 'minw' : 5, 82 | 'maxph' : 16, 83 | 'minph' : 5 84 | } 85 | ''' 86 | 87 | # also make sure, every character in words is an alphabet 88 | # if not, skip the row 89 | filtered_words, filtered_phoneme_lists = [], [] 90 | raw_data_len = len(words) 91 | for word, phonemes in zip(words, phoneme_lists): 92 | if word.isalpha(): 93 | if len(word) < limit['maxw'] and len(word) > limit['minw']: 94 | if len(phonemes) < limit['maxph'] and len(phonemes) > limit['minph']: 95 | filtered_words.append(word) 96 | filtered_phoneme_lists.append(phonemes) 97 | 98 | # print the fraction of the original data, filtered 99 | filt_data_len = len(filtered_words) 100 | filtered = int((raw_data_len - filt_data_len)*100/raw_data_len) 101 | print(str(filtered) + '% filtered from original data') 102 | 103 | return filtered_words, filtered_phoneme_lists 104 | 105 | 106 | ''' 107 | create the final dataset : 108 | - convert list of items to arrays of indices 109 | - add zero padding 110 | return ( [array_words([indices]), array_phonemes([indices]) ) 111 | 112 | ''' 113 | def zero_pad(words, phoneme_lists, alpha2idx, pho2idx): 114 | # num of rows 115 | data_len = len(words) 116 | idx_words = np.zeros([data_len, limit['maxw']], dtype=np.int32) 117 | idx_phonemes = np.zeros([data_len, limit['maxph']], dtype=np.int32) 118 | 119 | for i in range(data_len): 120 | #print(words[i], phoneme_lists[i], i) 121 | word_indices = [ alpha2idx[alpha] for alpha in words[i] ] \ 122 | + [0]*(limit['maxw'] - len(words[i])) 123 | pho_indices = [ pho2idx[phoneme] for phoneme in phoneme_lists[i] ] \ 124 | + [0]*(limit['maxph'] - len(phoneme_lists[i])) 125 | 126 | idx_words[i] = np.array(word_indices) 127 | idx_phonemes[i] = np.array(pho_indices) 128 | 129 | return idx_words, idx_phonemes 130 | 131 | 132 | def process_data(): 133 | 134 | print('>> Read from file') 135 | lines = read_line() 136 | print('\n:: random.choice(lines)') 137 | print(random.choice(lines)) 138 | print(random.choice(lines)) 139 | 140 | print('\n>> Separate data') 141 | # shuffle data 142 | random.shuffle(lines) 143 | # separate into words and phoneme lists 144 | words, phoneme_lists = split_data(lines) 145 | print('\n:: random.choice(words)') 146 | print(random.choice(words)) 147 | print(random.choice(words)) 148 | print('\n:: random.choice(phoneme_lists)') 149 | print(random.choice(phoneme_lists)) 150 | print(random.choice(phoneme_lists)) 151 | 152 | print('\n>> Index phonemes') 153 | idx2pho, pho2idx = index_phonemes(phoneme_lists) 154 | print('\n:: random.choice(idx2pho)') 155 | print(idx2pho[random.choice(list(idx2pho.keys()))]) 156 | print(idx2pho[random.choice(list(idx2pho.keys()))]) 157 | print('\n:: random.choice(pho2idx)') 158 | print(pho2idx[random.choice(list(pho2idx.keys()))]) 159 | print(pho2idx[random.choice(list(pho2idx.keys()))]) 160 | 161 | # index alphabets 162 | idx2alpha, alpha2idx = index_alphabets() 163 | 164 | print('\n>> Filter data') 165 | words, phoneme_lists = filter_data(words, phoneme_lists) 166 | 167 | # we know the maximum length of both sequences : 15 168 | # we should create zero-padded numpy arrays 169 | idx_words, idx_phonemes = zero_pad(words, phoneme_lists, alpha2idx, pho2idx) 170 | # save them 171 | np.save('idx_words.npy', idx_words) 172 | np.save('idx_phonemes.npy', idx_phonemes) 173 | 174 | # let us now save the necessary dictionaries 175 | data_ctl = { 176 | 'idx2alpha' : idx2alpha, 177 | 'idx2pho' : idx2pho, 178 | 'pho2idx' : pho2idx, 179 | 'alpha2idx' : alpha2idx, 180 | 'limit' : limit 181 | } 182 | # write to disk : data control dictionaries 183 | with open('data_ctl.pkl', 'wb') as f: 184 | pickle.dump(data_ctl, f) 185 | 186 | 187 | def load_data(PATH=''): 188 | # read data control dictionaries 189 | with open(PATH + 'data_ctl.pkl', 'rb') as f: 190 | data_ctl = pickle.load(f) 191 | # read numpy arrays 192 | idx_words = np.load(PATH + 'idx_words.npy') 193 | idx_phonemes = np.load(PATH + 'idx_phonemes.npy') 194 | return data_ctl, idx_words, idx_phonemes 195 | 196 | 197 | 198 | if __name__ == '__main__': 199 | process_data() 200 | -------------------------------------------------------------------------------- /datasets/cmudict/data_ctl.pkl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/datasets/cmudict/data_ctl.pkl -------------------------------------------------------------------------------- /datasets/cornell_corpus/data.py: -------------------------------------------------------------------------------- 1 | EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in whitelist 2 | EN_BLACKLIST = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\'' 3 | 4 | limit = { 5 | 'maxq' : 25, 6 | 'minq' : 2, 7 | 'maxa' : 25, 8 | 'mina' : 2 9 | } 10 | 11 | UNK = 'unk' 12 | VOCAB_SIZE = 8000 13 | 14 | 15 | import random 16 | 17 | import nltk 18 | import itertools 19 | from collections import defaultdict 20 | 21 | import numpy as np 22 | 23 | import pickle 24 | 25 | 26 | 27 | ''' 28 | 1. Read from 'movie-lines.txt' 29 | 2. Create a dictionary with ( key = line_id, value = text ) 30 | ''' 31 | def get_id2line(): 32 | lines=open('raw_data/movie_lines.txt', encoding='utf-8', errors='ignore').read().split('\n') 33 | id2line = {} 34 | for line in lines: 35 | _line = line.split(' +++$+++ ') 36 | if len(_line) == 5: 37 | id2line[_line[0]] = _line[4] 38 | return id2line 39 | 40 | ''' 41 | 1. Read from 'movie_conversations.txt' 42 | 2. Create a list of [list of line_id's] 43 | ''' 44 | def get_conversations(): 45 | conv_lines = open('raw_data/movie_conversations.txt', encoding='utf-8', errors='ignore').read().split('\n') 46 | convs = [ ] 47 | for line in conv_lines[:-1]: 48 | _line = line.split(' +++$+++ ')[-1][1:-1].replace("'","").replace(" ","") 49 | convs.append(_line.split(',')) 50 | return convs 51 | 52 | ''' 53 | 1. Get each conversation 54 | 2. Get each line from conversation 55 | 3. Save each conversation to file 56 | ''' 57 | def extract_conversations(convs,id2line,path=''): 58 | idx = 0 59 | for conv in convs: 60 | f_conv = open(path + str(idx)+'.txt', 'w') 61 | for line_id in conv: 62 | f_conv.write(id2line[line_id]) 63 | f_conv.write('\n') 64 | f_conv.close() 65 | idx += 1 66 | 67 | ''' 68 | Get lists of all conversations as Questions and Answers 69 | 1. [questions] 70 | 2. [answers] 71 | ''' 72 | def gather_dataset(convs, id2line): 73 | questions = []; answers = [] 74 | 75 | for conv in convs: 76 | if len(conv) %2 != 0: 77 | conv = conv[:-1] 78 | for i in range(len(conv)): 79 | if i%2 == 0: 80 | questions.append(id2line[conv[i]]) 81 | else: 82 | answers.append(id2line[conv[i]]) 83 | 84 | return questions, answers 85 | 86 | 87 | ''' 88 | We need 4 files 89 | 1. train.enc : Encoder input for training 90 | 2. train.dec : Decoder input for training 91 | 3. test.enc : Encoder input for testing 92 | 4. test.dec : Decoder input for testing 93 | ''' 94 | def prepare_seq2seq_files(questions, answers, path='',TESTSET_SIZE = 30000): 95 | 96 | # open files 97 | train_enc = open(path + 'train.enc','w') 98 | train_dec = open(path + 'train.dec','w') 99 | test_enc = open(path + 'test.enc', 'w') 100 | test_dec = open(path + 'test.dec', 'w') 101 | 102 | # choose 30,000 (TESTSET_SIZE) items to put into testset 103 | test_ids = random.sample([i for i in range(len(questions))],TESTSET_SIZE) 104 | 105 | for i in range(len(questions)): 106 | if i in test_ids: 107 | test_enc.write(questions[i]+'\n') 108 | test_dec.write(answers[i]+ '\n' ) 109 | else: 110 | train_enc.write(questions[i]+'\n') 111 | train_dec.write(answers[i]+ '\n' ) 112 | if i%10000 == 0: 113 | print('\n>> written {} lines'.format(i)) 114 | 115 | # close files 116 | train_enc.close() 117 | train_dec.close() 118 | test_enc.close() 119 | test_dec.close() 120 | 121 | 122 | 123 | ''' 124 | remove anything that isn't in the vocabulary 125 | return str(pure en) 126 | 127 | ''' 128 | def filter_line(line, whitelist): 129 | return ''.join([ ch for ch in line if ch in whitelist ]) 130 | 131 | 132 | 133 | ''' 134 | filter too long and too short sequences 135 | return tuple( filtered_ta, filtered_en ) 136 | 137 | ''' 138 | def filter_data(qseq, aseq): 139 | filtered_q, filtered_a = [], [] 140 | raw_data_len = len(qseq) 141 | 142 | assert len(qseq) == len(aseq) 143 | 144 | for i in range(raw_data_len): 145 | qlen, alen = len(qseq[i].split(' ')), len(aseq[i].split(' ')) 146 | if qlen >= limit['minq'] and qlen <= limit['maxq']: 147 | if alen >= limit['mina'] and alen <= limit['maxa']: 148 | filtered_q.append(qseq[i]) 149 | filtered_a.append(aseq[i]) 150 | 151 | # print the fraction of the original data, filtered 152 | filt_data_len = len(filtered_q) 153 | filtered = int((raw_data_len - filt_data_len)*100/raw_data_len) 154 | print(str(filtered) + '% filtered from original data') 155 | 156 | return filtered_q, filtered_a 157 | 158 | 159 | ''' 160 | read list of words, create index to word, 161 | word to index dictionaries 162 | return tuple( vocab->(word, count), idx2w, w2idx ) 163 | 164 | ''' 165 | def index_(tokenized_sentences, vocab_size): 166 | # get frequency distribution 167 | freq_dist = nltk.FreqDist(itertools.chain(*tokenized_sentences)) 168 | # get vocabulary of 'vocab_size' most used words 169 | vocab = freq_dist.most_common(vocab_size) 170 | # index2word 171 | index2word = ['_'] + [UNK] + [ x[0] for x in vocab ] 172 | # word2index 173 | word2index = dict([(w,i) for i,w in enumerate(index2word)] ) 174 | return index2word, word2index, freq_dist 175 | 176 | ''' 177 | filter based on number of unknowns (words not in vocabulary) 178 | filter out the worst sentences 179 | 180 | ''' 181 | def filter_unk(qtokenized, atokenized, w2idx): 182 | data_len = len(qtokenized) 183 | 184 | filtered_q, filtered_a = [], [] 185 | 186 | for qline, aline in zip(qtokenized, atokenized): 187 | unk_count_q = len([ w for w in qline if w not in w2idx ]) 188 | unk_count_a = len([ w for w in aline if w not in w2idx ]) 189 | if unk_count_a <= 2: 190 | if unk_count_q > 0: 191 | if unk_count_q/len(qline) > 0.2: 192 | pass 193 | filtered_q.append(qline) 194 | filtered_a.append(aline) 195 | 196 | # print the fraction of the original data, filtered 197 | filt_data_len = len(filtered_q) 198 | filtered = int((data_len - filt_data_len)*100/data_len) 199 | print(str(filtered) + '% filtered from original data') 200 | 201 | return filtered_q, filtered_a 202 | 203 | 204 | 205 | 206 | ''' 207 | create the final dataset : 208 | - convert list of items to arrays of indices 209 | - add zero padding 210 | return ( [array_en([indices]), array_ta([indices]) ) 211 | 212 | ''' 213 | def zero_pad(qtokenized, atokenized, w2idx): 214 | # num of rows 215 | data_len = len(qtokenized) 216 | 217 | # numpy arrays to store indices 218 | idx_q = np.zeros([data_len, limit['maxq']], dtype=np.int32) 219 | idx_a = np.zeros([data_len, limit['maxa']], dtype=np.int32) 220 | 221 | for i in range(data_len): 222 | q_indices = pad_seq(qtokenized[i], w2idx, limit['maxq']) 223 | a_indices = pad_seq(atokenized[i], w2idx, limit['maxa']) 224 | 225 | #print(len(idx_q[i]), len(q_indices)) 226 | #print(len(idx_a[i]), len(a_indices)) 227 | idx_q[i] = np.array(q_indices) 228 | idx_a[i] = np.array(a_indices) 229 | 230 | return idx_q, idx_a 231 | 232 | 233 | ''' 234 | replace words with indices in a sequence 235 | replace with unknown if word not in lookup 236 | return [list of indices] 237 | 238 | ''' 239 | def pad_seq(seq, lookup, maxlen): 240 | indices = [] 241 | for word in seq: 242 | if word in lookup: 243 | indices.append(lookup[word]) 244 | else: 245 | indices.append(lookup[UNK]) 246 | return indices + [0]*(maxlen - len(seq)) 247 | 248 | 249 | 250 | 251 | 252 | def process_data(): 253 | 254 | id2line = get_id2line() 255 | print('>> gathered id2line dictionary.\n') 256 | convs = get_conversations() 257 | print(convs[121:125]) 258 | print('>> gathered conversations.\n') 259 | questions, answers = gather_dataset(convs,id2line) 260 | 261 | # change to lower case (just for en) 262 | questions = [ line.lower() for line in questions ] 263 | answers = [ line.lower() for line in answers ] 264 | 265 | # filter out unnecessary characters 266 | print('\n>> Filter lines') 267 | questions = [ filter_line(line, EN_WHITELIST) for line in questions ] 268 | answers = [ filter_line(line, EN_WHITELIST) for line in answers ] 269 | 270 | # filter out too long or too short sequences 271 | print('\n>> 2nd layer of filtering') 272 | qlines, alines = filter_data(questions, answers) 273 | 274 | for q,a in zip(qlines[141:145], alines[141:145]): 275 | print('q : [{0}]; a : [{1}]'.format(q,a)) 276 | 277 | # convert list of [lines of text] into list of [list of words ] 278 | print('\n>> Segment lines into words') 279 | qtokenized = [ [w.strip() for w in wordlist.split(' ') if w] for wordlist in qlines ] 280 | atokenized = [ [w.strip() for w in wordlist.split(' ') if w] for wordlist in alines ] 281 | print('\n:: Sample from segmented list of words') 282 | 283 | for q,a in zip(qtokenized[141:145], atokenized[141:145]): 284 | print('q : [{0}]; a : [{1}]'.format(q,a)) 285 | 286 | # indexing -> idx2w, w2idx 287 | print('\n >> Index words') 288 | idx2w, w2idx, freq_dist = index_( qtokenized + atokenized, vocab_size=VOCAB_SIZE) 289 | 290 | # filter out sentences with too many unknowns 291 | print('\n >> Filter Unknowns') 292 | qtokenized, atokenized = filter_unk(qtokenized, atokenized, w2idx) 293 | print('\n Final dataset len : ' + str(len(qtokenized))) 294 | 295 | 296 | print('\n >> Zero Padding') 297 | idx_q, idx_a = zero_pad(qtokenized, atokenized, w2idx) 298 | 299 | print('\n >> Save numpy arrays to disk') 300 | # save them 301 | np.save('idx_q.npy', idx_q) 302 | np.save('idx_a.npy', idx_a) 303 | 304 | # let us now save the necessary dictionaries 305 | metadata = { 306 | 'w2idx' : w2idx, 307 | 'idx2w' : idx2w, 308 | 'limit' : limit, 309 | 'freq_dist' : freq_dist 310 | } 311 | 312 | # write to disk : data control dictionaries 313 | with open('metadata.pkl', 'wb') as f: 314 | pickle.dump(metadata, f) 315 | 316 | # count of unknowns 317 | unk_count = (idx_q == 1).sum() + (idx_a == 1).sum() 318 | # count of words 319 | word_count = (idx_q > 1).sum() + (idx_a > 1).sum() 320 | 321 | print('% unknown : {0}'.format(100 * (unk_count/word_count))) 322 | print('Dataset count : ' + str(idx_q.shape[0])) 323 | 324 | 325 | #print '>> gathered questions and answers.\n' 326 | #prepare_seq2seq_files(questions,answers) 327 | 328 | 329 | if __name__ == '__main__': 330 | process_data() 331 | 332 | 333 | def load_data(PATH=''): 334 | # read data control dictionaries 335 | with open(PATH + 'metadata.pkl', 'rb') as f: 336 | metadata = pickle.load(f) 337 | # read numpy arrays 338 | idx_q = np.load(PATH + 'idx_q.npy') 339 | idx_a = np.load(PATH + 'idx_a.npy') 340 | return metadata, idx_q, idx_a 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | -------------------------------------------------------------------------------- /datasets/twitter/data.py: -------------------------------------------------------------------------------- 1 | EN_WHITELIST = '0123456789abcdefghijklmnopqrstuvwxyz ' # space is included in whitelist 2 | EN_BLACKLIST = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\'' 3 | 4 | FILENAME = 'data/chat.txt' 5 | 6 | limit = { 7 | 'maxq' : 20, 8 | 'minq' : 0, 9 | 'maxa' : 20, 10 | 'mina' : 3 11 | } 12 | 13 | UNK = 'unk' 14 | VOCAB_SIZE = 6000 15 | 16 | import random 17 | import sys 18 | 19 | import nltk 20 | import itertools 21 | from collections import defaultdict 22 | 23 | import numpy as np 24 | 25 | import pickle 26 | 27 | 28 | def ddefault(): 29 | return 1 30 | 31 | ''' 32 | read lines from file 33 | return [list of lines] 34 | 35 | ''' 36 | def read_lines(filename): 37 | return open(filename).read().split('\n')[:-1] 38 | 39 | 40 | ''' 41 | split sentences in one line 42 | into multiple lines 43 | return [list of lines] 44 | 45 | ''' 46 | def split_line(line): 47 | return line.split('.') 48 | 49 | 50 | ''' 51 | remove anything that isn't in the vocabulary 52 | return str(pure ta/en) 53 | 54 | ''' 55 | def filter_line(line, whitelist): 56 | return ''.join([ ch for ch in line if ch in whitelist ]) 57 | 58 | 59 | ''' 60 | read list of words, create index to word, 61 | word to index dictionaries 62 | return tuple( vocab->(word, count), idx2w, w2idx ) 63 | 64 | ''' 65 | def index_(tokenized_sentences, vocab_size): 66 | # get frequency distribution 67 | freq_dist = nltk.FreqDist(itertools.chain(*tokenized_sentences)) 68 | # get vocabulary of 'vocab_size' most used words 69 | vocab = freq_dist.most_common(vocab_size) 70 | # index2word 71 | index2word = ['_'] + [UNK] + [ x[0] for x in vocab ] 72 | # word2index 73 | word2index = dict([(w,i) for i,w in enumerate(index2word)] ) 74 | return index2word, word2index, freq_dist 75 | 76 | 77 | ''' 78 | filter too long and too short sequences 79 | return tuple( filtered_ta, filtered_en ) 80 | 81 | ''' 82 | def filter_data(sequences): 83 | filtered_q, filtered_a = [], [] 84 | raw_data_len = len(sequences)//2 85 | 86 | for i in range(0, len(sequences), 2): 87 | qlen, alen = len(sequences[i].split(' ')), len(sequences[i+1].split(' ')) 88 | if qlen >= limit['minq'] and qlen <= limit['maxq']: 89 | if alen >= limit['mina'] and alen <= limit['maxa']: 90 | filtered_q.append(sequences[i]) 91 | filtered_a.append(sequences[i+1]) 92 | 93 | # print the fraction of the original data, filtered 94 | filt_data_len = len(filtered_q) 95 | filtered = int((raw_data_len - filt_data_len)*100/raw_data_len) 96 | print(str(filtered) + '% filtered from original data') 97 | 98 | return filtered_q, filtered_a 99 | 100 | 101 | 102 | 103 | 104 | ''' 105 | create the final dataset : 106 | - convert list of items to arrays of indices 107 | - add zero padding 108 | return ( [array_en([indices]), array_ta([indices]) ) 109 | 110 | ''' 111 | def zero_pad(qtokenized, atokenized, w2idx): 112 | # num of rows 113 | data_len = len(qtokenized) 114 | 115 | # numpy arrays to store indices 116 | idx_q = np.zeros([data_len, limit['maxq']], dtype=np.int32) 117 | idx_a = np.zeros([data_len, limit['maxa']], dtype=np.int32) 118 | 119 | for i in range(data_len): 120 | q_indices = pad_seq(qtokenized[i], w2idx, limit['maxq']) 121 | a_indices = pad_seq(atokenized[i], w2idx, limit['maxa']) 122 | 123 | #print(len(idx_q[i]), len(q_indices)) 124 | #print(len(idx_a[i]), len(a_indices)) 125 | idx_q[i] = np.array(q_indices) 126 | idx_a[i] = np.array(a_indices) 127 | 128 | return idx_q, idx_a 129 | 130 | 131 | ''' 132 | replace words with indices in a sequence 133 | replace with unknown if word not in lookup 134 | return [list of indices] 135 | 136 | ''' 137 | def pad_seq(seq, lookup, maxlen): 138 | indices = [] 139 | for word in seq: 140 | if word in lookup: 141 | indices.append(lookup[word]) 142 | else: 143 | indices.append(lookup[UNK]) 144 | return indices + [0]*(maxlen - len(seq)) 145 | 146 | 147 | def process_data(): 148 | 149 | print('\n>> Read lines from file') 150 | lines = read_lines(filename=FILENAME) 151 | 152 | # change to lower case (just for en) 153 | lines = [ line.lower() for line in lines ] 154 | 155 | print('\n:: Sample from read(p) lines') 156 | print(lines[121:125]) 157 | 158 | # filter out unnecessary characters 159 | print('\n>> Filter lines') 160 | lines = [ filter_line(line, EN_WHITELIST) for line in lines ] 161 | print(lines[121:125]) 162 | 163 | # filter out too long or too short sequences 164 | print('\n>> 2nd layer of filtering') 165 | qlines, alines = filter_data(lines) 166 | print('\nq : {0} ; a : {1}'.format(qlines[60], alines[60])) 167 | print('\nq : {0} ; a : {1}'.format(qlines[61], alines[61])) 168 | 169 | 170 | # convert list of [lines of text] into list of [list of words ] 171 | print('\n>> Segment lines into words') 172 | qtokenized = [ wordlist.split(' ') for wordlist in qlines ] 173 | atokenized = [ wordlist.split(' ') for wordlist in alines ] 174 | print('\n:: Sample from segmented list of words') 175 | print('\nq : {0} ; a : {1}'.format(qtokenized[60], atokenized[60])) 176 | print('\nq : {0} ; a : {1}'.format(qtokenized[61], atokenized[61])) 177 | 178 | 179 | # indexing -> idx2w, w2idx : en/ta 180 | print('\n >> Index words') 181 | idx2w, w2idx, freq_dist = index_( qtokenized + atokenized, vocab_size=VOCAB_SIZE) 182 | 183 | print('\n >> Zero Padding') 184 | idx_q, idx_a = zero_pad(qtokenized, atokenized, w2idx) 185 | 186 | print('\n >> Save numpy arrays to disk') 187 | # save them 188 | np.save('idx_q.npy', idx_q) 189 | np.save('idx_a.npy', idx_a) 190 | 191 | # let us now save the necessary dictionaries 192 | metadata = { 193 | 'w2idx' : w2idx, 194 | 'idx2w' : idx2w, 195 | 'limit' : limit, 196 | 'freq_dist' : freq_dist 197 | } 198 | 199 | # write to disk : data control dictionaries 200 | with open('metadata.pkl', 'wb') as f: 201 | pickle.dump(metadata, f) 202 | 203 | def load_data(PATH=''): 204 | # read data control dictionaries 205 | with open(PATH + 'metadata.pkl', 'rb') as f: 206 | metadata = pickle.load(f) 207 | # read numpy arrays 208 | idx_q = np.load(PATH + 'idx_q.npy') 209 | idx_a = np.load(PATH + 'idx_a.npy') 210 | return metadata, idx_q, idx_a 211 | 212 | 213 | if __name__ == '__main__': 214 | process_data() 215 | -------------------------------------------------------------------------------- /datasets/twitter/pull: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | wget -c 'https://www.dropbox.com/s/tmfwptbs3q180p0/seq2seq.twitter.tar.gz?dl=0' -O seq2seq.twitter.tar.gz 4 | -------------------------------------------------------------------------------- /datasets/twitter/pull_raw_data: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | wget -c https://raw.githubusercontent.com/Marsan-Ma/chat_corpus/master/twitter_en.txt.gz 3 | -------------------------------------------------------------------------------- /datasets/twitter/seq2seq.twitter.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/datasets/twitter/seq2seq.twitter.tar.gz -------------------------------------------------------------------------------- /img/phoneme.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/img/phoneme.png -------------------------------------------------------------------------------- /img/twitter01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/img/twitter01.png -------------------------------------------------------------------------------- /img/twitter02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/suriyadeepan/practical_seq2seq/eb2e44b77b0b4af52c8d1b6d41e19919873a7f4f/img/twitter02.png -------------------------------------------------------------------------------- /seq2seq_wrapper.py: -------------------------------------------------------------------------------- 1 | import tensorflow as tf 2 | import numpy as np 3 | import sys 4 | 5 | 6 | class Seq2Seq(object): 7 | 8 | def __init__(self, xseq_len, yseq_len, 9 | xvocab_size, yvocab_size, 10 | emb_dim, num_layers, ckpt_path, 11 | lr=0.0001, 12 | epochs=100000, model_name='seq2seq_model'): 13 | 14 | # attach these arguments to self 15 | self.xseq_len = xseq_len 16 | self.yseq_len = yseq_len 17 | self.ckpt_path = ckpt_path 18 | self.epochs = epochs 19 | self.model_name = model_name 20 | 21 | 22 | # build thy graph 23 | # attach any part of the graph that needs to be exposed, to the self 24 | def __graph__(): 25 | 26 | # placeholders 27 | tf.reset_default_graph() 28 | # encoder inputs : list of indices of length xseq_len 29 | self.enc_ip = [ tf.placeholder(shape=[None,], 30 | dtype=tf.int64, 31 | name='ei_{}'.format(t)) for t in range(xseq_len) ] 32 | 33 | # labels that represent the real outputs 34 | self.labels = [ tf.placeholder(shape=[None,], 35 | dtype=tf.int64, 36 | name='ei_{}'.format(t)) for t in range(yseq_len) ] 37 | 38 | # decoder inputs : 'GO' + [ y1, y2, ... y_t-1 ] 39 | self.dec_ip = [ tf.zeros_like(self.enc_ip[0], dtype=tf.int64, name='GO') ] + self.labels[:-1] 40 | 41 | 42 | # Basic LSTM cell wrapped in Dropout Wrapper 43 | self.keep_prob = tf.placeholder(tf.float32) 44 | # define the basic cell 45 | basic_cell = tf.contrib.rnn.core_rnn_cell.DropoutWrapper( 46 | tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(emb_dim, state_is_tuple=True), 47 | output_keep_prob=self.keep_prob) 48 | # stack cells together : n layered model 49 | stacked_lstm = tf.contrib.rnn.core_rnn_cell.MultiRNNCell([basic_cell]*num_layers, state_is_tuple=True) 50 | 51 | 52 | # for parameter sharing between training model 53 | # and testing model 54 | with tf.variable_scope('decoder') as scope: 55 | # build the seq2seq model 56 | # inputs : encoder, decoder inputs, LSTM cell type, vocabulary sizes, embedding dimensions 57 | self.decode_outputs, self.decode_states = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq(self.enc_ip,self.dec_ip, stacked_lstm, 58 | xvocab_size, yvocab_size, emb_dim) 59 | # share parameters 60 | scope.reuse_variables() 61 | # testing model, where output of previous timestep is fed as input 62 | # to the next timestep 63 | self.decode_outputs_test, self.decode_states_test = tf.contrib.legacy_seq2seq.embedding_rnn_seq2seq( 64 | self.enc_ip, self.dec_ip, stacked_lstm, xvocab_size, yvocab_size,emb_dim, 65 | feed_previous=True) 66 | 67 | # now, for training, 68 | # build loss function 69 | 70 | # weighted loss 71 | # TODO : add parameter hint 72 | loss_weights = [ tf.ones_like(label, dtype=tf.float32) for label in self.labels ] 73 | self.loss = tf.contrib.legacy_seq2seq.sequence_loss(self.decode_outputs, self.labels, loss_weights, yvocab_size) 74 | # train op to minimize the loss 75 | self.train_op = tf.train.AdamOptimizer(learning_rate=lr).minimize(self.loss) 76 | 77 | sys.stdout.write(' Building Graph ') 78 | # build comput graph 79 | __graph__() 80 | sys.stdout.write('') 81 | 82 | 83 | 84 | ''' 85 | Training and Evaluation 86 | 87 | ''' 88 | 89 | # get the feed dictionary 90 | def get_feed(self, X, Y, keep_prob): 91 | feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)} 92 | feed_dict.update({self.labels[t]: Y[t] for t in range(self.yseq_len)}) 93 | feed_dict[self.keep_prob] = keep_prob # dropout prob 94 | return feed_dict 95 | 96 | # run one batch for training 97 | def train_batch(self, sess, train_batch_gen): 98 | # get batches 99 | batchX, batchY = train_batch_gen.__next__() 100 | # build feed 101 | feed_dict = self.get_feed(batchX, batchY, keep_prob=0.5) 102 | _, loss_v = sess.run([self.train_op, self.loss], feed_dict) 103 | return loss_v 104 | 105 | def eval_step(self, sess, eval_batch_gen): 106 | # get batches 107 | batchX, batchY = eval_batch_gen.__next__() 108 | # build feed 109 | feed_dict = self.get_feed(batchX, batchY, keep_prob=1.) 110 | loss_v, dec_op_v = sess.run([self.loss, self.decode_outputs_test], feed_dict) 111 | # dec_op_v is a list; also need to transpose 0,1 indices 112 | # (interchange batch_size and timesteps dimensions 113 | dec_op_v = np.array(dec_op_v).transpose([1,0,2]) 114 | return loss_v, dec_op_v, batchX, batchY 115 | 116 | # evaluate 'num_batches' batches 117 | def eval_batches(self, sess, eval_batch_gen, num_batches): 118 | losses = [] 119 | for i in range(num_batches): 120 | loss_v, dec_op_v, batchX, batchY = self.eval_step(sess, eval_batch_gen) 121 | losses.append(loss_v) 122 | return np.mean(losses) 123 | 124 | # finally the train function that 125 | # runs the train_op in a session 126 | # evaluates on valid set periodically 127 | # prints statistics 128 | def train(self, train_set, valid_set, sess=None ): 129 | 130 | # we need to save the model periodically 131 | saver = tf.train.Saver() 132 | 133 | # if no session is given 134 | if not sess: 135 | # create a session 136 | sess = tf.Session() 137 | # init all variables 138 | sess.run(tf.global_variables_initializer()) 139 | 140 | sys.stdout.write('\n Training started \n') 141 | # run M epochs 142 | for i in range(self.epochs): 143 | try: 144 | self.train_batch(sess, train_set) 145 | if i and i% (self.epochs//100) == 0: # TODO : make this tunable by the user 146 | # save model to disk 147 | saver.save(sess, self.ckpt_path + self.model_name + '.ckpt', global_step=i) 148 | # evaluate to get validation loss 149 | val_loss = self.eval_batches(sess, valid_set, 16) # TODO : and this 150 | # print stats 151 | print('\nModel saved to disk at iteration #{}'.format(i)) 152 | print('val loss : {0:.6f}'.format(val_loss)) 153 | sys.stdout.flush() 154 | except KeyboardInterrupt: # this will most definitely happen, so handle it 155 | print('Interrupted by user at iteration {}'.format(i)) 156 | self.session = sess 157 | return sess 158 | 159 | def restore_last_session(self): 160 | saver = tf.train.Saver() 161 | # create a session 162 | sess = tf.Session() 163 | # get checkpoint state 164 | ckpt = tf.train.get_checkpoint_state(self.ckpt_path) 165 | # restore session 166 | if ckpt and ckpt.model_checkpoint_path: 167 | saver.restore(sess, ckpt.model_checkpoint_path) 168 | # return to user 169 | return sess 170 | 171 | # prediction 172 | def predict(self, sess, X): 173 | feed_dict = {self.enc_ip[t]: X[t] for t in range(self.xseq_len)} 174 | feed_dict[self.keep_prob] = 1. 175 | dec_op_v = sess.run(self.decode_outputs_test, feed_dict) 176 | # dec_op_v is a list; also need to transpose 0,1 indices 177 | # (interchange batch_size and timesteps dimensions 178 | dec_op_v = np.array(dec_op_v).transpose([1,0,2]) 179 | # return the index of item with highest probability 180 | return np.argmax(dec_op_v, axis=2) 181 | 182 | 183 | --------------------------------------------------------------------------------