第 1 部分:資料前處理

使用 Keras 進行機器翻譯

Thushan Ganegedara

Data Scientist and Author

資料介紹

  • 資料

    • en_text :Python 的句子清單,每個句子是以空白分隔的字串。
    • fr_text:Python 的句子清單,每個句子是以空白分隔的字串。
  • 列印資料集中的部分資料

for en_sent, fr_sent in zip(en_text[:3], fr_text[:3]):
  print("English: ", en_sent)
  print("\tFrench: ", fr_sent)
English:  new jersey is sometimes quiet during autumn , and it is snowy in april .
    French:  new jersey est parfois calme pendant l' automne , et il est neigeux en avril .
English:  the united states is usually chilly during july , and it is usually freezing in november .
    French:  les états-unis est généralement froid en juillet , et il gèle habituellement en novembre .
...
使用 Keras 進行機器翻譯

單字斷詞

  • 斷詞(Tokenization)

    • 將句子/片語切成單字或字元的過程。
    • 例如:"I watched a movie last night, it was okay." 會變成
    • [I, watched, a, movie, last, night, it, was, okay]
  • 使用 Keras 進行斷詞

    • 以語料庫學習「單字 → 單字 ID」的對應。
    • 可把字串轉成 ID 序列。
from tensorflow.keras.preprocessing.text import Tokenizer
en_tok = Tokenizer()
使用 Keras 進行機器翻譯

擬合 Tokenizer

  • 在資料上擬合 Tokenizer
    • Tokenizer 需先用一些句子擬合,才能學到單字到 ID 的對應。
en_tok = Tokenizer()
en_tok.fit_on_texts(en_text)
  • 取得「單字 → ID」對應
    • 使用 Tokenizer 的 word_index 屬性。
id = en_tok.word_index["january"] # => returns 51
  • 取得「ID → 單字」對應
w = en_tok.index_word[51] # => returns 'january'
使用 Keras 進行機器翻譯

將句子轉成序列

seq = en_tok.texts_to_sequences(['she likes grapefruit , peaches , and lemons .'])
[[26, 70, 27, 73, 7, 74]]
使用 Keras 進行機器翻譯

限制詞彙表大小

  • 你可以在 Keras 的 Tokenizer 中限制詞彙表大小。
tok = Tokenizer(num_words=50)
  • 超出詞彙表(OOV)單字

    • 訓練語料中的罕見單字。
    • 或未出現在訓練集的單字。
  • 例如:

    • tok.fit_on_texts(["I drank milk"])
    • tok.texts_to_sequences(["I drank water"])
    • 單字 water 是 OOV,會被忽略。
使用 Keras 進行機器翻譯

處理超出詞彙表的單字

  • 定義 OOV 標記
tok = Tokenizer(num_words=50, oov_token='UNK')
  • 例如:
    • tok.fit_on_texts(["I drank milk"])
    • tok.texts_to_sequences(["I drank water"])
    • 單字 water 是 OOV,會被替換為 UNK。
      • 也就是說,Keras 會看到 "I drank UNK"
使用 Keras 進行機器翻譯

一起來練習吧!

使用 Keras 進行機器翻譯

Preparing Video For Download...