第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
    • 需先在句子上拟合,以学习"词→ID"映射
en_tok = Tokenizer()
en_tok.fit_on_texts(en_text)
  • 获取词到 ID 的映射
    • 使用 Tokenizerword_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)词

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

Passons à la pratique !

使用 Keras 的机器翻译

Preparing Video For Download...