Hina-Blog

TensorflowのEmbeddingレイヤーってなに

October 01, 2020

なにをしているのか

簡単に

文字列を入力として、それぞれの単語をベクトル表現にした文章を返します。

詳しく

例文を以下のものとする
It is good to embed
It is nice to embed
このとき good と nice は近い働きをします。
これを数値に置き換えると
It is good to embed => [0,1,2,3,4]
It is nice to embed => [0,1,5,3,4]
登場した順番に置き換えていくと、上のようになります。

これを Embedding に入れるとベクトルに変換してくれます。

input_array = np.array([[0,1,2,3,4],[0,1,5,3,4]])
vocab_size=6

model=tf.keras.Sequential()
model.add(L.Embedding(vocab_size,2))
#model.add(L.GlobalAveragePooling1D())
model.compile(optimizer="Adam", loss="mse")

output_array=model.predict(input_array)
output_array

#出力は以下の通り
# array([[[ 0.04210998, -0.01260852],
#         [ 0.01690816,  0.00061071],
#         [ 0.02739259, -0.04781172],
#         [ 0.01341558,  0.03447438],
#         [-0.0405872 ,  0.04194418]],

#        [[ 0.04210998, -0.01260852],
#         [ 0.01690816,  0.00061071],
#         [-0.04146413, -0.03388226],
#         [ 0.01341558,  0.03447438],
#         [-0.0405872 ,  0.04194418]]], dtype=float32)

参考

TensorFlow ハブによるテキスト分類:映画レビュー
単語埋め込み (Word embeddings)