埋め込みレイヤーは、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 は embedded_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で述べたように、これらのベクトルはランダムに開始され、ネットワークの他のパラメーターと同様にネットワーク オプティマイザーによって最適化されます。