第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 的机器翻译

填充句子

  • 真实数据集的句子长度并不相同

  • 导入 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 的机器翻译

填充句子

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 的机器翻译

Vamos praticar!

使用 Keras 的机器翻译

Preparing Video For Download...