《python深度學習》筆記---6.1-2、word embedding-利用 Embedding 層學習詞嵌入
一、總結
一句話總結:
【考慮到僅查看每條評論的前 20 個單詞】:得到的驗證精度約為 76%,考慮到僅查看每條評論的前 20 個單詞,這個結果還是相當不錯 的。
【沒有考慮單詞之間的關系和句子結構】:但請注意,僅僅將嵌入序列展開並在上面訓練一個 Dense 層,會導致模型對輸入序列中的 每個單詞單獨處理,而沒有考慮單詞之間的關系和句子結構(舉個例子,這個模型可能會將 this movie is a bomb和this movie is the bomb兩條都歸為負面評論)。
【添加循環層或一維卷積層】:更好的做法是在嵌入序列上添 加循環層或一維卷積層,將每個序列作為整體來學習特征。
model.add(Embedding(10000, 8, input_length=maxlen))
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense model = Sequential() # We specify the maximum input length to our Embedding layer # so we can later flatten the embedded inputs # 指定 Embedding 層的最大輸入長度,以 便后面將嵌入輸入展平。 # Embedding 層 激活的形狀為 (samples, maxlen, 8) model.add(Embedding(10000, 8, input_length=maxlen)) # After the Embedding layer, # our activations have shape `(samples, maxlen, 8)`. # We flatten the 3D tensor of embeddings # into a 2D tensor of shape `(samples, maxlen * 8)` model.add(Flatten()) # We add the classifier on top model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) model.summary() history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
1、Embedding 層理解?
【字典:Embedding層實際上是一種字典查找】:最好將 Embedding 層理解為一個字典,將整數索引(表示特定單詞)映射為密集向量。它 接收整數作為輸入,並在內部字典中查找這些整數,然后返回相關聯的向量。Embedding 層實 際上是一種字典查找
【單詞索引-->Embedding層-->對應的詞向量】
2、Embedding 層的輸入?
【二維整數張量:(samples, sequence_length)】:Embedding 層的輸入是一個二維整數張量,其形狀為 (samples, sequence_length), 每個元素是一個整數序列。
【(32, 10)(32 個長度為10 的序列組成的批量)】:它能夠嵌入長度可變的序列,例如,對於前一個例子中的 Embedding 層,你可以輸入形狀為 (32, 10)(32 個長度為10 的序列組成的批量)或 (64, 15)(64 個長度為15 的序列組成的批量)的批量。
【不夠0填充,較長被截斷】:不過一批數據中的所有序列必須具有相同的 長度(因為需要將它們打包成一個張量),所以較短的序列應該用 0 填充,較長的序列應該被截斷。
3、Embedding 層 輸出?
【也就是在原來的基礎上擴充了embedding_dimensionality維】:【(samples, sequence_length, embedding_dimensionality)的三維浮點數張量】:這個Embedding 層返回一個形狀為(samples, sequence_length, embedding_ dimensionality) 的三維浮點數張量。然后可以用 RNN 層或一維卷積層來處理這個三維張量
4、IMDB 電影評論情感預測任務 word Embedding 層 實例?
【限制為前10 000 個最常見的單詞】:首先,我們需要快速准備 數據。將電影評論限制為前10 000 個最常見的單詞(第一次處理這個數據集時就是這么做的), 然后將評論長度限制為只有20 個單詞。
【將輸入的整數序列(二維整數張量)轉換為嵌入序列(三維浮點數張量),然后將這個張量展平為二維】:對於這10 000 個單詞,網絡將對每個詞都學習一個8 維嵌入,將輸入的整數序列(二維整數張量)轉換為嵌入序列(三維浮點數張量),然后將這個 張量展平為二維,最后在上面訓練一個 Dense 層用於分類。
二、word embedding-利用 Embedding 層學習詞嵌入
博客對應課程的視頻位置:
1、將一個 Embedding 層實例化
In [1]:
from tensorflow.keras.layers import Embedding # The Embedding layer takes at least two arguments: # the number of possible tokens, here 1000 (1 + maximum word index), # and the dimensionality of the embeddings, here 64. embedding_layer = Embedding(1000, 64)
In [2]:
print(embedding_layer)
In [3]:
print(dir(embedding_layer))
2、加載 IMDB 數據,准備用於 Embedding 層
In [4]:
from tensorflow.keras.datasets import imdb from tensorflow.keras import preprocessing # Number of words to consider as features max_features = 10000 # Cut texts after this number of words # (among top max_features most common words) maxlen = 20 # 將數據加載為整數列表 # Load the data as lists of integers. (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features) print(x_train.shape) print(x_test.shape) print(x_train[0]) print(x_train[1]) print(x_train)
為什么輸入是25000,因為這里是25000個list,numpy肯定統計不了list的形狀
從結果看好像是截斷操作
In [5]:
# 將整數列表轉換成形狀為(samples,maxlen)的二維整數張量
# This turns our lists of integers # into a 2D integer tensor of shape `(samples, maxlen)` x_train = preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen) x_test = preprocessing.sequence.pad_sequences(x_test, maxlen=maxlen) print(x_train.shape) print(x_test.shape) print(x_train[0]) print(x_train[1]) print(x_train)
從結果看好像是截斷操作
3、在 IMDB 數據上使用 Embedding 層和分類器
In [6]:
from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Flatten, Dense model = Sequential() # We specify the maximum input length to our Embedding layer # so we can later flatten the embedded inputs # 指定 Embedding 層的最大輸入長度,以 便后面將嵌入輸入展平。 # Embedding 層 激活的形狀為 (samples, maxlen, 8) model.add(Embedding(10000, 8, input_length=maxlen)) # After the Embedding layer, # our activations have shape `(samples, maxlen, 8)`. # We flatten the 3D tensor of embeddings # into a 2D tensor of shape `(samples, maxlen * 8)` model.add(Flatten()) # We add the classifier on top model.add(Dense(1, activation='sigmoid')) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['acc']) model.summary() history = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_split=0.2)
得到的驗證精度約為 76%,考慮到僅查看每條評論的前 20 個單詞,這個結果還是相當不錯 的。但請注意,僅僅將嵌入序列展開並在上面訓練一個 Dense 層,會導致模型對輸入序列中的 每個單詞單獨處理,而沒有考慮單詞之間的關系和句子結構(舉個例子,這個模型可能會將 this movie is a bomb和this movie is the bomb兩條都歸為負面評論 a)。更好的做法是在嵌入序列上添 加循環層或一維卷積層,將每個序列作為整體來學習特征。
In [ ]: