用ELMO和Keras?

2024-05-23 21:40:07 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我开始在我的模型中使用手套,它工作得很好,但现在我想换成Elmo,但我总是遇到这样的错误:

ValueError: A Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 20), (None, 20), (None, 20, 5)]

你能帮帮我吗?下面是我的代码片段:如果需要更多详细信息,请告诉我。在

Keras的Elmo

class ElmoEmbeddingLayer(Layer):
    def __init__(self, **kwargs):
        self.dimensions = 1024
        self.trainable = True
        super(ElmoEmbeddingLayer, self).__init__(**kwargs)
def build(self, input_shape):
        self.elmo = hub.Module('https://tfhub.dev/google/elmo/2', trainable=self.trainable, name="{}_module".format(self.name))
        self.trainable_weights += K.tf.trainable_variables(scope="^{}_module/.*".format(self.name))
        super(ElmoEmbeddingLayer, self).build(input_shape)
def call(self, x, mask=None):
        result = self.elmo(K.squeeze(K.cast(x, tf.string), axis=1),
                      as_dict=True,
                      signature='default',
                      )['default']
        return result
def compute_mask(self, inputs, mask=None):
        return K.not_equal(inputs, '--PAD--')
def compute_output_shape(self, input_shape):
        return (input_shape[0], self.dimensions)

我的模型

^{pr2}$

Tags: name模型selfnoneinputreturndefmask
1条回答
网友
1楼 · 发布于 2024-05-23 21:40:07

你还没有提供你的预测层。 但是错误发生在连接层,所以可以使用您提供的代码来解决这个错误。 首先,我很惊讶您之前没有收到错误,因为带有signature='default'的Elmo需要一个字符串作为输入。(您应该以空格分隔的标记形式提供所有输入,例如。 ["the cat is on the mat", "dogs are in the fog"], ) 或使用

embeddings = elmo(
inputs={
"tokens": tokens_input,
"sequence_len": tokens_length
},
signature="tokens",
as_dict=True)["elmo"]

但现在让我们使用空格分隔的令牌。在

因此,ElmoEmbeddingLayer输入的唯一可能值是1,我们得到

^{pr2}$

所以现在它起作用了(至少对我来说)。 今后我建议您将签名从'default'改为'elmo'。在

相关问题 更多 >