
作者 | Francois Chollet
編譯 | CDA數(shù)據(jù)分析師
A ten-minute introduction to sequence-to-sequence learning in Keras
什么是順序學習?
序列到序列學習(Seq2Seq)是關于將模型從一個域(例如英語中的句子)轉換為另一域(例如將相同句子翻譯為法語的序列)的訓練模型。
“貓坐在墊子上” -> [ Seq2Seq 模型] -> “在小吃中聊天
這可用于機器翻譯或免費問答(在給定自然語言問題的情況下生成自然語言答案)-通常,它可在需要生成文本的任何時間使用。
有多種處理此任務的方法,可以使用RNN或使用一維卷積網絡。在這里,我們將重點介紹RNN。
普通情況:輸入和輸出序列的長度相同
當輸入序列和輸出序列的長度相同時,您可以簡單地使用Keras LSTM或GRU層(或其堆棧)來實現(xiàn)此類模型。在此示例腳本 中就是這種情況, 該腳本顯示了如何教RNN學習加編碼為字符串的數(shù)字:
該方法的一個警告是,它假定可以生成target[...t]給定input[...t]。在某些情況下(例如添加數(shù)字字符串),該方法有效,但在大多數(shù)用例中,則無效。在一般情況下,有關整個輸入序列的信息是必需的,以便開始生成目標序列。
一般情況:規(guī)范序列間
在一般情況下,輸入序列和輸出序列具有不同的長度(例如,機器翻譯),并且需要整個輸入序列才能開始預測目標。這需要更高級的設置,這是人們在沒有其他上下文的情況下提到“序列模型的序列”時通常所指的東西。運作方式如下:
RNN層(或其堆棧)充當“編碼器”:它處理輸入序列并返回其自己的內部狀態(tài)。請注意,我們放棄了編碼器RNN的輸出,僅恢復 了狀態(tài)。在下一步中,此狀態(tài)將用作解碼器的“上下文”或“條件”。
另一個RNN層(或其堆棧)充當“解碼器”:在給定目標序列的先前字符的情況下,對其進行訓練以預測目標序列的下一個字符。具體而言,它經過訓練以將目標序列變成相同序列,但在將來會偏移一個時間步,在這種情況下,該訓練過程稱為“教師強迫”。重要的是,編碼器使用來自編碼器的狀態(tài)向量作為初始狀態(tài),這就是解碼器如何獲取有關應該生成的信息的方式。有效地,解碼器學會產生targets[t+1...] 給定的targets[...t],調節(jié)所述輸入序列。
在推斷模式下,即當我們想解碼未知的輸入序列時,我們會經歷一個略有不同的過程:
同樣的過程也可以用于訓練Seq2Seq網絡,而無需 “教師強制”,即通過將解碼器的預測重新注入到解碼器中。
一個Keras例子
因為訓練過程和推理過程(解碼句子)有很大的不同,所以我們對兩者使用不同的模型,盡管它們都利用相同的內部層。
這是我們的訓練模型。它利用Keras RNN的三個關鍵功能:
return_state構造器參數(shù),配置RNN層返回一個列表,其中,第一項是輸出與下一個條目是內部RNN狀態(tài)。這用于恢復編碼器的狀態(tài)。
inital_state呼叫參數(shù),指定一個RNN的初始狀態(tài)(S)。這用于將編碼器狀態(tài)作為初始狀態(tài)傳遞給解碼器。
return_sequences構造函數(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)
我們分兩行訓練我們的模型,同時監(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上運行大約一個小時后,我們就可以進行推斷了。為了解碼測試語句,我們將反復:
這是我們的推理設置:
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
我們得到了一些不錯的結果-毫不奇怪,因為我們正在解碼從訓練測試中提取的樣本
Input sentence: Be nice. Decoded sentence: Soyez gentil ! - Input sentence: Drop it! Decoded sentence: Laissez tomber ! - Input sentence: Get out! Decoded sentence: Sortez?!
到此,我們結束了對Keras中序列到序列模型的十分鐘介紹。提醒:此腳本的完整代碼可以在GitHub上找到。
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關鍵? 在循環(huán)神經網絡(RNN)家族中,長短期記憶網絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準備指南? ? 在數(shù)據(jù)驅動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務的價值轉化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數(shù)據(jù)查詢到趨勢預判? ? 在數(shù)據(jù)驅動決策的時代,預測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領域中,準確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內權威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網絡(LSTM)作為循環(huán)神經網絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調研數(shù)據(jù)中的深度應用? 市場調研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉日期:解鎖數(shù)據(jù)處理的關鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03