我想使用 Functional API 创建一个支持掩码的自定义层,这意味着它在输入张量上传播掩码,以便输出也被掩码。
Keras 指南中有明确的说明,用于使用子类对自定义层执行此操作。这是一个支持遮罩的自定义图层的简单示例:
import tensorflow as tf
class CustomLayer(tf.keras.layers.Layer):
def __init__(self, multiplier=2.0):
super(CustomLayer, self).__init__()
self.multiplier = multiplier
self.supports_masking = True
def call(self, inputs):
return inputs * self.multiplier
当我们传递带有掩码的张量 x_emb
时,我们会看到它被传播:
raw_inputs = [
[711, 632, 71],
[73, 8, 3215, 55, 927],
[83, 91, 1, 645, 1253, 927],
]
padded_inputs = tf.keras.preprocessing.sequence.pad_sequences(
raw_inputs, padding="post"
)
embedding = tf.keras.layers.Embedding(5000, 16, mask_zero=True)
x_emb = embedding(padded_inputs)
custom_layer = CustomLayer()
output1 = custom_layer(x_emb)
print(output1._keras_mask)
顺序 API 自动支持屏蔽(假设其所有组成层都支持)。例如:
sequential_layer = tf.keras.Sequential([
custom_layer,
custom_layer
])
output2 = sequential_layer(x_emb)
print(output2._keras_mask)
我的问题是如果可能的话,如何让函数式 API 也支持屏蔽?默认情况下它不会:
inputs = tf.keras.layers.Input(shape=(None,))
outputs = custom_layer(inputs)
functional_layer = tf.keras.Model(inputs=inputs, outputs=outputs)
output3 = functional_layer(x_emb)
print(output3._keras_layer)
## AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute '_keras_layer'
编辑:这里没有问题。我用_keras_layer
代替_keras_mask
做了一个尴尬的字体。