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