パート2:テキストの前処理

Kerasで学ぶMachine Translation

Thushan Ganegedara

Data Scientist and Author

開始/終了トークンの追加

次の文:

'les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre .'

は、次のようになります。

'sos les états-unis est parfois occupé en janvier , et il est parfois chaud en novembre . eos',

特別トークンを追加すると

  • sos - 文/系列の開始
  • eos - 文/系列の終了
Kerasで学ぶMachine Translation

文のパディング

  • 実データでは、すべての文の語数は同じではない

  • pad_sequences を読み込む

from tensorflow.keras.preprocessing.sequence import pad_sequences
  • 文を系列に変換する
sentences = [
  'new jersey is sometimes quiet during autumn .',
  'california is never rainy during july , but it is sometimes beautiful in february .'
]
seqs = en_tok.texts_to_sequences(sentences)
Kerasで学ぶMachine Translation

文のパディング

preproc_text = pad_sequences(seqs, padding='post', truncating='post', maxlen=12)

for orig, padded in zip(seqs, preproc_text): print(orig, ' => ', padded)

最初の文は末尾に 0 が5つ追加される:

#  'new jersey is sometimes quiet during autumn .',
[18, 20, 2, 10, 32, 5, 46]  =>  [18 20  2 10 32  5 46  0  0  0  0  0]

2つ目の文は末尾の語が1つ切り詰められる:

# 'california is never rainy during july , but it is sometimes beautiful in february .'
[21, 2, 11, 47, 5, 41, 7, 4, 2, 10, 30, 3, 38]  =>  [ 12 2 11 47  5 41  7  4  2 10 30  3]
  • Keras では 0 は単語IDに割り当てられない
Kerasで学ぶMachine Translation

文を反転する利点

  • エンコーダとデコーダの初期結合を強めるのに有効

反転あり/なしの距離

Kerasで学ぶMachine Translation

文を反転する

  • パディングした系列を作成し、時間方向に反転する
    sentences = ["california is never rainy during july .",]
    seqs = en_tok.texts_to_sequences(sentences)
    pad_seq = preproc_text = pad_sequences(seqs, padding='post', truncating='post', maxlen=12)
    
[[21  2  9 25  5 27  0  0  0  0  0  0]]
Kerasで学ぶMachine Translation

文を反転する

pad_seq
[[21  2  9 25  5 27  0  0  0  0  0  0]]
pad_seq = pad_seq[:,::-1]
[[ 0  0  0  0  0  0 27  5 25  9  2 21]]
rev_sent = [en_tok.index_word[wid] for wid in pad_seq[0][-6:]] 
print('Sentence: ', sentences[0])
print('\tReversed: ',' '.join(rev_sent))
Sentence:  california is never rainy during july .
    Reversed:  july during rainy never is california
Kerasで学ぶMachine Translation

Passons à la pratique !

Kerasで学ぶMachine Translation

Preparing Video For Download...