KerasでEmbedding
Embedding
Keras Documentationの説明
正の整数(インデックス)を固定次元の密ベクトルに変換します.
Embeddingレイヤー - Keras Documentation
使い方
model.add(Embedding(1000, 64, input_length=10))
引数:
- input_dim: 正の整数.語彙数.入力データの最大インデックス + 1.
- output_dim: 0以上の整数.密なembeddingsの次元数.
- input_length: 入力の系列長(定数).
自然言語処理での使い方としては、
Embedding(語彙数, 分散ベクトルの次元数, 文書の次元数))
※事前に入力文書の次元数をそろえる必要がある。
動きの確認
import numpy as np from keras.models import Sequential from keras.layers import Embedding model = Sequential() model.add(Embedding(20, 10, input_length=5)) input_array = np.random.randint(20, size=(10, 5)) model.compile('rmsprop', 'mse') output_array = model.predict(input_array) print input_array[0:2] [[16 12 18 17 16] [ 8 14 6 15 19]] print output_array[0:2] [[[ 0.028 0.021 0.005 -0.024 0.024 -0.037 -0.039 -0.013 -0.035 0. ] [-0.03 0.048 -0.047 -0.014 0.045 -0.049 -0.037 0.006 0.017 0.017] [ 0.003 0.011 -0.046 -0.014 -0.011 0.019 -0.026 0.035 0.032 -0.018] [ 0.02 -0.027 -0.025 -0.011 0. -0.042 0.009 -0.042 0.002 -0.002] [ 0.028 0.021 0.005 -0.024 0.024 -0.037 -0.039 -0.013 -0.035 0. ]] [[ 0.02 0.01 -0.023 0.041 0.015 -0.012 0.002 0.033 -0.012 -0.042] [ 0.044 0.015 0.031 -0.014 -0.045 -0.003 -0.02 0.009 -0.021 0.02 ] [ 0.004 0.028 -0.018 -0.002 0.016 0.039 -0.046 -0.046 0.002 0.001] [ 0.035 0.016 0.013 0.003 0.019 -0.033 -0.037 0.037 0.014 -0.018] [ 0.001 -0.019 0.041 0.002 0.044 0.007 -0.017 0.005 -0.03 0.02 ]]]
input_array
は、全文書の行列(文書数、単語ID)を想定output_array
は、単語の分散表現
ここでは、単語ID「16」のの分散表現が、
[ 0.028 0.021 0.005 -0.024 0.024 -0.037 -0.039 -0.013 -0.035 0. ]
のようになる。