请注意Press and Wolf 不建议将权重冻结到一些预训练的权重,而是将它们绑定。这意味着,要确保在训练期间输入和输出权重始终相同(在同步的意义上)。
在典型的 NLP 模型(例如语言建模/翻译)中,您有一个大小为 V 的输入维度(词汇表)和一个大小为 H 的隐藏表示。然后,您从Embedding 层开始,它是一个矩阵VxH。输出层(可能)类似于Dense(V, activation='softmax'),它是一个矩阵H2xV。绑定权重时,我们希望这些矩阵相同(因此,H==H2)。
对于在 Keras 中执行此操作,我认为要走的路是通过共享层:
在您的模型中,您需要实例化一个共享嵌入层(维度为VxH),并将其应用于您的输入和输出。但是您需要对其进行转置,以获得所需的输出尺寸 (HxV)。因此,我们声明一个TiedEmbeddingsTransposed 层,它从给定层转置嵌入矩阵(并应用激活函数):
class TiedEmbeddingsTransposed(Layer):
"""Layer for tying embeddings in an output layer.
A regular embedding layer has the shape: V x H (V: size of the vocabulary. H: size of the projected space).
In this layer, we'll go: H x V.
With the same weights than the regular embedding.
In addition, it may have an activation.
# References
- [ Using the Output Embedding to Improve Language Models](https://arxiv.org/abs/1608.05859)
"""
def __init__(self, tied_to=None,
activation=None,
**kwargs):
super(TiedEmbeddingsTransposed, self).__init__(**kwargs)
self.tied_to = tied_to
self.activation = activations.get(activation)
def build(self, input_shape):
self.transposed_weights = K.transpose(self.tied_to.weights[0])
self.built = True
def compute_mask(self, inputs, mask=None):
return mask
def compute_output_shape(self, input_shape):
return input_shape[0], K.int_shape(self.tied_to.weights[0])[0]
def call(self, inputs, mask=None):
output = K.dot(inputs, self.transposed_weights)
if self.activation is not None:
output = self.activation(output)
return output
def get_config(self):
config = {'activation': activations.serialize(self.activation)
}
base_config = super(TiedEmbeddingsTransposed, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
这一层的用法是:
# Declare the shared embedding layer
shared_embedding_layer = Embedding(V, H)
# Obtain word embeddings
word_embedding = shared_embedding_layer(input)
# Do stuff with your model
# Compute output (e.g. a vocabulary-size probability vector) with the shared layer:
output = TimeDistributed(TiedEmbeddingsTransposed(tied_to=shared_embedding_layer, activation='softmax')(intermediate_rep)
我已经在NMT-Keras 中对此进行了测试,并且可以正常训练。但是,当我尝试加载经过训练的模型时,它会出现错误,这与 Keras 加载模型的方式有关:它没有从 tied_to 加载权重。我发现了几个关于此的问题(1、2、3),但我还没有设法解决这个问题。如果有人对接下来要采取的步骤有任何想法,我会很高兴听到他们的声音:)