Phần 2: Tiền xử lý văn bản

Machine Translation với Keras

Thushan Ganegedara

Data Scientist and Author

Thêm token bắt đầu/kết thúc

Câu:

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

trở thành:

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

sau khi thêm token đặc biệt

  • sos - Bắt đầu câu/chuỗi
  • eos - Kết thúc câu/chuỗi
Machine Translation với Keras

Đệm (padding) các câu

  • Dữ liệu thực tế hiếm khi có số từ bằng nhau trong mọi câu

  • Import pad_sequences

from tensorflow.keras.preprocessing.sequence import pad_sequences
  • Chuyển câu thành chuỗi
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)
Machine Translation với Keras

Đệm (padding) các câu

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

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

Câu đầu được đệm năm số 0 ở cuối:

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

Câu thứ hai bị cắt bớt một từ ở cuối:

# '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]
  • Trong Keras, 0 không bao giờ được gán làm ID từ
Machine Translation với Keras

Lợi ích của việc đảo câu

  • Giúp tăng liên kết ban đầu giữa encoder và decoder

Khoảng cách có và không đảo ngược

Machine Translation với Keras

Đảo ngược câu

  • Tạo chuỗi đã đệm và đảo chuỗi theo trục thời gian
    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]]
Machine Translation với Keras

Đảo ngược câu

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
Machine Translation với Keras

Ayo berlatih!

Machine Translation với Keras

Preparing Video For Download...