您可以使用mean
Keras 后端的函数并将其包装在一个Lambda
层中,以平均单词的嵌入。
import keras
from keras.layers import Embedding
from keras.models import Sequential
import numpy as np
# Set parameters
vocab_size=1000
max_length=10
# Generate random embedding matrix for sake of illustration
embedding_matrix = np.random.rand(vocab_size,300)
model = Sequential()
model.add(Embedding(vocab_size, 300, weights=[embedding_matrix],
input_length=max_length, trainable=False))
# Average the output of the Embedding layer over the word dimension
model.add(keras.layers.Lambda(lambda x: keras.backend.mean(x, axis=1)))
model.summary()
给出:
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_6 (Embedding) (None, 10, 300) 300000
_________________________________________________________________
lambda_6 (Lambda) (None, 300) 0
=================================================================
Total params: 300,000
Trainable params: 0
Non-trainable params: 300,000
此外,您可以使用该Lambda
层包装在 Keras 层中对张量进行操作的任意函数,并将它们添加到您的模型中。如果您使用的是 TensorFlow 后端,您也可以访问 tensorflow 操作:
import tensorflow as tf
model = Sequential()
model.add(Embedding(vocab_size, 300, weights=[embedding_matrix],
input_length=max_length, trainable=False))
model.add(keras.layers.Lambda(lambda x: tf.reduce_mean(x, axis=1)))
# same model as before
这可以帮助实现更多的自定义平均函数。