-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathseq2seq_translation_tutorial.py
869 lines (709 loc) Β· 33.6 KB
/
seq2seq_translation_tutorial.py
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
# -*- coding: utf-8 -*-
"""
κΈ°μ΄λΆν° μμνλ NLP: Sequence to Sequence λ€νΈμν¬μ Attentionμ μ΄μ©ν λ²μ
********************************************************************************
**Author**: `Sean Robertson <https://github.com/spro>`_
**λ²μ**: `ν©μ±μ <https://github.com/adonisues>`_
μ΄ νν 리μΌμ "κΈ°μ΄λΆν° μμνλ NLP"μ μΈλ²μ§Έμ΄μ λ§μ§λ§ νΈμΌλ‘, NLP λͺ¨λΈλ§ μμ
μ
μν λ°μ΄ν° μ μ²λ¦¬μ μ¬μ©ν μ체 ν΄λμ€μ ν¨μλ€μ μμ±ν΄λ³΄κ² μ΅λλ€.
μ΄ νν 리μΌμ λ§μΉ λ€μλ `torchtext` κ° μ΄λ»κ² μ§κΈκΉμ§μ νν 리μΌλ€μμμ
μ μ²λ¦¬ κ³Όμ μ λ€λ£¨λμ§λ₯Ό μ΄ν νν 리μΌλ€μμ λ°°μΈ μ μμ΅λλ€.
μ΄ νλ‘μ νΈμμλ μ κ²½λ§μ΄ λΆμ΄λ₯Ό μμ΄λ‘ λ²μνλλ‘ κ°λ₯΄μΉ μμ μ
λλ€.
.. code-block:: sh
[KEY: > input, = target, < output]
> il est en train de peindre un tableau .
= he is painting a picture .
< he is painting a picture .
> pourquoi ne pas essayer ce vin delicieux ?
= why not try that delicious wine ?
< why not try that delicious wine ?
> elle n est pas poete mais romanciere .
= she is not a poet but a novelist .
< she not not a poet but a novelist .
> vous etes trop maigre .
= you re too skinny .
< you re all alone .
... μ±κ³΅μ¨μ λ¬λΌμ§ μ μμ΅λλ€.
νλμ μνμ€λ₯Ό λ€λ₯Έ μνμ€λ‘ λ°κΎΈλ λ κ°μ RNNμ΄ ν¨κ» λμνλ
`sequence to sequence network <https://arxiv.org/abs/1409.3215>`__ μ κ°λ¨νμ§λ§ κ°λ ₯ν μμ΄λμ΄κ°
μ΄κ²(λ²μ)μ κ°λ₯νκ² ν©λλ€. μΈμ½λ λ€νΈμν¬λ μ
λ ₯ μνμ€λ₯Ό 벑ν°λ‘ μμΆνκ³ ,
λμ½λ λ€νΈμν¬λ ν΄λΉ 벑ν°λ₯Ό μλ‘μ΄ μνμ€λ‘ νΌμΉ©λλ€.
.. figure:: /_static/img/seq-seq-images/seq2seq.png
:alt:
μ΄ λͺ¨λΈμ κ°μ νκΈ° μν΄ `Attention Mechanism <https://arxiv.org/abs/1409.0473>`__ μ
μ¬μ©νλ©΄ λμ½λκ° μ
λ ₯ μνμ€μ νΉμ λ²μμ μ§μ€ν μ μλλ‘ ν©λλ€.
**μΆμ² μλ£:**
μ΅μν Pytorchλ₯Ό μ€μΉνκ³ , Pythonμ μκ³ , Tensorλ₯Ό μ΄ν΄νλ€κ³ κ°μ ν©λλ€.:
- http://pytorch.org/ μ€μΉ μλ΄λ₯Ό μν μλ£
- :doc:`/beginner/deep_learning_60min_blitz` μΌλ°μ μΈ PyTorch μμμ μν μλ£
- :doc:`/beginner/pytorch_with_examples` λκ³ κΉμ ν΅μ°°μ μν μλ£
- :doc:`/beginner/former_torchies_tutorial` μ΄μ Lua Torch μ¬μ©μλ₯Ό μν μλ£
Sequence to Sequence λ€νΈμν¬μ λμ λ°©λ²μ κ΄ν΄μ μλ κ²μ μ μ©ν©λλ€:
- `Learning Phrase Representations using RNN Encoder-Decoder for
Statistical Machine Translation <https://arxiv.org/abs/1406.1078>`__
- `Sequence to Sequence Learning with Neural
Networks <https://arxiv.org/abs/1409.3215>`__
- `Neural Machine Translation by Jointly Learning to Align and
Translate <https://arxiv.org/abs/1409.0473>`__
- `A Neural Conversational Model <https://arxiv.org/abs/1506.05869>`__
μ΄μ νν 리μΌμ μλ
:doc:`/intermediate/char_rnn_classification_tutorial`
μ :doc:`/intermediate/char_rnn_generation_tutorial` λ
κ°κ° μΈμ½λ, λμ½λ λͺ¨λΈκ³Ό λΉμ·ν 컨μΌμ κ°μ§κΈ° λλ¬Έμ λμμ΄ λ©λλ€.
**μꡬ μ¬ν**
"""
from __future__ import unicode_literals, print_function, division
from io import open
import unicodedata
import re
import random
import torch
import torch.nn as nn
from torch import optim
import torch.nn.functional as F
import numpy as np
from torch.utils.data import TensorDataset, DataLoader, RandomSampler
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
######################################################################
#
# λ°μ΄ν° νμΌ λΆλ¬μ€κΈ°
# ========================
#
# μ΄ νλ‘μ νΈμ λ°μ΄ν°λ μμ² κ°μ μμ΄-νλμ€μ΄ λ²μ μμ
λλ€.
#
# `Open Data Stack Exchange <https://opendata.stackexchange.com/questions/3888/dataset-of-sentences-translated-into-many-languages>`__
# μ κ΄ν μ΄ μ§λ¬Έμ https://tatoeba.org/eng/downloads μμ λ€μ΄ λ‘λκ° κ°λ₯ν
# κ³΅κ° λ²μ μ¬μ΄νΈ https://tatoeba.org/ λ₯Ό μλ € μ£Όμμ΅λλ€. λ λμ λ°©λ²μΌλ‘
# μΈμ΄ μμ κ°λ³ ν
μ€νΈ νμΌλ‘ λΆν νλ μΆκ° μμ
μ μνν
# https://www.manythings.org/anki/ κ° μμ΅λλ€:
#
# μμ΄-νλμ€μ΄ μμ΄ λ무 컀μ μ μ₯μμ ν¬ν¨ ν μ μκΈ° λλ¬Έμ
# κ³μνκΈ° μ μ ``data/eng-fra.txt`` λ‘ λ€μ΄λ‘λνμμμ€.
# μ΄ νμΌμ νμΌλ‘ ꡬλΆλ λ²μ μ λͺ©λ‘μ
λλ€:
#
# .. code-block:: sh
#
# I am cold. J'ai froid.
#
# .. note::
# `μ¬κΈ° <https://download.pytorch.org/tutorial/data.zip>`_
# μμ λ°μ΄ν°λ₯Ό λ€μ΄ λ°κ³ νμ¬ λλ ν 리μ μμΆμ νΈμμμ€.
######################################################################
# λ¬Έμ λ¨μ RNN νν 리μΌμμ μ¬μ©λ λ¬Έμ μΈμ½λ©κ³Ό μ μ¬νκ², μΈμ΄μ κ°
# λ¨μ΄λ€μ One-Hot λ²‘ν° λλ κ·Έ λ¨μ΄μ μ£Όμμλ§ λ¨ νλμ 1μ μ μΈνκ³
# λͺ¨λ 0μΈ ν° λ²‘ν°λ‘ ννν©λλ€. ν κ°μ§ μΈμ΄μ μλ μμ κ°μ λ¬Έμμ
# λ¬λ¦¬ λ²μμλ μμ£Ό λ§μ λ¨μ΄λ€μ΄ μκΈ° λλ¬Έμ μΈμ½λ© 벑ν°λ λ§€μ° λ ν½λλ€.
# κ·Έλ¬λ μ°λ¦¬λ μ½κ°μ νΈλ¦λ₯Ό μ¨μ μΈμ΄ λΉ μμ² λ¨μ΄ λ§
# μ¬μ©νλλ‘ λ°μ΄ν°λ₯Ό λ€λ¬μ κ²μ
λλ€.
#
# .. figure:: /_static/img/seq-seq-images/word-encoding.png
# :alt:
#
#
######################################################################
# λμ€μ λ€νΈμν¬μ μ
λ ₯ λ° λͺ©νλ‘ μ¬μ©νλ €λ©΄ λ¨μ΄ λΉ κ³ μ λ²νΈκ°
# νμν©λλ€. μ΄ λͺ¨λ κ²μ μΆμ νκΈ° μν΄ μ°λ¦¬λ
# λ¨μ΄βμμΈ(``word2index``)κ³Ό μμΈβλ¨μ΄(``index2word``) μ¬μ ,
# κ·Έλ¦¬κ³ λμ€μ ν¬κ· λ¨μ΄λ₯Ό λ체νλλ° μ¬μ©ν κ° λ¨μ΄μ λΉλ
# ``word2count`` λ₯Ό κ°μ§ ``Lang`` μ΄λΌλ ν¬νΌ ν΄λμ€λ₯Ό μ¬μ©ν©λλ€.
#
SOS_token = 0
EOS_token = 1
class Lang:
def __init__(self, name):
self.name = name
self.word2index = {}
self.word2count = {}
self.index2word = {0: "SOS", 1: "EOS"}
self.n_words = 2 # SOS μ EOS ν¬ν¨
def addSentence(self, sentence):
for word in sentence.split(' '):
self.addWord(word)
def addWord(self, word):
if word not in self.word2index:
self.word2index[word] = self.n_words
self.word2count[word] = 1
self.index2word[self.n_words] = word
self.n_words += 1
else:
self.word2count[word] += 1
######################################################################
# νμΌμ λͺ¨λ μ λ μ½λλ‘ λμ΄μμ΄ κ°λ¨νκ² νκΈ° μν΄ μ λ μ½λ λ¬Έμλ₯Ό
# ASCIIλ‘ λ³ννκ³ , λͺ¨λ λ¬Έμλ₯Ό μλ¬Έμλ‘ λ§λ€κ³ , λλΆλΆμ ꡬλμ μ
# μ§μμ€λλ€.
#
# μ λ μ½λ λ¬Έμμ΄μ μΌλ° ASCIIλ‘ λ³ννμμμ€.
# https://stackoverflow.com/a/518232/2809427
def unicodeToAscii(s):
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn'
)
# μλ¬Έμ, λ€λ¬κΈ°, κ·Έλ¦¬κ³ λ¬Έμκ° μλ λ¬Έμ μ κ±°
def normalizeString(s):
s = unicodeToAscii(s.lower().strip())
s = re.sub(r"([.!?])", r" \1", s)
s = re.sub(r"[^a-zA-Z!?]+", r" ", s)
return s.strip()
######################################################################
# To read the data file we will split the file into lines, and then split
# lines into pairs. The files are all English β Other Language, so if we
# want to translate from Other Language β English I added the ``reverse``
# flag to reverse the pairs.
#
def readLangs(lang1, lang2, reverse=False):
print("Reading lines...")
# νμΌμ μ½κ³ μ€λ‘ λΆλ¦¬
lines = open('data/%s-%s.txt' % (lang1, lang2), encoding='utf-8').\
read().strip().split('\n')
# λͺ¨λ μ€μ μμΌλ‘ λΆλ¦¬νκ³ μ κ·ν
pairs = [[normalizeString(s) for s in l.split('\t')] for l in lines]
# μμ λ€μ§κ³ , Lang μΈμ€ν΄μ€ μμ±
if reverse:
pairs = [list(reversed(p)) for p in pairs]
input_lang = Lang(lang2)
output_lang = Lang(lang1)
else:
input_lang = Lang(lang1)
output_lang = Lang(lang2)
return input_lang, output_lang, pairs
######################################################################
# *λ§μ* μμ λ¬Έμ₯μ΄ μκ³ μ μνκ² νμ΅νκΈ°λ₯Ό μνκΈ° λλ¬Έμ
# λΉκ΅μ μ§§κ³ κ°λ¨ν λ¬Έμ₯μΌλ‘λ§ λ°μ΄ν° μ
μ μ 리ν κ²μ
λλ€. μ¬κΈ°μ
# μ΅λ κΈΈμ΄λ 10 λ¨μ΄ (μ’
λ£ λ¬Έμ₯ λΆνΈ ν¬ν¨)μ΄λ©° "I am" λλ
# "He is" λ±μ ννλ‘ λ²μλλ λ¬Έμ₯μΌλ‘ νν°λ§λ©λλ€.(μ΄μ μ
# μν¬μ€νΈλ‘νΌλ λ체 λ¨)
#
MAX_LENGTH = 10
eng_prefixes = (
"i am ", "i m ",
"he is", "he s ",
"she is", "she s ",
"you are", "you re ",
"we are", "we re ",
"they are", "they re "
)
def filterPair(p):
return len(p[0].split(' ')) < MAX_LENGTH and \
len(p[1].split(' ')) < MAX_LENGTH and \
p[1].startswith(eng_prefixes)
def filterPairs(pairs):
return [pair for pair in pairs if filterPair(pair)]
######################################################################
# λ°μ΄ν° μ€λΉλ₯Ό μν μ 체 κ³Όμ :
#
# - ν
μ€νΈ νμΌμ μ½κ³ μ€λ‘ λΆλ¦¬νκ³ , μ€μ μμΌλ‘ λΆλ¦¬ν©λλ€.
# - ν
μ€νΈλ₯Ό μ κ·ν νκ³ κΈΈμ΄μ λ΄μ©μΌλ‘ νν°λ§ ν©λλ€.
# - μμ μ΄λ£¬ λ¬Έμ₯λ€λ‘ λ¨μ΄ 리μ€νΈλ₯Ό μμ±ν©λλ€.
#
def prepareData(lang1, lang2, reverse=False):
input_lang, output_lang, pairs = readLangs(lang1, lang2, reverse)
print("Read %s sentence pairs" % len(pairs))
pairs = filterPairs(pairs)
print("Trimmed to %s sentence pairs" % len(pairs))
print("Counting words...")
for pair in pairs:
input_lang.addSentence(pair[0])
output_lang.addSentence(pair[1])
print("Counted words:")
print(input_lang.name, input_lang.n_words)
print(output_lang.name, output_lang.n_words)
return input_lang, output_lang, pairs
input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
print(random.choice(pairs))
######################################################################
#
# Seq2Seq λͺ¨λΈ
# =================
#
# Recurrent Neural Network(RNN)λ μνμ€μμ μλνκ³ λ€μ λ¨κ³μ
# μ
λ ₯μΌλ‘ μμ μ μΆλ ₯μ μ¬μ©νλ λ€νΈμν¬μ
λλ€.
#
# `Sequence to Sequence network <https://arxiv.org/abs/1409.3215>`__, λλ
# Seq2Seq λ€νΈμν¬, λλ `Encoder Decoder
# network <https://arxiv.org/pdf/1406.1078v3.pdf>`__ λ μΈμ½λ λ°
# λμ½λλΌκ³ νλ λ κ°μ RNNμΌλ‘ ꡬμ±λ λͺ¨λΈμ
λλ€.
# μΈμ½λλ μ
λ ₯ μνμ€λ₯Ό μ½κ³ λ¨μΌ 벑ν°λ₯Ό μΆλ ₯νκ³ ,
# λμ½λλ ν΄λΉ 벑ν°λ₯Ό μ½μ΄ μΆλ ₯ μνμ€λ₯Ό μμ±ν©λλ€.
#
# .. figure:: /_static/img/seq-seq-images/seq2seq.png
# :alt:
#
# λͺ¨λ μ
λ ₯μ ν΄λΉνλ μΆλ ₯μ΄ μλ λ¨μΌ RNNμ μνμ€ μμΈ‘κ³Ό λ¬λ¦¬
# Seq2Seq λͺ¨λΈμ μνμ€ κΈΈμ΄μ μμλ₯Ό μμ λ‘κ²νκΈ° λλ¬Έμ
# λ μΈμ΄ μ¬μ΄μ λ²μμ μ΄μμ μ
λλ€.
#
# λ€μ λ¬Έμ₯ ``Je ne suis pas le chat noir`` β ``I am not the black cat``
# λ₯Ό μ΄ν΄ λ΄
μλ€. μ
λ ₯ λ¬Έμ₯μ λ¨μ΄ λλΆλΆμ μΆλ ₯ λ¬Έμ₯μμ
# μ§μ(``chat noir`` μ ``black cat``)λμ§λ§ μ½κ° λ€λ₯Έ μμλ μμ΅λλ€.
# ``ne/pas`` κ΅¬μ‘°λ‘ μΈν΄ μ
λ ₯ λ¬Έμ₯μ λ¨μ΄κ° νλ λ μμ΅λλ€.
# μ
λ ₯ λ¨μ΄μ μνμ€λ₯Ό μ§μν΄μ μ νν λ²μμ λ§λλ
# κ²μ μ΄λ €μΈ κ²μ
λλ€.
#
# Seq2Seq λͺ¨λΈμ μ¬μ©νλ©΄ μΈμ½λλ νλμ 벑ν°λ₯Ό μμ±ν©λλ€.
# μ΄μμ μΈ κ²½μ°μ μ
λ ₯ μνμ€μ "μλ―Έ"λ₯Ό λ¬Έμ₯μ N μ°¨μ 곡κ°μ μλ
# λ¨μΌ μ§μ μΈ λ¨μΌ 벑ν°μΌλ‘ μΈμ½λ©ν©λλ€.
#
######################################################################
# μΈμ½λ
# -----------
#
# Seq2Seq λ€νΈμν¬μ μΈμ½λλ μ
λ ₯ λ¬Έμ₯μ λͺ¨λ λ¨μ΄μ λν΄ μ΄λ€ κ°μ
# μΆλ ₯νλ RNNμ
λλ€. λͺ¨λ μ
λ ₯ λ¨μ΄μ λν΄ μΈμ½λλ 벑ν°μ
# μλ μνλ₯Ό μΆλ ₯νκ³ λ€μ μ
λ ₯ λ¨μ΄λ₯Ό μν΄ κ·Έ μλ μνλ₯Ό μ¬μ©ν©λλ€.
#
# .. figure:: /_static/img/seq-seq-images/encoder-network.png
# :alt:
#
#
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size, dropout_p=0.1):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
self.dropout = nn.Dropout(dropout_p)
def forward(self, input):
embedded = self.dropout(self.embedding(input))
output, hidden = self.gru(embedded)
return output, hidden
######################################################################
#
# λμ½λ
# -----------
#
# λμ½λλ μΈμ½λ μΆλ ₯ 벑ν°λ₯Ό λ°μμ λ²μμ μμ±νκΈ° μν λ¨μ΄ μνμ€λ₯Ό
# μΆλ ₯ν©λλ€.
#
######################################################################
#
# κ°λ¨ν λμ½λ
# ^^^^^^^^^^^^^^
#
# κ°μ₯ κ°λ¨ν Seq2Seq λμ½λλ μΈμ½λμ λ§μ§λ§ μΆλ ₯λ§μ μ΄μ©ν©λλ€.
# μ΄ λ§μ§λ§ μΆλ ₯μ μ 체 μνμ€μμ λ¬Έλ§₯μ μΈμ½λνκΈ° λλ¬Έμ
# *λ¬Έλ§₯ 벑ν°(context vector)* λ‘ λΆλ¦½λλ€. μ΄ λ¬Έλ§₯ 벑ν°λ λμ½λμ μ΄κΈ° μλ μνλ‘
# μ¬μ© λ©λλ€.
#
# λμ½λ©μ λ§€ λ¨κ³μμ λμ½λμκ² μ
λ ₯ ν ν°κ³Ό μλ μνκ° μ£Όμ΄μ§λλ€.
# μ΄κΈ° μ
λ ₯ ν ν°μ λ¬Έμμ΄-μμ (start-of-string) ``<SOS>`` ν ν°μ΄κ³ ,
# 첫 μλ μνλ λ¬Έλ§₯ 벑ν°(μΈμ½λμ λ§μ§λ§ μλ μν) μ
λλ€.
#
# .. figure:: /_static/img/seq-seq-images/decoder-network.png
# :alt:
#
#
class DecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size):
super(DecoderRNN, self).__init__()
self.embedding = nn.Embedding(output_size, hidden_size)
self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True)
self.out = nn.Linear(hidden_size, output_size)
def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
batch_size = encoder_outputs.size(0)
decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
decoder_hidden = encoder_hidden
decoder_outputs = []
for i in range(MAX_LENGTH):
decoder_output, decoder_hidden = self.forward_step(decoder_input, decoder_hidden)
decoder_outputs.append(decoder_output)
if target_tensor is not None:
# Teacher forcing ν¬ν¨: λͺ©νλ₯Ό λ€μ μ
λ ₯μΌλ‘ μ λ¬
decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
else:
# Teacher forcing λ―Έν¬ν¨: μμ μ μμΈ‘μ λ€μ μ
λ ₯μΌλ‘ μ¬μ©
_, topi = decoder_output.topk(1)
decoder_input = topi.squeeze(-1).detach() # μ
λ ₯μΌλ‘ μ¬μ©ν λΆλΆμ νμ€ν 리μμ λΆλ¦¬
decoder_outputs = torch.cat(decoder_outputs, dim=1)
decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
return decoder_outputs, decoder_hidden, None # νμ΅ λ£¨νμ μΌκ΄μ± μ μ§λ₯Ό μν΄ `None` μ μΆκ°λ‘ λ°ν
def forward_step(self, input, hidden):
output = self.embedding(input)
output = F.relu(output)
output, hidden = self.gru(output, hidden)
output = self.out(output)
return output, hidden
######################################################################
# μ΄ λͺ¨λΈμ κ²°κ³Όλ₯Ό νμ΅νκ³ κ΄μ°°νλ κ²μ κΆμ₯νμ§λ§,
# 곡κ°μ μ μ½νκΈ° μν΄ μ΅μ’
λͺ©μ μ§λ‘ λ°λ‘ μ΄λν΄μ
# Attention λ©μ»€λμ¦μ μκ° ν κ²μ
λλ€.
#
######################################################################
#
# Attention λμ½λ
# ^^^^^^^^^^^^^^^^^
#
# λ¬Έλ§₯ 벑ν°λ§ μΈμ½λμ λμ½λ μ¬μ΄λ‘ μ λ¬ λλ€λ©΄, λ¨μΌ 벑ν°κ° μ 체 λ¬Έμ₯μ
# μΈμ½λ© ν΄μΌνλ λΆλ΄μ κ°μ§κ² λ©λλ€.
#
# Attentionμ λμ½λ λ€νΈμν¬κ° μκΈ° μΆλ ₯μ λͺ¨λ λ¨κ³μμ μΈμ½λ μΆλ ₯μ
# λ€λ₯Έ λΆλΆμ "μ§μ€" ν μ μκ² ν©λλ€. 첫째 *Attention κ°μ€μΉ* μ μΈνΈλ₯Ό
# κ³μ°ν©λλ€. μ΄κ²μ κ°μ€μΉ μ‘°ν©μ λ§λ€κΈ° μν΄μ μΈμ½λ μΆλ ₯ 벑ν°μ
# κ³±ν΄μ§λλ€. κ·Έ κ²°κ³Ό(μ½λμμ ``attn_applied``)λ μ
λ ₯ μνμ€μ
# νΉμ λΆλΆμ κ΄ν μ 보λ₯Ό ν¬ν¨ν΄μΌνκ³ λ°λΌμ λμ½λκ° μλ§μ μΆλ ₯
# λ¨μ΄λ₯Ό μ ννλ κ²μ λμμ€λλ€.
#
# .. figure:: https://i.imgur.com/1152PYf.png
# :alt:
#
# μ΄ν
μ
κ°μ€μΉ κ³μ°μ λμ½λμ μ
λ ₯ λ° μλ μνλ₯Ό μ
λ ₯μΌλ‘
# μ¬μ©νλ λ€λ₯Έ feed-forwad κ³μΈ΅μΈ ``attn`` μΌλ‘ μνλ©λλ€.
# νμ΅ λ°μ΄ν°μλ λͺ¨λ ν¬κΈ°μ λ¬Έμ₯μ΄ μκΈ° λλ¬Έμ μ΄ κ³μΈ΅μ μ€μ λ‘
# λ§λ€κ³ νμ΅μν€λ €λ©΄ μ μ© ν μ μλ μ΅λ λ¬Έμ₯ κΈΈμ΄ (μΈμ½λ μΆλ ₯μ μν μ
λ ₯ κΈΈμ΄)λ₯Ό
# μ νν΄μΌ ν©λλ€. μ΅λ κΈΈμ΄μ λ¬Έμ₯μ λͺ¨λ Attention κ°μ€μΉλ₯Ό μ¬μ©νμ§λ§
# λ μ§§μ λ¬Έμ₯μ μ²μ λͺ κ°λ§ μ¬μ©ν©λλ€.
#
# .. figure:: /_static/img/seq-seq-images/attention-decoder-network.png
# :alt:
#
#
# λΆκ°μ μ΄ν
μ
(Additive Attention)μ΄λΌκ³ λ μλ €μ§ λ°λ€λμ° μ΄ν
μ
(Bahdanau
# Attention)μ κΈ°κ³ λ²μ μμ
κ³Ό κ°μ μνμ€-ν¬-μνμ€ λͺ¨λΈμμ μΌλ°μ μΌλ‘
# μ¬μ©νλ μ΄ν
μ
κΈ°λ²(mechanism)μ
λλ€. μ΄ μ΄ν
μ
κΈ°λ²μ Bahdanau et al.μ λ
Όλ¬ΈμΈ
# `Neural Machine Translation by Jointly Learning to Align and Translate <https://arxiv.org/pdf/1409.0473.pdf>`__
# μμ μκ°λμμ΅λλ€. μ΄ μ΄ν
μ
κΈ°λ²μ νμ΅λ μ λ ¬ λͺ¨λΈ(learned alignment model)μ
# μ¬μ©νμ¬ μΈμ½λμ λμ½λμ μλ μν(hidden state) κ°μ μ΄ν
μ
μ μλ₯Ό κ³μ°ν©λλ€.
# μ΄λ μ λ ¬λ μ΄ν
μ
μ μλ₯Ό κ³μ°νκΈ° μν΄ feed-forward μ κ²½λ§μ μ¬μ©ν©λλ€.
#
# λλ, λμ½λμ μλ μνμ μΈμ½λμ μλ μν μ¬μ΄μ μ΄ν
μ
μ μλ₯Ό Dot-Productλ‘
# κ³μ°νλ λ£¨μΉ μ΄ν
μ
(Luong Attention)κ³Ό κ°μ λ€λ₯Έ μ΄ν
μ
κΈ°λ²λ€μ μ¬μ©ν μλ μμ΅λλ€.
# μ΄λ λ°λ€λμ° μ΄ν
μ
(Bahdanau Attention)μμ μ¬μ©νλ λΉμ ν λ³ν(non-linear transformation)μ
# μ¬μ©νμ§λ μμ΅λλ€.
#
# μ΄ νν 리μΌμμλ λ°λ€λμ° μ΄ν
μ
(Bahdanau Attention)μ μ¬μ©ν κ²μ
λλ€. νμ§λ§ μ΄λ₯Ό
# λ£¨μΉ μ΄ν
μ
(Luong Attention) κΈ°λ²μΌλ‘ λ³κ²½ν΄λ³΄λ κ²λ μ’μ μ°μ΅μ΄ λ κ²μ
λλ€.
class BahdanauAttention(nn.Module):
def __init__(self, hidden_size):
super(BahdanauAttention, self).__init__()
self.Wa = nn.Linear(hidden_size, hidden_size)
self.Ua = nn.Linear(hidden_size, hidden_size)
self.Va = nn.Linear(hidden_size, 1)
def forward(self, query, keys):
scores = self.Va(torch.tanh(self.Wa(query) + self.Ua(keys)))
scores = scores.squeeze(2).unsqueeze(1)
weights = F.softmax(scores, dim=-1)
context = torch.bmm(weights, keys)
return context, weights
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, dropout_p=0.1):
super(AttnDecoderRNN, self).__init__()
self.embedding = nn.Embedding(output_size, hidden_size)
self.attention = BahdanauAttention(hidden_size)
self.gru = nn.GRU(2 * hidden_size, hidden_size, batch_first=True)
self.out = nn.Linear(hidden_size, output_size)
self.dropout = nn.Dropout(dropout_p)
def forward(self, encoder_outputs, encoder_hidden, target_tensor=None):
batch_size = encoder_outputs.size(0)
decoder_input = torch.empty(batch_size, 1, dtype=torch.long, device=device).fill_(SOS_token)
decoder_hidden = encoder_hidden
decoder_outputs = []
attentions = []
for i in range(MAX_LENGTH):
decoder_output, decoder_hidden, attn_weights = self.forward_step(
decoder_input, decoder_hidden, encoder_outputs
)
decoder_outputs.append(decoder_output)
attentions.append(attn_weights)
if target_tensor is not None:
# Teacher forcing ν¬ν¨: λͺ©νλ₯Ό λ€μ μ
λ ₯μΌλ‘ μ λ¬
decoder_input = target_tensor[:, i].unsqueeze(1) # Teacher forcing
else:
# Teacher forcing λ―Έν¬ν¨: μμ μ μμΈ‘μ λ€μ μ
λ ₯μΌλ‘ μ¬μ©
_, topi = decoder_output.topk(1)
decoder_input = topi.squeeze(-1).detach() # μ
λ ₯μΌλ‘ μ¬μ©ν λΆλΆμ νμ€ν 리μμ λΆλ¦¬
decoder_outputs = torch.cat(decoder_outputs, dim=1)
decoder_outputs = F.log_softmax(decoder_outputs, dim=-1)
attentions = torch.cat(attentions, dim=1)
return decoder_outputs, decoder_hidden, attentions
def forward_step(self, input, hidden, encoder_outputs):
embedded = self.dropout(self.embedding(input))
query = hidden.permute(1, 0, 2)
context, attn_weights = self.attention(query, encoder_outputs)
input_gru = torch.cat((embedded, context), dim=2)
output, hidden = self.gru(input_gru, hidden)
output = self.out(output)
return output, hidden, attn_weights
######################################################################
# .. note::
# κΈΈμ΄ μ νμ ν΄κ²°νκΈ° μν΄ μλμ μμΉ μ κ·Ό(relative position approach)
# λ°©μμ μ¬μ©νλ λ€λ₯Έ ννμ μ΄ν
μ
λ°©μλ€λ μμ΅λλ€.
# `Effective Approaches to Attention-based Neural Machine Translation <https://arxiv.org/abs/1508.04025>`__
# μμ "local attention" μ λν΄ μ½μ΄λ³΄μΈμ.
#
# νμ΅
# ========
#
# νμ΅ λ°μ΄ν° μ€λΉ
# -----------------------
#
# νμ΅μ μν΄μ, κ° μλ§λ€ μ
λ ₯ Tensor(μ
λ ₯ λ¬Έμ₯μ λ¨μ΄ μ£Όμ)μ
# λͺ©ν Tensor(λͺ©ν λ¬Έμ₯μ λ¨μ΄ μ£Όμ)κ° νμν©λλ€. μ΄ λ²‘ν°λ€μ
# μμ±νλ λμ λ μνμ€μ EOS ν ν°μ μΆκ° ν©λλ€.
#
def indexesFromSentence(lang, sentence):
return [lang.word2index[word] for word in sentence.split(' ')]
def tensorFromSentence(lang, sentence):
indexes = indexesFromSentence(lang, sentence)
indexes.append(EOS_token)
return torch.tensor(indexes, dtype=torch.long, device=device).view(1, -1)
def tensorsFromPair(pair):
input_tensor = tensorFromSentence(input_lang, pair[0])
target_tensor = tensorFromSentence(output_lang, pair[1])
return (input_tensor, target_tensor)
def get_dataloader(batch_size):
input_lang, output_lang, pairs = prepareData('eng', 'fra', True)
n = len(pairs)
input_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
target_ids = np.zeros((n, MAX_LENGTH), dtype=np.int32)
for idx, (inp, tgt) in enumerate(pairs):
inp_ids = indexesFromSentence(input_lang, inp)
tgt_ids = indexesFromSentence(output_lang, tgt)
inp_ids.append(EOS_token)
tgt_ids.append(EOS_token)
input_ids[idx, :len(inp_ids)] = inp_ids
target_ids[idx, :len(tgt_ids)] = tgt_ids
train_data = TensorDataset(torch.LongTensor(input_ids).to(device),
torch.LongTensor(target_ids).to(device))
train_sampler = RandomSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=batch_size)
return input_lang, output_lang, train_dataloader
######################################################################
#
# λͺ¨λΈ νμ΅
# ------------------
#
# νμ΅μ μν΄μ μΈμ½λμ μ
λ ₯ λ¬Έμ₯μ λ£κ³ λͺ¨λ μΆλ ₯κ³Ό μ΅μ μλ μνλ₯Ό
# μΆμ ν©λλ€. κ·Έλ° λ€μ λμ½λμ 첫 λ²μ§Έ μ
λ ₯μΌλ‘ ``<SOS>`` ν ν°κ³Ό
# μΈμ½λμ λ§μ§λ§ μλ μνκ° μ²« λ²μ§Έ μλ μνλ‘ μ 곡λ©λλ€.
#
# "Teacher forcing"μ λ€μ μ
λ ₯μΌλ‘ λμ½λμ μμΈ‘μ μ¬μ©νλ λμ
# μ€μ λͺ©ν μΆλ ₯μ λ€μ μ
λ ₯μΌλ‘ μ¬μ©νλ 컨μ
μ
λλ€.
# "Teacher forcing"μ μ¬μ©νλ©΄ μλ ΄μ΄ λΉ¨λ¦¬λμ§λ§ `νμ΅λ λ€νΈμν¬κ°
# μλͺ» μ¬μ©λ λ λΆμμ μ±μ 보μ
λλ€.
# <http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.378.4095&rep=rep1&type=pdf>`__.
#
# Teacher-forced λ€νΈμν¬μ μΆλ ₯μ΄ μΌκ΄λ λ¬Έλ²μΌλ‘ μ½μ§λ§ μ νν
# λ²μκ³Όλ κ±°λ¦¬κ° λ©λ€λ κ²μ λ³Ό μ μμ΅λλ€. μ§κ΄μ μΌλ‘ μΆλ ₯ λ¬Έλ²μ
# νννλ λ²μ λ°°μ°κ³ κ΅μ¬κ° μ²μ λͺ λ¨μ΄λ₯Ό λ§νλ©΄ μλ―Έλ₯Ό "μ ν" ν μ μμ§λ§,
# λ²μμμ μ²μμΌλ‘ λ¬Έμ₯μ λ§λλ λ²μ μ λ°°μ°μ§ λͺ»ν©λλ€.
#
# PyTorchμ autograd κ° μ 곡νλ μμ λλΆμ κ°λ¨ν If λ¬ΈμΌλ‘
# Teacher Forcingμ μ¬μ©ν μ§ μλλ©΄ μ¬μ©νμ§ μμμ§λ₯Ό μ νν μ μμ΅λλ€.
# λ λ§μ΄ μ¬μ©νλ €λ©΄ ``teacher_forcing_ratio`` λ₯Ό νμΈνμμμ€.
#
def train_epoch(dataloader, encoder, decoder, encoder_optimizer,
decoder_optimizer, criterion):
total_loss = 0
for data in dataloader:
input_tensor, target_tensor = data
encoder_optimizer.zero_grad()
decoder_optimizer.zero_grad()
encoder_outputs, encoder_hidden = encoder(input_tensor)
decoder_outputs, _, _ = decoder(encoder_outputs, encoder_hidden, target_tensor)
loss = criterion(
decoder_outputs.view(-1, decoder_outputs.size(-1)),
target_tensor.view(-1)
)
loss.backward()
encoder_optimizer.step()
decoder_optimizer.step()
total_loss += loss.item()
return total_loss / len(dataloader)
######################################################################
# μ΄κ²μ νμ¬ μκ°κ³Ό μ§νλ₯ %μ κ³ λ €ν΄ κ²½κ³Όλ μκ°κ³Ό λ¨μ μμ
# μκ°μ μΆλ ₯νλ ν¬νΌ ν¨μμ
λλ€.
#
import time
import math
def asMinutes(s):
m = math.floor(s / 60)
s -= m * 60
return '%dm %ds' % (m, s)
def timeSince(since, percent):
now = time.time()
s = now - since
es = s / (percent)
rs = es - s
return '%s (- %s)' % (asMinutes(s), asMinutes(rs))
######################################################################
# μ 체 νμ΅ κ³Όμ μ λ€μκ³Ό κ°μ΅λλ€:
#
# - νμ΄λ¨Έ μμ
# - optimizersμ criterion μ΄κΈ°ν
# - νμ΅ μμ μΈνΈ μμ±
# - λμνλ₯Ό μν λΉ μμ€ λ°°μ΄ μμ
#
# κ·Έλ° λ€μ μ°λ¦¬λ μ¬λ¬ λ² ``train`` μ νΈμΆνλ©° λλ‘λ μ§νλ₯
# (μμ μ %, νμ¬κΉμ§μ μμ μκ°)κ³Ό νκ· μμ€μ μΆλ ₯ν©λλ€.
#
def train(train_dataloader, encoder, decoder, n_epochs, learning_rate=0.001,
print_every=100, plot_every=100):
start = time.time()
plot_losses = []
print_loss_total = 0 # Reset every print_every
plot_loss_total = 0 # Reset every plot_every
encoder_optimizer = optim.Adam(encoder.parameters(), lr=learning_rate)
decoder_optimizer = optim.Adam(decoder.parameters(), lr=learning_rate)
criterion = nn.NLLLoss()
for epoch in range(1, n_epochs + 1):
loss = train_epoch(train_dataloader, encoder, decoder, encoder_optimizer, decoder_optimizer, criterion)
print_loss_total += loss
plot_loss_total += loss
if epoch % print_every == 0:
print_loss_avg = print_loss_total / print_every
print_loss_total = 0
print('%s (%d %d%%) %.4f' % (timeSince(start, epoch / n_epochs),
epoch, epoch / n_epochs * 100, print_loss_avg))
if epoch % plot_every == 0:
plot_loss_avg = plot_loss_total / plot_every
plot_losses.append(plot_loss_avg)
plot_loss_total = 0
showPlot(plot_losses)
######################################################################
#
# κ²°κ³Ό λμν
# ----------------
#
# matplotlibλ‘ νμ΅ μ€μ μ μ₯λ μμ€ κ° ``plot_losses`` μ λ°°μ΄μ
# μ¬μ©νμ¬ λμνν©λλ€.
#
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import matplotlib.ticker as ticker
import numpy as np
def showPlot(points):
plt.figure()
fig, ax = plt.subplots()
# μ£ΌκΈ°μ μΈ κ°κ²©μΌλ‘ μ΄ locatorκ° tickμ μ€μ
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
######################################################################
#
# νκ°
# ==========
#
# νκ°λ λλΆλΆ νμ΅κ³Ό λμΌνμ§λ§ λͺ©νκ° μμΌλ―λ‘ κ° λ¨κ³λ§λ€ λμ½λμ
# μμΈ‘μ λλλ € μ λ¬ν©λλ€.
# λ¨μ΄λ₯Ό μμΈ‘ν λλ§λ€ κ·Έ λ¨μ΄λ₯Ό μΆλ ₯ λ¬Έμμ΄μ μΆκ°ν©λλ€.
# λ§μ½ EOS ν ν°μ μμΈ‘νλ©΄ κ±°κΈ°μμ λ©μΆ₯λλ€.
# λμ€μ λμνλ₯Ό μν΄μ λμ½λμ Attention μΆλ ₯μ μ μ₯ν©λλ€.
#
def evaluate(encoder, decoder, sentence, input_lang, output_lang):
with torch.no_grad():
input_tensor = tensorFromSentence(input_lang, sentence)
encoder_outputs, encoder_hidden = encoder(input_tensor)
decoder_outputs, decoder_hidden, decoder_attn = decoder(encoder_outputs, encoder_hidden)
_, topi = decoder_outputs.topk(1)
decoded_ids = topi.squeeze()
decoded_words = []
for idx in decoded_ids:
if idx.item() == EOS_token:
decoded_words.append('<EOS>')
break
decoded_words.append(output_lang.index2word[idx.item()])
return decoded_words, decoder_attn
######################################################################
#
# νμ΅ μΈνΈμ μλ μμμ λ¬Έμ₯μΌλ‘ νκ°ν λ€μ, μ
λ ₯(input), λͺ©ν(target)
# λ° μΆλ ₯(output) κ°λ€μ νμνμ¬ μ£Όκ΄μ μΌλ‘ νμ§μ λν΄ νλ¨ν΄λ³Ό μ μμ΅λλ€:
#
def evaluateRandomly(encoder, decoder, n=10):
for i in range(n):
pair = random.choice(pairs)
print('>', pair[0])
print('=', pair[1])
output_words, _ = evaluate(encoder, decoder, pair[0], input_lang, output_lang)
output_sentence = ' '.join(output_words)
print('<', output_sentence)
print('')
######################################################################
# νμ΅κ³Ό νκ°
# =======================
#
# μ΄λ¬ν λͺ¨λ ν¬νΌ ν¨μλ₯Ό μ΄μ©ν΄μ (μΆκ° μμ
μ²λΌ 보μ΄μ§λ§ μ¬λ¬ μ€νμ
# λ μ½κ² μν ν μ μμ) μ€μ λ‘ λ€νΈμν¬λ₯Ό μ΄κΈ°ννκ³ νμ΅μ
# μμν μ μμ΅λλ€.
#
# μ
λ ₯ λ¬Έμ₯μ΄ λ§μ΄ νν°λ§λμμμ κΈ°μ΅νμμμ€. μ΄ μμ λ°μ΄ν° μΈνΈμ
# κ²½μ° 256 ν¬κΈ°μ μλ λ
Έλ(hidden node)μ λ¨μΌ GRU κ³μΈ΅ κ°μ μλμ μΌλ‘ μμ
# λ€νΈμν¬λ₯Ό μ¬μ©ν μ μμ΅λλ€. MacBook CPUμμ μ½ 40λΆ νμ
# ν©λ¦¬μ μΈ κ²°κ³Όλ₯Ό μ»μ κ²μ
λλ€.
#
# .. Note::
# μ΄ λ
ΈνΈλΆμ μ€ννλ©΄ νμ΅, 컀λ μ€λ¨, νκ°λ₯Ό ν μ μκ³ λμ€μ
# μ΄μ΄μ νμ΅μ ν μ μμ΅λλ€. μΈμ½λμ λμ½λκ° μ΄κΈ°ν λ νμ
# μ£Όμ μ²λ¦¬νκ³ ``trainIters`` λ₯Ό λ€μ μ€ννμμμ€.
#
hidden_size = 128
batch_size = 32
input_lang, output_lang, train_dataloader = get_dataloader(batch_size)
encoder = EncoderRNN(input_lang.n_words, hidden_size).to(device)
decoder = AttnDecoderRNN(hidden_size, output_lang.n_words).to(device)
train(train_dataloader, encoder, decoder, 80, print_every=5, plot_every=5)
######################################################################
#
#
# λλ‘μμ(dropout) λ μ΄μ΄λ€μ νκ° (``eval``) λͺ¨λλ‘ μ€μ ν©λλ€.
encoder.eval()
decoder.eval()
evaluateRandomly(encoder, decoder)
######################################################################
# Attention μκ°ν
# ---------------------
#
# Attention λ©μ»€λμ¦μ μ μ©ν μμ±μ νλλ ν΄μ κ°λ₯μ±μ΄ λμ μΆλ ₯μ
λλ€.
# μ
λ ₯ μνμ€μ νΉμ μΈμ½λ μΆλ ₯μ κ°μ€μΉλ₯Ό λΆμ¬νλ λ° μ¬μ©λλ―λ‘
# κ° μκ° λ¨κ³μμ λ€νΈμν¬κ° κ°μ₯ μ§μ€λλ μμΉλ₯Ό νμ
ν μ μμ΅λλ€.
#
# Attention μΆλ ₯μ νλ ¬λ‘ νμνκΈ° μν΄μλ ``plt.matshow(attentions)`` μ
# κ·Έλ₯ μ€νν΄λ λ©λλ€. νμ§λ§ μ’ λ λμ μκ°νλ₯Ό μν΄ μΆ(axis)κ³Ό λΌλ²¨(label)μ
# μΆκ°νλ μ½κ°μ μμ
μ λ ν΄λ³΄κ² μ΅λλ€:
#
def showAttention(input_sentence, output_words, attentions):
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
fig.colorbar(cax)
# μΆ μ€μ
ax.set_xticklabels([''] + input_sentence.split(' ') +
['<EOS>'], rotation=90)
ax.set_yticklabels([''] + output_words)
# λ§€ ν±λ§λ€ λΌλ²¨ 보μ¬μ£ΌκΈ°
ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.show()
def evaluateAndShowAttention(input_sentence):
output_words, attentions = evaluate(encoder, decoder, input_sentence, input_lang, output_lang)
print('input =', input_sentence)
print('output =', ' '.join(output_words))
showAttention(input_sentence, output_words, attentions[0, :len(output_words), :])
evaluateAndShowAttention('il n est pas aussi grand que son pere')
evaluateAndShowAttention('je suis trop fatigue pour conduire')
evaluateAndShowAttention('je suis desole si c est une question idiote')
evaluateAndShowAttention('je suis reellement fiere de vous')
######################################################################
# μ°μ΅
# =========
#
# - λ€λ₯Έ λ°μ΄ν° μ
μ μλν΄ λ³΄μμμ€
#
# - λ€λ₯Έ μΈμ΄μ
# - μ¬λ β κΈ°κ³ (e.g. IOT λͺ
λ Ήμ΄)
# - μ±ν
β μλ΅
# - μ§λ¬Έ β λ΅λ³
#
# - ``word2vec`` λλ ``GloVe`` κ°μ 미리 νμ΅λ word embedding μΌλ‘
# embedding μ κ΅μ²΄νμμμ€
#
# - λ λ§μ λ μ΄μ΄, μλ μ λ, λ λ§μ λ¬Έμ₯μ μ¬μ©νμμμ€.
# νμ΅ μκ°κ³Ό κ²°κ³Όλ₯Ό λΉκ΅ν΄ 보μμμ€
# - λ§μ½ κ°μ ꡬ문 λκ°μ μμΌλ‘ λ λ²μ νμΌμ μ΄μ©νλ€λ©΄,
# (``I am test \t I am test``), μ΄κ²μ μ€ν μΈμ½λλ‘
# μ¬μ©ν μ μμ΅λλ€.
# μ΄κ²μ μλν΄ λ³΄μμμ€:
#
# - μ€ν μΈμ½λ νμ΅
# - μΈμ½λ λ€νΈμν¬ μ μ₯νκΈ°
# - κ·Έ μνμμ λ²μμ μν μλ‘μ΄ λμ½λ νμ΅
#