<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、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 如何使用 Keras 將詞嵌入層用于深度學習 > 原文: [https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/](https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/) 詞嵌入提供了單詞及其相對含義的密集表示。 它們是對簡單包含的單詞模型表示中使用的稀疏表示的改進。 可以從文本數據中學習詞嵌入,并在項目中重用。它們也可以作為在文本數據上擬合神經網絡的一部分來學習。 在本教程中,您將了解如何使用詞嵌入在 Python 中使用 Keras 進行深度學習。 完成本教程后,您將了解: * 關于字嵌入和 Keras 通過嵌入層支持字嵌入。 * 如何在擬合神經網絡時學習單詞嵌入。 * 如何在神經網絡中使用預先訓練的單詞嵌入。 讓我們開始吧。 * **2018 年 2 月更新**:修復了由于底層 API 發生變化而導致的錯誤。 ![How to Use Word Embedding Layers for Deep Learning with Keras](img/2218ca2cd0b8ce367f990aafb1cebca5.jpg) 如何使用 Keras 使用詞嵌入層深度學習照片由 [thisguy](https://www.flickr.com/photos/davebloggs007/36375879215/) 拍攝,保留一些權利。 ## 教程概述 本教程分為 3 個部分;他們是: 1. 單詞嵌入 2. Keras 嵌入層 3. 學習嵌入的示例 4. 使用預訓練 GloVe 嵌入的示例 ## 1.單詞嵌入 單詞嵌入是使用密集向量表示來表示單詞和文檔的一類方法。 它是對傳統的詞袋模型編碼方案的改進,其中使用大的稀疏向量來表示每個單詞或者對向量中的每個單詞進行評分以表示整個詞匯表。這些表示是稀疏的,因為詞匯量很大,并且給定的單詞或文檔將由主要由零值組成的大向量表示。 相反,在嵌入中,單詞由密集向量表示,其中向量表示單詞到連續向量空間的投影。 向量空間中的單詞的位置是從文本中學習的,并且基于在使用單詞時圍繞單詞的單詞。 學習向量空間中的單詞的位置被稱為其嵌入。 從文本中學習單詞嵌入的兩種流行方法示例包括: * Word2Vec。 * 手套。 除了這些精心設計的方法之外,還可以學習單詞嵌入作為深度學習模型的一部分。這可能是一種較慢的方法,但可以將模型定制為特定的訓練數據集。 ## 2\. Keras 嵌入層 Keras 提供[嵌入](https://keras.io/layers/embeddings/#embedding)層,可用于文本數據上的神經網絡。 它要求輸入數據是整數編碼的,以便每個單詞由唯一的整數表示。該數據準備步驟可以使用 Keras 提供的 [Tokenizer API](https://keras.io/preprocessing/text/#tokenizer) 來執行。 使用隨機權重初始化嵌入層,并將學習訓練數據集中所有單詞的嵌入。 它是一個靈活的層,可以以多種方式使用,例如: * 它可以單獨用于學習可以保存并在以后用于其他模型的單詞嵌入。 * 它可以用作深度學習模型的一部分,其中嵌入與模型本身一起被學習。 * 它可以用于加載預訓練的單詞嵌入模型,一種轉移學習。 嵌入層被定義為網絡的第一個隱藏層。它必須指定 3 個參數: 它必須指定 3 個參數: * **input_dim** :這是文本數據中詞匯表的大小。例如,如果您的數據整數編碼為 0-10 之間的值,那么詞匯表的大小將為 11 個單詞。 * **output_dim** :這是將嵌入單詞的向量空間的大小。它為每個單詞定義了該層的輸出向量的大小。例如,它可以是 32 或 100 甚至更大。測試問題的不同值。 * **input_length** :這是輸入序列的長度,正如您為 Keras 模型的任何輸入層定義的那樣。例如,如果所有輸入文檔都包含 1000 個單詞,則為 1000。 例如,下面我們定義具有 200 的詞匯表的嵌入層(例如,從 0 到 199 的整數編碼的單詞),其中將嵌入單詞的 32 維的向量空間,以及每個具有 50 個單詞的輸入文檔。 ```py e = Embedding(200, 32, input_length=50) ``` 嵌入層具有學習的權重。如果將模型保存到文件,則將包括嵌入層的權重。 _ 嵌入 _ 層的輸出是 2D 向量,在輸入的單詞序列(輸入文檔)中為每個單詞嵌入一個。 如果您希望將 _Dense_ 層直接連接到嵌入層,則必須先使用 _Flatten_ 層將 2D 輸出矩陣展平為 1D 向量。 現在,讓我們看看我們如何在實踐中使用嵌入層。 ## 3.學習嵌入的示例 在本節中,我們將看看如何在將神經網絡擬合到文本分類問題時學習單詞嵌入。 我們將定義一個小問題,其中我們有 10 個文本文檔,每個文檔都有一個學生提交的工作評論。每個文本文檔被分類為正“1”或負“0”。這是一個簡單的情感分析問題。 首先,我們將定義文檔及其類標簽。 ```py # define documents docs = ['Well done!', 'Good work', 'Great effort', 'nice work', 'Excellent!', 'Weak', 'Poor effort!', 'not good', 'poor work', 'Could have done better.'] # define class labels labels = array([1,1,1,1,1,0,0,0,0,0]) ``` 接下來,我們可以整數編碼每個文檔。這意味著作為輸入,嵌入層將具有整數序列。我們可以嘗試其他更復雜的單詞模型編碼,如計數或 TF-IDF。 Keras 提供 [one_hot()函數](https://keras.io/preprocessing/text/#one_hot),它將每個單詞的散列創建為有效的整數編碼。我們將估計 50 的詞匯量,這比減少哈希函數碰撞的概率要大得多。 ```py # integer encode the documents vocab_size = 50 encoded_docs = [one_hot(d, vocab_size) for d in docs] print(encoded_docs) ``` 序列具有不同的長度,Keras 更喜歡輸入以進行向量化,并且所有輸入具有相同的長度。我們將填充所有輸入序列的長度為 4.再次,我們可以使用內置的 Keras 函數,在這種情況下 [pad_sequences()函數](https://keras.io/preprocessing/sequence/#pad_sequences)。 ```py # pad documents to a max length of 4 words max_length = 4 padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post') print(padded_docs) ``` 我們現在準備將我們的 _ 嵌入 _ 層定義為我們的神經網絡模型的一部分。 _ 嵌入 _ 的詞匯量為 50,輸入長度為 4.我們將選擇 8 維的小嵌入空間。 該模型是一個簡單的二元分類模型。重要的是,_ 嵌入 _ 層的輸出將是 4 個向量,每個維度為 8 維,每個單詞一個。我們將其展平為一個 32 元素向量,以傳遞給 _Dense_ 輸出層。 ```py # define the model model = Sequential() model.add(Embedding(vocab_size, 8, input_length=max_length)) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) # compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) # summarize the model print(model.summary()) ``` 最后,我們可以擬合和評估分類模型。 ```py # fit the model model.fit(padded_docs, labels, epochs=50, verbose=0) # evaluate the model loss, accuracy = model.evaluate(padded_docs, labels, verbose=0) print('Accuracy: %f' % (accuracy*100)) ``` 完整的代碼清單如下。 ```py from numpy import array from keras.preprocessing.text import one_hot from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Dense from keras.layers import Flatten from keras.layers.embeddings import Embedding # define documents docs = ['Well done!', 'Good work', 'Great effort', 'nice work', 'Excellent!', 'Weak', 'Poor effort!', 'not good', 'poor work', 'Could have done better.'] # define class labels labels = array([1,1,1,1,1,0,0,0,0,0]) # integer encode the documents vocab_size = 50 encoded_docs = [one_hot(d, vocab_size) for d in docs] print(encoded_docs) # pad documents to a max length of 4 words max_length = 4 padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post') print(padded_docs) # define the model model = Sequential() model.add(Embedding(vocab_size, 8, input_length=max_length)) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) # compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) # summarize the model print(model.summary()) # fit the model model.fit(padded_docs, labels, epochs=50, verbose=0) # evaluate the model loss, accuracy = model.evaluate(padded_docs, labels, verbose=0) print('Accuracy: %f' % (accuracy*100)) ``` 首先運行該示例打印整數編碼的文檔。 ```py [[6, 16], [42, 24], [2, 17], [42, 24], [18], [17], [22, 17], [27, 42], [22, 24], [49, 46, 16, 34]] ``` 然后打印每個文檔的填充版本,使它們均勻長度。 ```py [[ 6 16 0 0] [42 24 0 0] [ 2 17 0 0] [42 24 0 0] [18 0 0 0] [17 0 0 0] [22 17 0 0] [27 42 0 0] [22 24 0 0] [49 46 16 34]] ``` 定義網絡后,將打印層的摘要。我們可以看到,正如預期的那樣,嵌入層的輸出是一個 4×8 矩陣,并且由 Flatten 層壓縮為 32 個元素的向量。 ```py _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_1 (Embedding) (None, 4, 8) 400 _________________________________________________________________ flatten_1 (Flatten) (None, 32) 0 _________________________________________________________________ dense_1 (Dense) (None, 1) 33 ================================================================= Total params: 433 Trainable params: 433 Non-trainable params: 0 _________________________________________________________________ ``` 最后,打印訓練模型的準確性,表明它完美地學習了訓練數據集(這并不奇怪)。 ```py Accuracy: 100.000000 ``` 您可以將已學習的權重從嵌入層保存到文件中,以便以后在其他模型中使用。 您通常也可以使用此模型對在測試數據集中看到的具有相同類型詞匯的其他文檔進行分類。 接下來,讓我們看看在 Keras 中加載預先訓練好的單詞嵌入。 ## 4.使用預訓練 GloVe 嵌入的示例 Keras 嵌入層還可以使用在其他地方學習的單詞嵌入。 在自然語言處理領域中常見的是學習,保存和免費提供單詞嵌入。 例如,GloVe 方法背后的研究人員在其公共領域許可下發布的網站上提供了一套預先訓練過的單詞嵌入。看到: * [GloVe:用于詞表示的全局向量](https://nlp.stanford.edu/projects/glove/) 最小的嵌入包是 822Mb,稱為“_ 手套.6B.zip_ ”。它是在 10 億個令牌(單詞)的數據集上訓練的,詞匯量為 40 萬字。有一些不同的嵌入向量大小,包括 50,100,200 和 300 維度。 您可以下載這個嵌入集合,我們可以使用訓練數據集中單詞的訓練前嵌入的權重對 Keras _ 嵌入 _ 層進行播種。 這個例子的靈感來自 Keras 項目中的一個例子: [pretrained_word_embeddings.py](https://github.com/fchollet/keras/blob/master/examples/pretrained_word_embeddings.py) 。 下載并解壓縮后,您將看到一些文件,其中一個是“ _glove.6B.100d.txt_ ”,其中包含 100 維版本的嵌入。 如果您查看文件內部,您將看到一個標記(單詞),后面跟著每行的權重(100 個數字)。例如,下面是嵌入 ASCII 文本文件的第一行,顯示“”的嵌入。 ```py the -0.038194 -0.24487 0.72812 -0.39961 0.083172 0.043953 -0.39141 0.3344 -0.57545 0.087459 0.28787 -0.06731 0.30906 -0.26384 -0.13231 -0.20757 0.33395 -0.33848 -0.31743 -0.48336 0.1464 -0.37304 0.34577 0.052041 0.44946 -0.46971 0.02628 -0.54155 -0.15518 -0.14107 -0.039722 0.28277 0.14393 0.23464 -0.31021 0.086173 0.20397 0.52624 0.17164 -0.082378 -0.71787 -0.41531 0.20335 -0.12763 0.41367 0.55187 0.57908 -0.33477 -0.36559 -0.54857 -0.062892 0.26584 0.30205 0.99775 -0.80481 -3.0243 0.01254 -0.36942 2.2167 0.72201 -0.24978 0.92136 0.034514 0.46745 1.1079 -0.19358 -0.074575 0.23353 -0.052062 -0.22044 0.057162 -0.15806 -0.30798 -0.41625 0.37972 0.15006 -0.53212 -0.2055 -1.2526 0.071624 0.70565 0.49744 -0.42063 0.26148 -1.538 -0.30223 -0.073438 -0.28312 0.37104 -0.25217 0.016215 -0.017099 -0.38984 0.87424 -0.72569 -0.51058 -0.52028 -0.1459 0.8278 0.27062 ``` 與前一節一樣,第一步是定義示例,將它們編碼為整數,然后將序列填充為相同的長度。 在這種情況下,我們需要能夠將單詞映射到整數以及將整數映射到單詞。 Keras 提供了一個 [Tokenizer](https://keras.io/preprocessing/text/#tokenizer) 類,它可以適應訓練數據,可以通過調用 _Tokenizer_ 類上的 _texts_to_sequences()_ 方法將文本轉換為序列,并提供對 _word_index_ 屬性中單詞到整數的字典映射的訪問。 ```py # define documents docs = ['Well done!', 'Good work', 'Great effort', 'nice work', 'Excellent!', 'Weak', 'Poor effort!', 'not good', 'poor work', 'Could have done better.'] # define class labels labels = array([1,1,1,1,1,0,0,0,0,0]) # prepare tokenizer t = Tokenizer() t.fit_on_texts(docs) vocab_size = len(t.word_index) + 1 # integer encode the documents encoded_docs = t.texts_to_sequences(docs) print(encoded_docs) # pad documents to a max length of 4 words max_length = 4 padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post') print(padded_docs) ``` 接下來,我們需要將整個 GloVe 字嵌入文件作為嵌入數組的字典加載到內存中。 ```py # load the whole embedding into memory embeddings_index = dict() f = open('glove.6B.100d.txt') for line in f: values = line.split() word = values[0] coefs = asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Loaded %s word vectors.' % len(embeddings_index)) ``` 這很慢。最好過濾訓練數據中唯一單詞的嵌入。 接下來,我們需要為訓練數據集中的每個單詞創建一個嵌入矩陣。我們可以通過枚舉 _Tokenizer.word_index_ 中的所有唯一單詞并從加載的 GloVe 嵌入中定位嵌入權重向量來實現。 結果是僅在我們將在訓練期間看到的單詞的權重矩陣。 ```py # create a weight matrix for words in training docs embedding_matrix = zeros((vocab_size, 100)) for word, i in t.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector ``` 現在我們可以像以前一樣定義我們的模型,擬合并評估它。 關鍵的區別在于嵌入層可以使用 GloVe 字嵌入權重進行播種。我們選擇了 100 維版本,因此必須在 _output_dim_ 設置為 100 的情況下定義嵌入層。最后,我們不想更新此模型中的學習單詞權重,因此我們將設置 _]模型的可訓練 _ 屬性為 _False_ 。 ```py e = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=4, trainable=False) ``` 下面列出了完整的工作示例。 ```py from numpy import array from numpy import asarray from numpy import zeros from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from keras.models import Sequential from keras.layers import Dense from keras.layers import Flatten from keras.layers import Embedding # define documents docs = ['Well done!', 'Good work', 'Great effort', 'nice work', 'Excellent!', 'Weak', 'Poor effort!', 'not good', 'poor work', 'Could have done better.'] # define class labels labels = array([1,1,1,1,1,0,0,0,0,0]) # prepare tokenizer t = Tokenizer() t.fit_on_texts(docs) vocab_size = len(t.word_index) + 1 # integer encode the documents encoded_docs = t.texts_to_sequences(docs) print(encoded_docs) # pad documents to a max length of 4 words max_length = 4 padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post') print(padded_docs) # load the whole embedding into memory embeddings_index = dict() f = open('../glove_data/glove.6B/glove.6B.100d.txt') for line in f: values = line.split() word = values[0] coefs = asarray(values[1:], dtype='float32') embeddings_index[word] = coefs f.close() print('Loaded %s word vectors.' % len(embeddings_index)) # create a weight matrix for words in training docs embedding_matrix = zeros((vocab_size, 100)) for word, i in t.word_index.items(): embedding_vector = embeddings_index.get(word) if embedding_vector is not None: embedding_matrix[i] = embedding_vector # define model model = Sequential() e = Embedding(vocab_size, 100, weights=[embedding_matrix], input_length=4, trainable=False) model.add(e) model.add(Flatten()) model.add(Dense(1, activation='sigmoid')) # compile the model model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['acc']) # summarize the model print(model.summary()) # fit the model model.fit(padded_docs, labels, epochs=50, verbose=0) # evaluate the model loss, accuracy = model.evaluate(padded_docs, labels, verbose=0) print('Accuracy: %f' % (accuracy*100)) ``` 運行示例可能需要更長的時間,但后來證明它能夠適應這個簡單的問題。 ```py [[6, 2], [3, 1], [7, 4], [8, 1], [9], [10], [5, 4], [11, 3], [5, 1], [12, 13, 2, 14]] [[ 6 2 0 0] [ 3 1 0 0] [ 7 4 0 0] [ 8 1 0 0] [ 9 0 0 0] [10 0 0 0] [ 5 4 0 0] [11 3 0 0] [ 5 1 0 0] [12 13 2 14]] Loaded 400000 word vectors. _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= embedding_1 (Embedding) (None, 4, 100) 1500 _________________________________________________________________ flatten_1 (Flatten) (None, 400) 0 _________________________________________________________________ dense_1 (Dense) (None, 1) 401 ================================================================= Total params: 1,901 Trainable params: 401 Non-trainable params: 1,500 _________________________________________________________________ Accuracy: 100.000000 ``` 在實踐中,我鼓勵您嘗試使用經過預先訓練的嵌入來學習單詞嵌入,該嵌入是固定的并且嘗試在預訓練嵌入之上進行學習。 了解哪種方法最適合您的具體問題。 ## 進一步閱讀 如果您要深入了解,本節將提供有關該主題的更多資源。 * [詞嵌入維基百科](https://en.wikipedia.org/wiki/Word_embedding) * [Keras 嵌入層 API](https://keras.io/layers/embeddings/#embedding) * [在 Keras 模型中使用預訓練的字嵌入](https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html),2016 * [在 Keras](https://github.com/fchollet/keras/blob/master/examples/pretrained_word_embeddings.py) 中使用預先訓練的 GloVe 嵌入的示例 * [GloVe 嵌入](https://nlp.stanford.edu/projects/glove/) * [詞匯嵌入概述及其與分布式語義模型的聯系](http://blog.aylien.com/overview-word-embeddings-history-word2vec-cbow-glove/),2016 * [Deep Learning,NLP 和 Representations](http://colah.github.io/posts/2014-07-NLP-RNNs-Representations/) ,2014 ## 摘要 在本教程中,您了解了如何使用詞嵌入在 Python 中使用 Keras 進行深度學習。 具體來說,你學到了: * 關于字嵌入和 Keras 通過嵌入層支持字嵌入。 * 如何在擬合神經網絡時學習單詞嵌入。 * 如何在神經網絡中使用預先訓練的單詞嵌入。 你有任何問題嗎? 在下面的評論中提出您的問題,我會盡力回答。
                  <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>

                              哎呀哎呀视频在线观看