1 回答
TA贡献1777条经验 获得超3个赞
您可以使用meanKeras 后端的函数并将其包装在一个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
这有助于实现更多的自定义平均函数。
添加回答
举报