重塑的输入与请求的形状不匹配

2024-09-29 17:10:01 发布

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

我知道其他人已经发布了类似的问题,但我在这里找不到合适的解决方案

我已经编写了一个自定义的keras层,用于根据掩码平均DistilBert的输出。也就是说,我有dim=[batch_size, n_tokens_out, 768]进来,基于dim=[batch_size, n_tokens_out]的掩码沿着n_tokens_out进行掩码。输出应该是dim=[batch_size, 768]。以下是该层的代码:

class CustomPool(tf.keras.layers.Layer):
    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        super(CustomPool, self).__init__(**kwargs)
    
    def call(self, x, mask):
        masked = tf.cast(tf.boolean_mask(x, mask = mask, axis = 0), tf.float32)
        mn = tf.reduce_mean(masked, axis = 1, keepdims=True)
        return tf.reshape(mn, (tf.shape(x)[0], self.output_dim))
    
    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

模型编译时没有错误,但培训一开始,我就出现以下错误:

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument:  Input to reshape is a tensor with 967 values, but the requested shape has 12288
     [[node pooled_distilBert/CustomPooling/Reshape (defined at <ipython-input-245-a498c2817fb9>:13) ]]
     [[assert_greater_equal/Assert/AssertGuard/pivot_f/_3/_233]]
  (1) Invalid argument:  Input to reshape is a tensor with 967 values, but the requested shape has 12288
     [[node pooled_distilBert/CustomPooling/Reshape (defined at <ipython-input-245-a498c2817fb9>:13) ]]
0 successful operations.
0 derived errors ignored. [Op:__inference_train_function_211523]

Errors may have originated from an input operation.
Input Source operations connected to node pooled_distilBert/CustomPooling/Reshape:
 pooled_distilBert/CustomPooling/Mean (defined at <ipython-input-245-a498c2817fb9>:11)

Input Source operations connected to node pooled_distilBert/CustomPooling/Reshape:
 pooled_distilBert/CustomPooling/Mean (defined at <ipython-input-245-a498c2817fb9>:11)

我得到的维度比预期的维度小,这对我来说很奇怪

以下是模型的外观(TFDistilBertModel来自huggingfacetransformers库):

dbert_layer = TFDistilBertModel.from_pretrained('distilbert-base-uncased')

in_id = tf.keras.layers.Input(shape=(seq_max_length,), dtype='int32', name="input_ids")
in_mask = tf.keras.layers.Input(shape=(seq_max_length,), dtype='int32', name="input_masks")
    
dbert_inputs = [in_id, in_mask]
dbert_output = dbert_layer(dbert_inputs)[0]
x = CustomPool(output_dim = dbert_output.shape[2], name='CustomPooling')(dbert_output, in_mask)
dense1 = tf.keras.layers.Dense(256, activation = 'relu', name='dense256')(x)
pred = tf.keras.layers.Dense(n_classes, activation='softmax', name='MODEL_OUT')(dense1)

model = tf.keras.models.Model(inputs = dbert_inputs, outputs = pred, name='pooled_distilBert')

这里的任何帮助都将得到极大的感谢,因为我已经浏览了现有的问题,大多数问题最终都是通过指定输入形状来解决的(在我的情况下不适用)


Tags: nameselfinputoutputlayerstfmaskkeras

热门问题