用例子说明:如何在keras中嵌入图层

问题描述 投票:14回答:1

我不明白Keras的嵌入层。虽然有很多文章在解释它,但我仍然感到困惑。例如,下面的代码来自imdb情感分析:

top_words = 5000
max_review_length = 500
embedding_vecor_length = 32    

model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length))
model.add(LSTM(100))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
model.fit(X_train, y_train, nb_epoch=3, batch_size=64)

在这段代码中,嵌入层到底在做什么?嵌入层的输出是什么?如果有人可以用一些例子解释它,那将是很好的!

machine-learning neural-network keras word-embedding
1个回答
9
投票

嵌入层从输入词中创建嵌入向量(我自己仍然不理解数学),类似于word2vec或预先计算的手套。

在我开始编写代码之前,让我们举一个简短的例子。

texts = ['This is a text','This is not a text']

首先,我们将这些句子转换为整数向量,其中每个单词是分配给字典中单词的数字,向量的顺序创建单词的序列。

from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences 
from keras.utils import to_categorical

max_review_length = 6 #maximum length of the sentence
embedding_vecor_length = 3
top_words = 10

#num_words is tne number of unique words in the sequence, if there's more top count words are taken
tokenizer = Tokenizer(top_words)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
word_index = tokenizer.word_index
input_dim = len(word_index) + 1
print('Found %s unique tokens.' % len(word_index))

#max_review_length is the maximum length of the input text so that we can create vector [... 0,0,1,3,50] where 1,3,50 are individual words
data = pad_sequences(sequences, max_review_length)

print('Shape of data tensor:', data.shape)
print(data)

[Out:] 
'This is a text' --> [0 0 1 2 3 4]
'This is not a text' --> [0 1 2 5 3 4]

现在您可以将这些输入到嵌入层中

from keras.models import Sequential
from keras.layers import Embedding

model = Sequential()
model.add(Embedding(top_words, embedding_vecor_length, input_length=max_review_length,mask_zero=True))
model.compile(optimizer='adam', loss='categorical_crossentropy')
output_array = model.predict(data)

output_array包含大小(2,6,3)的数组:在我的情况下为2输入评论或句子,6是每个评论中的最大字数(max_review_length),3是embedding_vecor_length。例如。

array([[[-0.01494285, -0.007915  ,  0.01764857],
    [-0.01494285, -0.007915  ,  0.01764857],
    [-0.03019481, -0.02910612,  0.03518577],
    [-0.0046863 ,  0.04763055, -0.02629668],
    [ 0.02297204,  0.02146662,  0.03114786],
    [ 0.01634104,  0.02296363, -0.02348827]],

   [[-0.01494285, -0.007915  ,  0.01764857],
    [-0.03019481, -0.02910612,  0.03518577],
    [-0.0046863 ,  0.04763055, -0.02629668],
    [-0.01736645, -0.03719328,  0.02757809],
    [ 0.02297204,  0.02146662,  0.03114786],
    [ 0.01634104,  0.02296363, -0.02348827]]], dtype=float32)

在你的情况下,你有一个5000个单词的列表,可以创建最多500个单词的评论(更多将被修剪)并将这500个单词中的每一个转换为大小为32的向量。

您可以通过运行以下命令在单词索引和嵌入向量之间进行映射:

model.layers[0].get_weights()

在下面的情况下,top_words是10,所以我们有10个单词的映射,你可以看到0,1,2,3,4和5的映射等于上面的output_array。

[array([[-0.01494285, -0.007915  ,  0.01764857],
    [-0.03019481, -0.02910612,  0.03518577],
    [-0.0046863 ,  0.04763055, -0.02629668],
    [ 0.02297204,  0.02146662,  0.03114786],
    [ 0.01634104,  0.02296363, -0.02348827],
    [-0.01736645, -0.03719328,  0.02757809],
    [ 0.0100757 , -0.03956784,  0.03794377],
    [-0.02672029, -0.00879055, -0.039394  ],
    [-0.00949502, -0.02805768, -0.04179233],
    [ 0.0180716 ,  0.03622523,  0.02232374]], dtype=float32)]

正如在https://stats.stackexchange.com/questions/270546/how-does-keras-embedding-layer-work中所提到的,这些向量是随机启动的,并且由网络优化器优化,就像网络的任何其他参数一样。

© www.soinside.com 2019 - 2024. All rights reserved.