第 2 部分:文字前處理

使用 Keras 進行機器翻譯

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 進行機器翻譯

句子補齊(Padding)

  • 真實世界的資料集中,各句子長度不會相同

  • 匯入 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 進行機器翻譯

句子補齊(Padding)

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

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

第一句在結尾補上五個 0:

#  '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]

第二句在結尾截斷一個字:

# '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 進行機器翻譯

反轉句子的好處

  • 有助於在編碼器與解碼器之間建立更強的初始連結

反轉與否的距離

使用 Keras 進行機器翻譯

反轉句子

  • 產生補齊序列,並在時間維度上反轉序列
    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 進行機器翻譯

反轉句子

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 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...