<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 如何開發一個單詞級神經語言模型并用它來生成文本 > 原文: [https://machinelearningmastery.com/how-to-develop-a-word-level-neural-language-model-in-keras/](https://machinelearningmastery.com/how-to-develop-a-word-level-neural-language-model-in-keras/) 語言模型可以基于序列中已經觀察到的單詞來預測序列中下一個單詞的概率。 神經網絡模型是開發統計語言模型的首選方法,因為它們可以使用分布式表示,其中具有相似含義的不同單詞具有相似的表示,并且因為它們在進行預測時可以使用最近觀察到的單詞的大的上下文。 在本教程中,您將了解如何使用 Python 中的深度學習開發統計語言模型。 完成本教程后,您將了解: * 如何準備文本以開發基于單詞的語言模型。 * 如何設計和擬合具有學習嵌入和 LSTM 隱藏層的神經語言模型。 * 如何使用學習的語言模型生成具有與源文本類似的統計屬性的新文本。 讓我們開始吧。 * **Update Apr / 2018** :修正了模型描述中 100 個輸入字與實際模型中 50 個輸入字之間的不匹配。 ![How to Develop a Word-Level Neural Language Model and Use it to Generate Text](img/d0ee6a8a9a2fc43e0ab26fc902881264.jpg) 如何開發一個單詞級神經語言模型并用它來生成文本 照片由 [Carlo Raso](https://www.flickr.com/photos/70125105@N06/32512473990/) 拍攝,保留一些權利。 ## 教程概述 本教程分為 4 個部分;他們是: 1. 柏拉圖共和國 2. 數據準備 3. 訓練語言模型 4. 使用語言模型 ## 柏拉圖共和國 [共和國](https://en.wikipedia.org/wiki/Republic_(Plato))是古典希臘哲學家柏拉圖最著名的作品。 它被構建為關于城市國家內秩序和正義主題的對話(例如對話) 整個文本在公共領域免費提供。它可以在 [Project Gutenberg 網站](https://www.gutenberg.org/ebooks/1497)上以多種格式獲得。 您可以在此處下載整本書(或書籍)的 ASCII 文本版本: * [下載柏拉圖共和國](http://www.gutenberg.org/cache/epub/1497/pg1497.txt) 下載書籍文本并將其直接放在當前工作中,文件名為“ _republic.txt_ ” 在文本編輯器中打開文件并刪除前后問題。這包括開頭的書籍詳細信息,長篇分析以及最后的許可證信息。 案文應以: > 書 I. > > 我昨天和阿里斯頓的兒子格勞孔一起去了比雷埃夫斯, > ...... 結束 > ...... > 在這一生和我們一直描述的千年朝圣中,我們都應該好好相處。 將清理后的版本保存為' _republic_clean。當前工作目錄中的 _ txt'。該文件應該是大約 15,802 行文本。 現在我們可以從這個文本開發一個語言模型。 ## 數據準備 我們將從準備建模數據開始。 第一步是查看數據。 ### 查看文本 在編輯器中打開文本,然后查看文本數據。 例如,這是第一個對話框: > 書 I. > > 我昨天和阿里斯頓的兒子 Glaucon 一起去了比雷埃夫斯, > 我可以向女神祈禱(Bendis,Thracian > Artemis。);而且因為我想看看他們以什么樣的方式 > 慶祝這個節日,這是一個新事物。我很滿意居民的 > 游行;但是色雷斯人的情況也是如此, > 即使不是更多,也是美麗的。當我們完成祈禱并觀看 > 景觀時,我們轉向了城市的方向;在那一瞬間 > Cephalus 的兒子 Polemarchus 偶然在我們回家的路上從 > 的距離看到了我們,并告訴他的仆人 > 跑去讓我們等他。仆人背后披著斗篷 > 抓住我,并說:Polemarchus 希望你等。 > > 我轉過身,問他的主人在哪里。 > > 他說,如果你只是等待,那么他就是那個年輕人。 > > 當然,我們會,Glaucon 說。幾分鐘后,Polemarchus > 出現了,并與他一起出現了 Glaucon 的兄弟 Adeimantus,Nicias 的兒子 Niceratus 以及其他幾位參加過游行的人。 > > Polemarchus 對我說:我認為,蘇格拉底,你和你的 > 同伴已經在前往城市的路上。 > > 我說,你沒錯。 > > ... 您認為我們在準備數據時需要處理什么? 以下是我從快速瀏覽中看到的內容: * 書/章標題(例如“BOOK I.”)。 * 英國英語拼寫(例如“榮幸”) * 標點符號很多(例如“ - ”,“; - ”,“? - ”等) * 奇怪的名字(例如“Polemarchus”)。 * 一些漫長的獨白,持續數百行。 * 一些引用的對話框(例如'...') 這些觀察以及更多建議以我們可能希望準備文本數據的方式提出。 我們準備數據的具體方式實際上取決于我們打算如何對其進行建模,而這又取決于我們打算如何使用它。 ### 語言模型設計 在本教程中,我們將開發一個文本模型,然后我們可以使用它來生成新的文本序列。 語言模型將是統計的,并且將預測給定輸入文本序列的每個單詞的概率。預測的單詞將作為輸入輸入,進而生成下一個單詞。 關鍵的設計決策是輸入序列應該有多長。它們需要足夠長以允許模型學習要預測的單詞的上下文。此輸入長度還將定義在使用模型時用于生成新序列的種子文本的長度。 沒有正確的答案。有了足夠的時間和資源,我們就可以探索模型用不同大小的輸入序列學習的能力。 相反,我們將為輸入序列的長度選擇 50 個字的長度,有點任意。 我們可以處理數據,以便模型只處理自包含的句子并填充或截斷文本以滿足每個輸入序列的這一要求。您可以將此作為本教程的擴展進行探索。 相反,為了使示例保持簡潔,我們將讓所有文本一起流動并訓練模型以預測文本中句子,段落甚至書籍或章節中的下一個單詞。 現在我們有一個模型設計,我們可以看看將原始文本轉換為 50 個輸入字到 1 個輸出字的序列,準備好適合模型。 ### 加載文字 第一步是將文本加載到內存中。 我們可以開發一個小函數來將整個文本文件加載到內存中并返回它。該函數名為 _load_doc()_,如下所示。給定文件名,它返回一個加載文本序列。 ```py # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text ``` 使用此函數,我們可以在文件' _republic_clean.txt_ '中加載文檔的清潔版本,如下所示: ```py # load document in_filename = 'republic_clean.txt' doc = load_doc(in_filename) print(doc[:200]) ``` 運行此代碼段會加載文檔并打印前 200 個字符作為完整性檢查。 > 書 I. > > 我昨天和阿里斯頓的兒子 Glaucon 一起去了比雷埃夫斯, > 我可以向女神祈禱(Bendis,Thracian > Artemis。);還因為我想知道什么 到現在為止還挺好。接下來,讓我們清理文本。 ### 干凈的文字 我們需要將原始文本轉換為一系列令牌或單詞,我們可以將其用作訓練模型的源。 基于查看原始文本(上文),下面是我們將執行的一些特定操作來清理文本。您可能希望自己探索更多清潔操作作為擴展。 * 將' - '替換為空格,以便我們可以更好地分割單詞。 * 基于空白區域的分詞。 * 從單詞中刪除所有標點符號以減少詞匯量大小(例如'What?'變為'What')。 * 刪除所有非字母的單詞以刪除獨立的標點符號。 * 將所有單詞標準化為小寫以減少詞匯量。 詞匯量大小與語言建模有很大關系。較小的詞匯量會導致較小的模型更快地訓練。 我們可以在一個函數中按此順序實現每個清理操作。下面是函數 _clean_doc()_,它將加載的文檔作為參數并返回一個干凈的標記數組。 ```py import string # turn a doc into clean tokens def clean_doc(doc): # replace '--' with a space ' ' doc = doc.replace('--', ' ') # split into tokens by white space tokens = doc.split() # remove punctuation from each token table = str.maketrans('', '', string.punctuation) tokens = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # make lower case tokens = [word.lower() for word in tokens] return tokens ``` 我們可以在加載的文檔上運行此清理操作,并打印出一些標記和統計信息作為完整性檢查。 ```py # clean document tokens = clean_doc(doc) print(tokens[:200]) print('Total Tokens: %d' % len(tokens)) print('Unique Tokens: %d' % len(set(tokens))) ``` 首先,我們可以看到一個很好的令牌列表,它看起來比原始文本更清晰。我們可以刪除' _Book I_ '章節標記等等,但這是一個好的開始。 ```py ['book', 'i', 'i', 'went', 'down', 'yesterday', 'to', 'the', 'piraeus', 'with', 'glaucon', 'the', 'son', 'of', 'ariston', 'that', 'i', 'might', 'offer', 'up', 'my', 'prayers', 'to', 'the', 'goddess', 'bendis', 'the', 'thracian', 'artemis', 'and', 'also', 'because', 'i', 'wanted', 'to', 'see', 'in', 'what', 'manner', 'they', 'would', 'celebrate', 'the', 'festival', 'which', 'was', 'a', 'new', 'thing', 'i', 'was', 'delighted', 'with', 'the', 'procession', 'of', 'the', 'inhabitants', 'but', 'that', 'of', 'the', 'thracians', 'was', 'equally', 'if', 'not', 'more', 'beautiful', 'when', 'we', 'had', 'finished', 'our', 'prayers', 'and', 'viewed', 'the', 'spectacle', 'we', 'turned', 'in', 'the', 'direction', 'of', 'the', 'city', 'and', 'at', 'that', 'instant', 'polemarchus', 'the', 'son', 'of', 'cephalus', 'chanced', 'to', 'catch', 'sight', 'of', 'us', 'from', 'a', 'distance', 'as', 'we', 'were', 'starting', 'on', 'our', 'way', 'home', 'and', 'told', 'his', 'servant', 'to', 'run', 'and', 'bid', 'us', 'wait', 'for', 'him', 'the', 'servant', 'took', 'hold', 'of', 'me', 'by', 'the', 'cloak', 'behind', 'and', 'said', 'polemarchus', 'desires', 'you', 'to', 'wait', 'i', 'turned', 'round', 'and', 'asked', 'him', 'where', 'his', 'master', 'was', 'there', 'he', 'is', 'said', 'the', 'youth', 'coming', 'after', 'you', 'if', 'you', 'will', 'only', 'wait', 'certainly', 'we', 'will', 'said', 'glaucon', 'and', 'in', 'a', 'few', 'minutes', 'polemarchus', 'appeared', 'and', 'with', 'him', 'adeimantus', 'glaucons', 'brother', 'niceratus', 'the', 'son', 'of', 'nicias', 'and', 'several', 'others', 'who', 'had', 'been', 'at', 'the', 'procession', 'polemarchus', 'said'] ``` 我們還獲得了有關干凈文檔的一些統計信息。 我們可以看到,干凈的文字中只有不到 120,000 個單詞,而且詞匯量不到 7,500 個單詞。這個很小,適合這些數據的模型應該可以在適度的硬件上進行管理。 ```py Total Tokens: 118684 Unique Tokens: 7409 ``` 接下來,我們可以看看將標記整形為序列并將它們保存到文件中。 ### 保存干凈的文字 我們可以將長令牌列表組織成 50 個輸入字和 1 個輸出字的序列。 也就是說,51 個單詞的序列。 我們可以通過從令牌 51 開始迭代令牌列表并將先前的 50 個令牌作為序列進行迭代,然后將該過程重復到令牌列表的末尾。 我們將令牌轉換為以空格分隔的字符串,以便以后存儲在文件中。 下面列出了將清潔令牌列表拆分為長度為 51 令牌的序列的代碼。 ```py # organize into sequences of tokens length = 50 + 1 sequences = list() for i in range(length, len(tokens)): # select sequence of tokens seq = tokens[i-length:i] # convert into a line line = ' '.join(seq) # store sequences.append(line) print('Total Sequences: %d' % len(sequences)) ``` 運行此片段會創建一長串的行。 在列表上打印統計數據,我們可以看到我們將有 118,633 種訓練模式來適應我們的模型。 ```py Total Sequences: 118633 ``` 接下來,我們可以將序列保存到新文件中以便以后加載。 我們可以定義一個新函數來保存文本行到文件。這個新函數叫做 _save_doc()_,如下所示。它將行和文件名列表作為輸入。這些行以 ASCII 格式寫入,每行一行。 ```py # save tokens to file, one dialog per line def save_doc(lines, filename): data = '\n'.join(lines) file = open(filename, 'w') file.write(data) file.close() ``` 我們可以調用此函數并將訓練序列保存到文件' _republic_sequences.txt_ '。 ```py # save sequences to file out_filename = 'republic_sequences.txt' save_doc(sequences, out_filename) ``` 使用文本編輯器查看文件。 你會看到每一行都沿著一個單詞移動,最后一個新單詞被預測;例如,以下是截斷形式的前 3 行: > 我知道了......看到了 > 我去了......看到我們 > 我從 > 下來...... ### 完整的例子 將所有這些結合在一起,下面提供了完整的代碼清單。 ```py import string # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # turn a doc into clean tokens def clean_doc(doc): # replace '--' with a space ' ' doc = doc.replace('--', ' ') # split into tokens by white space tokens = doc.split() # remove punctuation from each token table = str.maketrans('', '', string.punctuation) tokens = [w.translate(table) for w in tokens] # remove remaining tokens that are not alphabetic tokens = [word for word in tokens if word.isalpha()] # make lower case tokens = [word.lower() for word in tokens] return tokens # save tokens to file, one dialog per line def save_doc(lines, filename): data = '\n'.join(lines) file = open(filename, 'w') file.write(data) file.close() # load document in_filename = 'republic_clean.txt' doc = load_doc(in_filename) print(doc[:200]) # clean document tokens = clean_doc(doc) print(tokens[:200]) print('Total Tokens: %d' % len(tokens)) print('Unique Tokens: %d' % len(set(tokens))) # organize into sequences of tokens length = 50 + 1 sequences = list() for i in range(length, len(tokens)): # select sequence of tokens seq = tokens[i-length:i] # convert into a line line = ' '.join(seq) # store sequences.append(line) print('Total Sequences: %d' % len(sequences)) # save sequences to file out_filename = 'republic_sequences.txt' save_doc(sequences, out_filename) ``` 您現在應該將訓練數據存儲在當前工作目錄中的文件' _republic_sequences.txt_ '中。 接下來,讓我們看看如何使語言模型適合這些數據。 ## 訓練語言模型 我們現在可以從準備好的數據中訓練統計語言模型。 我們將訓練的模型是神經語言模型。它有一些獨特的特點: * 它使用單詞的分布式表示,以便具有相似含義的不同單詞具有相似的表示。 * 它在學習模型的同時學習表示。 * 它學會使用最后 100 個單詞的上下文預測下一個單詞的概率。 具體來說,我們將使用嵌入層來學習單詞的表示,并使用長期短期記憶(LSTM)循環神經網絡來學習根據其上下文預測單詞。 讓我們從加載我們的訓練數據開始。 ### 加載序列 我們可以使用我們在上一節中開發的 _load_doc()_ 函數加載我們的訓練數據。 加載后,我們可以通過基于新行的拆分將數據拆分為單獨的訓練序列。 下面的代碼段將從當前工作目錄加載' _republic_sequences.txt_ '數據文件。 ```py # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # load in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') ``` 接下來,我們可以編碼訓練數據。 ### 編碼序列 單詞嵌入層要求輸入序列由整數組成。 我們可以將詞匯表中的每個單詞映射到一個唯一的整數,并對輸入序列進行編碼。之后,當我們進行預測時,我們可以將預測轉換為數字并在同一映射中查找其關聯的單詞。 要進行此編碼,我們將使用 Keras API 中的 [Tokenizer 類](https://keras.io/preprocessing/text/#tokenizer)。 首先,必須在整個訓練數據集上訓練 Tokenizer,這意味著它會找到數據中的所有唯一單詞并為每個單詞分配一個唯一的整數。 然后我們可以使用 fit Tokenizer 對所有訓練序列進行編碼,將每個序列從單詞列表轉換為整數列表。 ```py # integer encode sequences of words tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) sequences = tokenizer.texts_to_sequences(lines) ``` 我們可以訪問單詞到整數的映射,作為 Tokenizer 對象上名為 word_index 的字典屬性。 我們需要知道稍后定義嵌入層的詞匯表的大小。我們可以通過計算映射字典的大小來確定詞匯表。 為單詞分配從 1 到單詞總數的值(例如 7,409)。嵌入層需要為此詞匯表中的每個單詞分配一個向量表示,從索引 1 到最大索引,并且因為數組的索引是零偏移,所以詞匯結尾的單詞索引將是 7,409;這意味著數組的長度必須為 7,409 + 1。 因此,在為嵌入層指定詞匯表大小時,我們將其指定為比實際詞匯大 1。 ```py # vocabulary size vocab_size = len(tokenizer.word_index) + 1 ``` ### 序列輸入和輸出 現在我們已經編碼了輸入序列,我們需要將它們分成輸入( _X_ )和輸出( _y_ )元素。 我們可以通過數組切片來做到這一點。 分離后,我們需要對輸出字進行熱編碼。這意味著將它從整數轉換為 0 值的向量,一個用于詞匯表中的每個單詞,用 1 表示單詞整數值索引處的特定單詞。 這樣,模型學習預測下一個單詞的概率分布,并且除了接下來的實際單詞之外,所有單詞的學習基礎真實為 0。 Keras 提供 _to_categorical()_,可用于對每個輸入 - 輸出序列對的輸出字進行熱編碼。 最后,我們需要為嵌入層指定輸入序列的長度。我們知道有 50 個單詞,因為我們設計了模型,但指定的一個很好的通用方法是使用輸入數據形狀的第二個維度(列數)。這樣,如果在準備數據時更改序列的長度,則無需更改此數據加載代碼;它是通用的。 ```py # separate into input and output sequences = array(sequences) X, y = sequences[:,:-1], sequences[:,-1] y = to_categorical(y, num_classes=vocab_size) seq_length = X.shape[1] ``` ### 適合模型 我們現在可以在訓練數據上定義和擬合我們的語言模型。 如前所述,學習嵌入需要知道詞匯表的大小和輸入序列的長度。它還有一個參數來指定用于表示每個單詞的維度。也就是說,嵌入向量空間的大小。 常用值為 50,100 和 300.我們在這里使用 50,但考慮測試更小或更大的值。 我們將使用兩個 LSTM 隱藏層,每層有 100 個存儲單元。更多的存儲單元和更深的網絡可以獲得更好的結果。 具有 100 個神經元的密集完全連接層連接到 LSTM 隱藏層以解釋從序列提取的特征。輸出層將下一個單詞預測為單個向量,即詞匯表的大小,其中詞匯表中的每個單詞具有概率。 softmax 激活函數用于確保輸出具有歸一化概率的特征。 ```py # define model model = Sequential() model.add(Embedding(vocab_size, 50, input_length=seq_length)) model.add(LSTM(100, return_sequences=True)) model.add(LSTM(100)) model.add(Dense(100, activation='relu')) model.add(Dense(vocab_size, activation='softmax')) print(model.summary()) ``` 定義網絡的摘要打印為完整性檢查,以確保我們構建了我們的預期。 ```py _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_1 (Embedding) (None, 50, 50) 370500 _________________________________________________________________ lstm_1 (LSTM) (None, 50, 100) 60400 _________________________________________________________________ lstm_2 (LSTM) (None, 100) 80400 _________________________________________________________________ dense_1 (Dense) (None, 100) 10100 _________________________________________________________________ dense_2 (Dense) (None, 7410) 748410 ================================================================= Total params: 1,269,810 Trainable params: 1,269,810 Non-trainable params: 0 _________________________________________________________________ ``` 接下來,編譯模型,指定擬合模型所需的分類交叉熵損失。從技術上講,該模型正在學習多類分類,這是此類問題的合適損失函數。使用有效的 Adam 實現到小批量梯度下降并且評估模型的準確性。 最后,該模型適用于 100 個訓練時期的數據,適當的批量大小為 128,以加快速度。 沒有 GPU 的現代硬件上的訓練可能需要幾個小時。您可以使用更大的批量大小和/或更少的訓練時期加快速度。 ```py # compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # fit model model.fit(X, y, batch_size=128, epochs=100) ``` 在訓練期間,您將看到表現摘要,包括在每次批次更新結束時從訓練數據評估的損失和準確性。 你會得到不同的結果,但是預測序列中下一個單詞的準確度可能只有 50%以上,這也不錯。我們的目標不是 100%準確(例如記憶文本的模型),而是一種捕捉文本本質的模型。 ```py ... Epoch 96/100 118633/118633 [==============================] - 265s - loss: 2.0324 - acc: 0.5187 Epoch 97/100 118633/118633 [==============================] - 265s - loss: 2.0136 - acc: 0.5247 Epoch 98/100 118633/118633 [==============================] - 267s - loss: 1.9956 - acc: 0.5262 Epoch 99/100 118633/118633 [==============================] - 266s - loss: 1.9812 - acc: 0.5291 Epoch 100/100 118633/118633 [==============================] - 270s - loss: 1.9709 - acc: 0.5315 ``` ### 保存模型 在運行結束時,訓練的模型將保存到文件中。 在這里,我們使用 Keras 模型 API 將模型保存到當前工作目錄中的文件' _model.h5_ '。 之后,當我們加載模型進行預測時,我們還需要將單詞映射到整數。這是在 Tokenizer 對象中,我們也可以使用 Pickle 保存它。 ```py # save the model to file model.save('model.h5') # save the tokenizer dump(tokenizer, open('tokenizer.pkl', 'wb')) ``` ### 完整的例子 我們可以把所有這些放在一起;下面列出了擬合語言模型的完整示例。 ```py from numpy import array from pickle import dump from keras.preprocessing.text import Tokenizer from keras.utils import to_categorical from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Embedding # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # load in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') # integer encode sequences of words tokenizer = Tokenizer() tokenizer.fit_on_texts(lines) sequences = tokenizer.texts_to_sequences(lines) # vocabulary size vocab_size = len(tokenizer.word_index) + 1 # separate into input and output sequences = array(sequences) X, y = sequences[:,:-1], sequences[:,-1] y = to_categorical(y, num_classes=vocab_size) seq_length = X.shape[1] # define model model = Sequential() model.add(Embedding(vocab_size, 50, input_length=seq_length)) model.add(LSTM(100, return_sequences=True)) model.add(LSTM(100)) model.add(Dense(100, activation='relu')) model.add(Dense(vocab_size, activation='softmax')) print(model.summary()) # compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) # fit model model.fit(X, y, batch_size=128, epochs=100) # save the model to file model.save('model.h5') # save the tokenizer dump(tokenizer, open('tokenizer.pkl', 'wb')) ``` ## 使用語言模型 既然我們有一個訓練有素的語言模型,我們就可以使用它。 在這種情況下,我們可以使用它來生成與源文本具有相同統計屬性的新文本序列。 這是不切實際的,至少不是這個例子,但它給出了語言模型學到的具體例子。 我們將再次加載訓練序列。 ### 加載數據 我們可以使用上一節中的相同代碼來加載文本的訓練數據序列。 具體來說, _load_doc()_ 功能。 ```py # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # load cleaned text sequences in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') ``` 我們需要文本,以便我們可以選擇源序列作為模型的輸入,以生成新的文本序列。 該模型將需要 100 個單詞作為輸入。 稍后,我們需要指定預期的輸入長度。我們可以通過計算加載數據的一行的長度從輸入序列中確定這一點,并且對于同一行上的預期輸出字減去 1。 ```py seq_length = len(lines[0].split()) - 1 ``` ### 加載模型 我們現在可以從文件加載模型。 Keras 提供 _load_model()_ 功能,用于加載模型,隨時可以使用。 ```py # load the model model = load_model('model.h5') ``` 我們還可以使用 Pickle API 從文件加載 tokenizer。 ```py # load the tokenizer tokenizer = load(open('tokenizer.pkl', 'rb')) ``` 我們準備使用加載的模型。 ### 生成文本 生成文本的第一步是準備種子輸入。 為此,我們將從輸入文本中選擇一行隨機文本。一旦選定,我們將打印它,以便我們對使用的內容有所了解。 ```py # select a seed text seed_text = lines[randint(0,len(lines))] print(seed_text + '\n') ``` 接下來,我們可以一次創建一個新單詞。 首先,必須使用我們在訓練模型時使用的相同標記器將種子文本編碼為整數。 ```py encoded = tokenizer.texts_to_sequences([seed_text])[0] ``` 該模型可以通過調用 _model.predict_classes()_ 直接預測下一個單詞,該模型將返回具有最高概率的單詞的索引。 ```py # predict probabilities for each word yhat = model.predict_classes(encoded, verbose=0) ``` 然后,我們可以在 Tokenizers 映射中查找索引以獲取關聯的單詞。 ```py out_word = '' for word, index in tokenizer.word_index.items(): if index == yhat: out_word = word break ``` 然后,我們可以將此單詞附加到種子文本并重復該過程。 重要的是,輸入序列將變得太長。在輸入序列編碼為整數后,我們可以將其截斷為所需的長度。 Keras 提供了 _pad_sequences()_ 函數,我們可以使用它來執行此截斷。 ```py encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre') ``` 我們可以將所有這些包裝成一個名為 _generate_seq()_ 的函數,該函數將模型,標記生成器,輸入序列長度,種子文本和要生成的單詞數作為輸入。然后它返回由模型生成的一系列單詞。 ```py # generate a sequence from a language model def generate_seq(model, tokenizer, seq_length, seed_text, n_words): result = list() in_text = seed_text # generate a fixed number of words for _ in range(n_words): # encode the text as integer encoded = tokenizer.texts_to_sequences([in_text])[0] # truncate sequences to a fixed length encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre') # predict probabilities for each word yhat = model.predict_classes(encoded, verbose=0) # map predicted word index to word out_word = '' for word, index in tokenizer.word_index.items(): if index == yhat: out_word = word break # append to input in_text += ' ' + out_word result.append(out_word) return ' '.join(result) ``` 我們現在準備在給出一些種子文本的情況下生成一系列新單詞。 ```py # generate new text generated = generate_seq(model, tokenizer, seq_length, seed_text, 50) print(generated) ``` 綜上所述,下面列出了從學習語言模型生成文本的完整代碼清單。 ```py from random import randint from pickle import load from keras.models import load_model from keras.preprocessing.sequence import pad_sequences # load doc into memory def load_doc(filename): # open the file as read only file = open(filename, 'r') # read all text text = file.read() # close the file file.close() return text # generate a sequence from a language model def generate_seq(model, tokenizer, seq_length, seed_text, n_words): result = list() in_text = seed_text # generate a fixed number of words for _ in range(n_words): # encode the text as integer encoded = tokenizer.texts_to_sequences([in_text])[0] # truncate sequences to a fixed length encoded = pad_sequences([encoded], maxlen=seq_length, truncating='pre') # predict probabilities for each word yhat = model.predict_classes(encoded, verbose=0) # map predicted word index to word out_word = '' for word, index in tokenizer.word_index.items(): if index == yhat: out_word = word break # append to input in_text += ' ' + out_word result.append(out_word) return ' '.join(result) # load cleaned text sequences in_filename = 'republic_sequences.txt' doc = load_doc(in_filename) lines = doc.split('\n') seq_length = len(lines[0].split()) - 1 # load the model model = load_model('model.h5') # load the tokenizer tokenizer = load(open('tokenizer.pkl', 'rb')) # select a seed text seed_text = lines[randint(0,len(lines))] print(seed_text + '\n') # generate new text generated = generate_seq(model, tokenizer, seq_length, seed_text, 50) print(generated) ``` 首先運行示例打印種子文本。 > 當他說一個人長大后可以學到很多東西,因為他不能學到更多東西,因為他可以跑得很多青春是時候任何特殊的辛勞,因此計算和幾何以及所有其他教學要素都是一個 然后打印 50 個生成的文本。 > 辯證法的準備應該以怠惰揮霍者的名義呈現,其他人是多方面的,不公正的,是最好的,另一個是高興的靈魂靈魂的開放,繡花者必須在 你會得到不同的結果。嘗試運行幾代產品。 你可以看到文字看似合理。實際上,添加連接將有助于解釋種子和生成的文本。然而,生成的文本以正確的順序獲得正確的單詞。 嘗試運行幾次示例以查看生成文本的其他示例。如果你看到有趣的話,請在下面的評論中告訴我。 ## 擴展 本節列出了一些擴展您可能希望探索的教程的想法。 * **Sentence-Wise Model** 。基于句子分割原始數據并將每個句子填充到固定長度(例如,最長的句子長度)。 * **簡化詞匯**。探索一個更簡單的詞匯,可能會刪除詞干或停止詞。 * **調諧模型**。調整模型,例如隱藏層中嵌入的大小或存儲單元的數量,以查看是否可以開發更好的模型。 * **更深的型號**。擴展模型以具有多個 LSTM 隱藏層,可能具有丟失以查看是否可以開發更好的模型。 * **預訓練單詞嵌入**。擴展模型以使用預先訓練的 word2vec 或 GloVe 向量來查看它是否會產生更好的模型。 ## 進一步閱讀 如果您要深入了解,本節將提供有關該主題的更多資源。 * [Gutenberg 項目](https://www.gutenberg.org/) * [柏拉圖共和國古騰堡項目](https://www.gutenberg.org/ebooks/1497) * 維基百科上的[共和國(柏拉圖)](https://en.wikipedia.org/wiki/Republic_(Plato)) * 維基百科上的[語言模型](https://en.wikipedia.org/wiki/Language_model) ## 摘要 在本教程中,您了解了如何使用單詞嵌入和循環神經網絡開發基于單詞的語言模型。 具體來說,你學到了: * 如何準備文本以開發基于單詞的語言模型。 * 如何設計和擬合具有學習嵌入和 LSTM 隱藏層的神經語言模型。 * 如何使用學習的語言模型生成具有與源文本類似的統計屬性的新文本。 你有任何問題嗎? 在下面的評論中提出您的問題,我會盡力回答。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看