实现编码器

使用 Keras 的机器翻译

Thushan Ganegedara

Data Scientist and Author

理解数据

打印数据集中的部分数据

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 .

English:  california is usually quiet during march , and it is usually hot in june .
    French:  california est généralement calme en mars , et il est généralement chaud en juin .
使用 Keras 的机器翻译

对句子进行分词

分词

  • 将句子/短语拆分为独立的标记(如单词)的过程

对句子进行词级分词

first_sent = en_text[0]
print("First sentence: ", first_sent)
first_words = first_sent.split(" ")
print("\tWords: ", first_words)
First sentence:  new jersey is sometimes quiet during autumn , and it is snowy in april .
    Words:  ['new', 'jersey', 'is', 'sometimes', 'quiet', 'during', 'autumn', ',', 
             'and', 'it', 'is', 'snowy', 'in', 'april', '.']
使用 Keras 的机器翻译

计算句子长度

计算句子平均长度与词表大小(英语)

sent_lengths = [len(en_sent.split(" ")) for en_sent in en_text]
mean_length = np.mean(sent_lengths)
print('(English) Mean sentence length: ', mean_length)
(English) Mean sentence length:  13.20662
使用 Keras 的机器翻译

计算词表大小

all_words = []
for sent in en_text:
    all_words.extend(sent.split(" "))
vocab_size = len(set(all_words))
print("(English) Vocabulary size: ", vocab_size)
  • set 对象只包含唯一项,不含重复
(English) Vocabulary size:  228
使用 Keras 的机器翻译

编码器

编码器

使用 Keras 的机器翻译

用 Keras 实现编码器

  • 输入层
    en_inputs = Input(shape=(en_len, en_vocab))
    
  • GRU 层
    en_gru = GRU(hsize, return_state=True)
    en_out, en_state = en_gru(en_inputs)
    
  • Keras 模型
    encoder = Model(inputs=en_inputs, outputs=en_state)
    
使用 Keras 的机器翻译

理解 Keras 模型摘要

print(encoder.summary())
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, 15, 150)           0         
_________________________________________________________________
gru (GRU)                    [(None, 48), (None, 48)]  28656     
=================================================================
Total params: 28,656
Trainable params: 28,656
Non-trainable params: 0
_________________________________________________________________
使用 Keras 的机器翻译

让我们练习!

使用 Keras 的机器翻译

Preparing Video For Download...