
作者 | Francois Chollet
編譯 | CDA數(shù)據(jù)分析師
A ten-minute introduction to sequence-to-sequence learning in Keras
什么是順序?qū)W習(xí)?
序列到序列學(xué)習(xí)(Seq2Seq)是關(guān)于將模型從一個域(例如英語中的句子)轉(zhuǎn)換為另一域(例如將相同句子翻譯為法語的序列)的訓(xùn)練模型。
“貓坐在墊子上” -> [ Seq2Seq 模型] -> “在小吃中聊天
這可用于機器翻譯或免費問答(在給定自然語言問題的情況下生成自然語言答案)-通常,它可在需要生成文本的任何時間使用。
有多種處理此任務(wù)的方法,可以使用RNN或使用一維卷積網(wǎng)絡(luò)。在這里,我們將重點介紹RNN。
普通情況:輸入和輸出序列的長度相同
當輸入序列和輸出序列的長度相同時,您可以簡單地使用Keras LSTM或GRU層(或其堆棧)來實現(xiàn)此類模型。在此示例腳本 中就是這種情況, 該腳本顯示了如何教RNN學(xué)習(xí)加編碼為字符串的數(shù)字:
該方法的一個警告是,它假定可以生成target[...t]給定input[...t]。在某些情況下(例如添加數(shù)字字符串),該方法有效,但在大多數(shù)用例中,則無效。在一般情況下,有關(guān)整個輸入序列的信息是必需的,以便開始生成目標序列。
一般情況:規(guī)范序列間
在一般情況下,輸入序列和輸出序列具有不同的長度(例如,機器翻譯),并且需要整個輸入序列才能開始預(yù)測目標。這需要更高級的設(shè)置,這是人們在沒有其他上下文的情況下提到“序列模型的序列”時通常所指的東西。運作方式如下:
RNN層(或其堆棧)充當“編碼器”:它處理輸入序列并返回其自己的內(nèi)部狀態(tài)。請注意,我們放棄了編碼器RNN的輸出,僅恢復(fù) 了狀態(tài)。在下一步中,此狀態(tài)將用作解碼器的“上下文”或“條件”。
另一個RNN層(或其堆棧)充當“解碼器”:在給定目標序列的先前字符的情況下,對其進行訓(xùn)練以預(yù)測目標序列的下一個字符。具體而言,它經(jīng)過訓(xùn)練以將目標序列變成相同序列,但在將來會偏移一個時間步,在這種情況下,該訓(xùn)練過程稱為“教師強迫”。重要的是,編碼器使用來自編碼器的狀態(tài)向量作為初始狀態(tài),這就是解碼器如何獲取有關(guān)應(yīng)該生成的信息的方式。有效地,解碼器學(xué)會產(chǎn)生targets[t+1...] 給定的targets[...t],調(diào)節(jié)所述輸入序列。
在推斷模式下,即當我們想解碼未知的輸入序列時,我們會經(jīng)歷一個略有不同的過程:
同樣的過程也可以用于訓(xùn)練Seq2Seq網(wǎng)絡(luò),而無需 “教師強制”,即通過將解碼器的預(yù)測重新注入到解碼器中。
一個Keras例子
因為訓(xùn)練過程和推理過程(解碼句子)有很大的不同,所以我們對兩者使用不同的模型,盡管它們都利用相同的內(nèi)部層。
這是我們的訓(xùn)練模型。它利用Keras RNN的三個關(guān)鍵功能:
return_state構(gòu)造器參數(shù),配置RNN層返回一個列表,其中,第一項是輸出與下一個條目是內(nèi)部RNN狀態(tài)。這用于恢復(fù)編碼器的狀態(tài)。
inital_state呼叫參數(shù),指定一個RNN的初始狀態(tài)(S)。這用于將編碼器狀態(tài)作為初始狀態(tài)傳遞給解碼器。
return_sequences構(gòu)造函數(shù)的參數(shù),配置RNN返回其輸出全序列(而不只是最后的輸出,其默認行為)。在解碼器中使用。
from keras.models import Model from keras.layers import Input, LSTM, Dense # Define an input sequence and process it. encoder_inputs = Input(shape=(None, num_encoder_tokens)) encoder = LSTM(latent_dim, return_state=True) encoder_outputs, state_h, state_c = encoder(encoder_inputs) # We discard `encoder_outputs` and only keep the states. encoder_states = [state_h, state_c] # Set up the decoder, using `encoder_states` as initial state. decoder_inputs = Input(shape=(None, num_decoder_tokens)) # We set up our decoder to return full output sequences, # and to return internal states as well. We don't use the # return states in the training model, but we will use them in inference. decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True) decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states) decoder_dense = Dense(num_decoder_tokens, activation='softmax') decoder_outputs = decoder_dense(decoder_outputs) # Define the model that will turn # `encoder_input_data` & `decoder_input_data` into `decoder_target_data` model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
我們分兩行訓(xùn)練我們的模型,同時監(jiān)視20%的保留樣本中的損失。
# Run training model.compile(optimizer='rmsprop', loss='categorical_crossentropy') model.fit([encoder_input_data, decoder_input_data], decoder_target_data, batch_size=batch_size, epochs=epochs, validation_split=0.2)
在MacBook CPU上運行大約一個小時后,我們就可以進行推斷了。為了解碼測試語句,我們將反復(fù):
這是我們的推理設(shè)置:
encoder_model = Model(encoder_inputs, encoder_states) decoder_state_input_h = Input(shape=(latent_dim,)) decoder_state_input_c = Input(shape=(latent_dim,)) decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c] decoder_outputs, state_h, state_c = decoder_lstm( decoder_inputs, initial_state=decoder_states_inputs) decoder_states = [state_h, state_c] decoder_outputs = decoder_dense(decoder_outputs) decoder_model = Model( [decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states)
我們使用它來實現(xiàn)上述推理循環(huán):
def decode_sequence(input_seq): # Encode the input as state vectors. states_value = encoder_model.predict(input_seq) # Generate empty target sequence of length 1. target_seq = np.zeros((1, 1, num_decoder_tokens)) # Populate the first character of target sequence with the start character. target_seq[0, 0, target_token_index['\t']] = 1. # Sampling loop for a batch of sequences # (to simplify, here we assume a batch of size 1). stop_condition = False decoded_sentence = '' while not stop_condition: output_tokens, h, c = decoder_model.predict( [target_seq] + states_value) # Sample a token sampled_token_index = np.argmax(output_tokens[0, -1, :]) sampled_char = reverse_target_char_index[sampled_token_index] decoded_sentence += sampled_char # Exit condition: either hit max length # or find stop character. if (sampled_char == '\n' or len(decoded_sentence) > max_decoder_seq_length): stop_condition = True # Update the target sequence (of length 1). target_seq = np.zeros((1, 1, num_decoder_tokens)) target_seq[0, 0, sampled_token_index] = 1. # Update states states_value = [h, c] return decoded_sentence
我們得到了一些不錯的結(jié)果-毫不奇怪,因為我們正在解碼從訓(xùn)練測試中提取的樣本
Input sentence: Be nice. Decoded sentence: Soyez gentil ! - Input sentence: Drop it! Decoded sentence: Laissez tomber ! - Input sentence: Get out! Decoded sentence: Sortez?!
到此,我們結(jié)束了對Keras中序列到序列模型的十分鐘介紹。提醒:此腳本的完整代碼可以在GitHub上找到。
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗與 t 檢驗:差異、適用場景與實踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計學(xué)領(lǐng)域,假設(shè)檢驗是驗證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計劃中 rows 數(shù)量的準確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實踐指南 在 Python 進行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點數(shù)據(jù)的科學(xué)計數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點數(shù)據(jù)時的科學(xué)計數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計” 與 “用戶體驗 ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當下,精準營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10