In [1]:
%load_ext autoreload
%autoreload 2

In [2]:
# load the dataset
import os
with open(os.path.join('dataset', 'sharespeare-kaparthy.txt')) as f:
    raw = f.read()
print raw[:1000] # print the first 100 characters


First Citizen:
Before we proceed any further, hear me speak.

All:
Speak, speak.

First Citizen:
You are all resolved rather to die than to famish?

All:
Resolved. resolved.

First Citizen:
First, you know Caius Marcius is chief enemy to the people.

All:
We know't, we know't.

First Citizen:
Let us kill him, and we'll have corn at our own price.
Is't a verdict?

All:
No more talking on't; let it be done: away, away!

Second Citizen:
One word, good citizens.

First Citizen:
We are accounted poor citizens, the patricians good.
What authority surfeits on would relieve us: if they
would yield us but the superfluity, while it were
wholesome, we might guess they relieved us humanely;
but they think we are too dear: the leanness that
afflicts us, the object of our misery, is as an
inventory to particularise their abundance; our
sufferance is a gain to them Let us revenge this with
our pikes, ere we become rakes: for the gods know I
speak this in hunger for bread, not in thirst for revenge.



In [3]:
# convert raw data into indices
import numpy as np
from pystacks.utils.text.vocab import Vocab

vocab = Vocab(unk=False)
data = np.array([vocab.add(c) for c in raw])
print data[:100] # print the first 100 characters


[ 0  1  2  3  4  5  6  1  4  1  7  8  9 10 11 12  8 13 14  2  8  5 15  8  5
 16  2 14 17  8  8 18  5 19  9 20  5 13 21  2  4 22  8  2 23  5 22  8 19  2
  5 24  8  5  3 16  8 19 25 26 11 11 27 28 28 10 11 29 16  8 19 25 23  5  3
 16  8 19 25 26 11 11  0  1  2  3  4  5  6  1  4  1  7  8  9 10 11 30 14 21]

In [6]:
def get_batch(ngrams=10, batch_size=100):
    X, Y = [], []
    for i in np.random.randint(len(data)-ngrams-1, size=batch_size):
        x = data[i:i+ngrams]
        y = data[i+1:i+ngrams+1]
        X.append(x)
        Y.append(y)
    X = np.array(X, dtype='int32').reshape(batch_size, ngrams, 1)
    Y = np.array(Y, dtype='int32')
    return X, Y

X, Y = get_batch()
print X.shape # dim0 is batch size, dim1 is time steps, dim2 is feature size
print Y.shape # dim0 is batch size, dim2 is time steps

def one_hot(y):
    Y = np.zeros( list(y.shape) + [len(vocab)])
    for batch in xrange(Y.shape[0]):
        for time in xrange(Y.shape[1]):
            Y[batch, time, y[batch, time]] = 1
    return Y.astype('float32')

print one_hot(Y).shape


(100, 10, 1)
(100, 10)
(100, 10, 65)

In [13]:
# make a character model
from theano import tensor as T, function
from pystacks.layers.container import Recurrent
from pystacks.layers.memory import GRUMemoryLayer, LSTMMemoryLayer
from pystacks.layers.lookup import LookupTable
from pystacks.layers.common import LinearLayer, Tanh, Softmax, Dropout
from pystacks.criteria import cross_entropy_loss
from pystacks.update import rmsprop

emb_size = 20
h1_size = 500
h2_size = 500

net = Recurrent([
        LookupTable(len(vocab), emb_size), 
        LSTMMemoryLayer(emb_size, h1_size), 
        LSTMMemoryLayer(h1_size, h2_size), 
        LinearLayer(h2_size, len(vocab)), 
        Softmax()])

sym_X = T.itensor3()
sym_prob = net.forward(sym_X, return_sequence=True)
sym_pred = sym_prob.argmax(axis=-1)

f_pred = function([sym_X], [sym_prob, sym_pred])

In [14]:
original_weights = {name:param.get_value() for name, param in net.params.items()}

def reset_weights():
    for name, param in net.params.items():
        param.set_value(original_weights[name])

In [15]:
prob, pred = f_pred(X)
print prob.shape # (batch_size, time_step, probabilities)
print pred.shape # (batch_size, class_label at each time step)


(64, 50, 65)
(64, 50)

In [16]:
sym_Y = T.ftensor3()

sym_loss = cross_entropy_loss(sym_prob, sym_Y)
sym_acc = T.mean(T.eq(sym_pred, sym_Y.argmax(-1)))
sym_lr = T.fscalar()


train = function([sym_X, sym_Y, sym_lr], [sym_loss, sym_acc], updates=net.grad_updates(sym_loss, lr=sym_lr, update=rmsprop))
test = function([sym_X, sym_Y], [sym_loss, sym_acc])

In [17]:
ngrams = 100
batch_size = 64
num_batches = 3000
print_every = 100
decay_rate = 1e-5
lr = 1e-2

from time import time

reset_weights()

start = time()
for i in xrange(num_batches):
    X, Y = get_batch(ngrams, batch_size)
    loss, acc = train(X, one_hot(Y), lr)
    lr *= 1. / (1. + decay_rate)
    
    if i % print_every == 0:
        print 'iteration', i, 'loss', loss, 'acc', acc, 'elapsed', time() - start
        start = time()


iteration 0 loss 417.451842985 acc 0.0196875 elapsed 9.0211648941
iteration 100 loss 365.359262364 acc 0.056875 elapsed 932.802332878
iteration 200 loss 348.751220018 acc 0.14953125 elapsed 934.300982952
iteration 300 loss 338.498926185 acc 0.1484375 elapsed 931.127271891
iteration 400 loss 335.508762133 acc 0.1490625 elapsed 932.50473094
iteration 500 loss 337.320951664 acc 0.149375 elapsed 931.12044096
iteration 600 loss 337.648189872 acc 0.15015625 elapsed 930.924603939
iteration 700 loss 338.279174101 acc 0.1490625 elapsed 928.791729927
iteration 800 loss 330.889380499 acc 0.1521875 elapsed 930.503908873
iteration 900 loss 328.521252116 acc 0.15140625 elapsed 951.729323149
iteration 1000 loss 320.164005397 acc 0.14875 elapsed 939.566409111
iteration 1100 loss 274.206253082 acc 0.2290625 elapsed 944.184103966
iteration 1200 loss 235.86247336 acc 0.3240625 elapsed 937.295361042
iteration 1300 loss 210.619401588 acc 0.38359375 elapsed 939.269972086
iteration 1400 loss 195.562048399 acc 0.43234375 elapsed 942.047028065
iteration 1500 loss 177.688651489 acc 0.47109375 elapsed 942.615360975
iteration 1600 loss 170.188143897 acc 0.4915625 elapsed 941.305348873
iteration 1700 loss 167.687296692 acc 0.50015625 elapsed 944.531881094
iteration 1800 loss 163.012664461 acc 0.51296875 elapsed 946.074276209
iteration 1900 loss 158.041665276 acc 0.5240625 elapsed 943.706629992
iteration 2000 loss 158.240099682 acc 0.519375 elapsed 943.878690004
iteration 2100 loss 151.425111219 acc 0.54296875 elapsed 942.746580124
iteration 2200 loss 149.5819879 acc 0.54203125 elapsed 942.282858133
iteration 2300 loss 150.409841373 acc 0.53796875 elapsed 953.14794302
iteration 2400 loss 149.094170923 acc 0.54890625 elapsed 943.900464058
iteration 2500 loss 146.971957231 acc 0.5384375 elapsed 944.925806999
iteration 2600 loss 145.746991732 acc 0.55203125 elapsed 946.896852016
iteration 2700 loss 147.082750102 acc 0.5496875 elapsed 945.697485924
iteration 2800 loss 146.360227678 acc 0.553125 elapsed 946.989845037
iteration 2900 loss 144.910138003 acc 0.5628125 elapsed 946.332966805

In [19]:
chars = ['I']
for i in xrange(1000):
    in_ind = [vocab[c] for c in chars]
    prob, pred = f_pred(np.array([[in_ind[-ngrams:]]], dtype='int32').reshape(1, -1, 1))
    char = np.random.choice(vocab.index2word, p=prob[0, -1].flatten())
    chars.append(char)
print ''.join(chars)


0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 ILA:
My grief, what sprate udage leave mine.

QUEEN MARGARENCE:
O Richard, to make the great prove, thy parlies;
Whose time this bech answer, that's gentleman:
Butwouts' and be a justant, I'll be lucking this.

BRLISPNE:
Godress, what you perall, very births,
Tails not be instroyer
To your grain and I'll as heyterver dog this aon,
That feather will tent tumpt, but then.

CLARENCUS:
All hack you haze match.

KING LEWIS XI:
O will heard breath,
To saint goldest at well, sirl hearing,
Mest and please in thee, with hence intens
Making thou be patusting to-day.

PETRUCHIO:
Was give middun such suchness,
By he be guest for you may swear'st tumps.
Where's shall comes the pack to be;
Since the pates, madaments, he did fear, Signior,
Only set answer liece,
Opes, would, and he senst heathe.

NORFOLK:
Ah thus countly in him slem her hearts tasth?
But, this what; soldier waster, sir, and garry, understracher.

RIVERS:
I speak to hell, then; then!

Gerbrow, and dear blude--
Bequatibuness and perform

In [ ]: