注意:我已经发布了关于这个问题的here。我提出一个新问题是因为: 1我认为这个问题与在我的自定义层中重塑我的蒙版有关,但是我不确定是否完全忽略了我在原来的文章中提到的另一个错误。 2有许多关于重塑Keras层或添加掩蔽层的帖子,但我找不到任何关于重塑层内的掩蔽的帖子,所以我希望这篇帖子能更普遍地有用。你知道吗
问题是:
我有一个自定义的Keras层,它接受2D输入并返回3D输出(batch\u size,max\u length,1024),然后传递给BiLSTM和CRF。你知道吗
自定义Keras层是从this repository复制的。不同之处在于,我从elmo模型中获取“elmo”而不是“default”输出,因此输出是BiLSTM所要求的3D:
result = self.elmo(K.squeeze(K.cast(x, tf.string), axis=1),
as_dict=True,
signature='default',
)['elmo'] # The original code used 'default'
但是compute_mask函数不适合我的架构,因为它的输出是2D。因此我得到了错误:
InvalidArgumentError: Incompatible shapes: [32,47] vs. [32,0] [[{{node loss/crf_1_loss/mul_6}}]]
其中32是批量大小,47是一个小于我指定的最大\u长度。你知道吗
我肯定我需要重塑面具,但我找不到任何地方该怎么做。你知道吗
如果需要的话,很乐意用整个东西和/或完整的堆栈跟踪进行git回购。你知道吗
自定义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',)['elmo']
return result
# Original compute_mask function. Raises;
# InvalidArgumentError: Incompatible shapes: [32,47] vs. [32,0] [[{{node loss/crf_1_loss/mul_6}}]]
def compute_mask(self, inputs, mask=None):
return K.not_equal(inputs, '__PAD__')
def compute_output_shape(self, input_shape):
return input_shape[0], 48, self.dimensions
模型构建如下:
def build_model(): # uses crf from keras_contrib
input = layers.Input(shape=(1,), dtype=tf.string)
model = ElmoEmbeddingLayer(name='ElmoEmbeddingLayer')(input)
model = Bidirectional(LSTM(units=512, return_sequences=True))(model)
crf = CRF(num_tags)
out = crf(model)
model = Model(input, out)
model.compile(optimizer="rmsprop", loss=crf_loss, metrics=[crf_accuracy, categorical_accuracy, mean_squared_error])
model.summary()
return model
目前没有回答
相关问题 更多 >
编程相关推荐