Tensorflow 2.0拥抱面部变压器,TFBertForSequenceClassification,推断中的意外输出尺寸

时间:2020-05-07 11:38:06

标签: python tensorflow machine-learning nlp huggingface-transformers

摘要:

我想微调BERT,以对自定义数据集进行句子分类。我遵循了一些发现的示例,例如this one,这非常有帮助。我也看过this gist

我的问题是,对某些样本进行推断时,输出的尺寸超出了我的预期。

当我对23个样本进行推论时,我得到一个元组,其数组的维数为numpy(1472,42),其中42是类的数量。我希望尺寸为(23,42)。

代码和其他详细信息:

我像这样使用Keras对训练后的模型进行推论:

preds = model.predict(features)

功能被标记化并转换为数据集的地方:

for sample, ground_truth in tests:
    test_examples.append(InputExample(text=sample, category_index=ground_truth))

features = convert_examples_to_tf_dataset(test_examples, tokenizer)

sample可以是例如"A test sentence I want classified"ground_truth可以是12是编码标签。因为我进行推理,所以我提供的作为地面真理的东西当然不应该。

convert_examples_to_tf_dataset函数的外观如下(我在this gist中找到):

def convert_examples_to_tf_dataset(
    examples: List[Tuple[str, int]],
    tokenizer,
    max_length=64,
):
    """
    Loads data into a tf.data.Dataset for finetuning a given model.

    Args:
        examples: List of tuples representing the examples to be fed
        tokenizer: Instance of a tokenizer that will tokenize the examples
        max_length: Maximum string length

    Returns:
        a ``tf.data.Dataset`` containing the condensed features of the provided sentences
    """
    features = [] # -> will hold InputFeatures to be converted later

    for e in examples:
        # Documentation is really strong for this method, so please take a look at it
        input_dict = tokenizer.encode_plus(
            e.text,
            add_special_tokens=True,
            max_length=max_length, # truncates if len(s) > max_length
            return_token_type_ids=True,
            return_attention_mask=True,
            pad_to_max_length=True, # pads to the right by default
        )

        # input ids = token indices in the tokenizer's internal dict
        # token_type_ids = binary mask identifying different sequences in the model
        # attention_mask = binary mask indicating the positions of padded tokens so the model does not attend to them

        input_ids, token_type_ids, attention_mask = (input_dict["input_ids"],
            input_dict["token_type_ids"], input_dict['attention_mask'])

        features.append(
            InputFeatures(
                input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, label=e.category_index
            )
        )

    def gen():
        for f in features:
            yield (
                {
                    "input_ids": f.input_ids,
                    "attention_mask": f.attention_mask,
                    "token_type_ids": f.token_type_ids,
                },
                f.label,
            )

    return tf.data.Dataset.from_generator(
        gen,
        ({"input_ids": tf.int32, "attention_mask": tf.int32, "token_type_ids": tf.int32}, tf.int64),
        (
            {
                "input_ids": tf.TensorShape([None]),
                "attention_mask": tf.TensorShape([None]),
                "token_type_ids": tf.TensorShape([None]),
            },
            tf.TensorShape([]),
        ),
    )

with tf.device('/cpu:0'):
    train_data = convert_examples_to_tf_dataset(train_examples, tokenizer)
    train_data = train_data.shuffle(buffer_size=len(train_examples), reshuffle_each_iteration=True) \
                           .batch(BATCH_SIZE) \
                           .repeat(-1)

    val_data = convert_examples_to_tf_dataset(val_examples, tokenizer)
    val_data = val_data.shuffle(buffer_size=len(val_examples), reshuffle_each_iteration=True) \
                           .batch(BATCH_SIZE) \
                           .repeat(-1)

它按预期运行,运行print(list(features.as_numpy_iterator())[1])会产生以下结果:

({'input_ids': array([  101, 11639, 19962, 23288, 13264, 35372, 10410,   102,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0,     0,     0,     0,     0,     0,     0,     0,     0,
           0], dtype=int32), 'attention_mask': array([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      dtype=int32), 'token_type_ids': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      dtype=int32)}, 6705)

到目前为止,一切看起来都与我期望的一样。似乎分词器正在按预期工作; 3个长度为64的数组(与我设置的最大长度相对应),标签为整数。

已对模型进行如下训练:

config = BertConfig.from_pretrained(
    'bert-base-multilingual-cased',
    num_labels=len(label_encoder.classes_),
    output_hidden_states=False,
    output_attentions=False
)
model = TFBertForSequenceClassification.from_pretrained('bert-base-multilingual-cased', config=config)

# train_data is then a tf.data.Dataset we can pass to model.fit()
optimizer = tf.keras.optimizers.Adam(learning_rate=3e-05, epsilon=1e-08)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy')
model.compile(optimizer=optimizer,
              loss=loss,
              metrics=[metric])

model.summary()

history = model.fit(train_data,
                    epochs=EPOCHS,
                    steps_per_epoch=train_steps,
                    validation_data=val_data,
                    validation_steps=val_steps,
                    shuffle=True,
                    )

结果

现在的问题是,运行预测preds = model.predict(features)时,输出尺寸与documentation所说的logits (Numpy array or tf.Tensor of shape (batch_size, config.num_labels)):不对应。 我得到的是一个元组,其中包含一个尺寸为(1472,42)的numpy数组。

42很有意义,因为这是我的课程数量。我发送了23个样本进行测试,结果为23 x 64 =1472。64是我的最大句子长度,因此听起来有些熟悉。这个输出不正确吗?如何将每个输入样本的输出转换为实际的类别预测?当我预期为23时,我会得到1472个预测。

请告知我是否可以提供更多有助于解决此问题的详细信息。

2 个答案:

答案 0 :(得分:2)

我发现了问题-如果在使用Tensorflow数据集(tf.data.Dataset)时获得了意外的尺寸,则可能是由于未运行.batch

所以在我的示例中:

features = convert_examples_to_tf_dataset(test_examples, tokenizer)

添加:

features = features.batch(BATCH_SIZE)

使这项工作如我所期望的那样。因此,这不是与TFBertForSequenceClassification相关的问题,仅是由于我的输入不正确。我还想添加对this answer的引用,这使我发现了问题。

答案 1 :(得分:1)

我报告了我的示例,其中我尝试预测3个文本样本并获得(3,42)作为输出形状

### define model
config = BertConfig.from_pretrained(
    'bert-base-multilingual-cased',
    num_labels=42,
    output_hidden_states=False,
    output_attentions=False
)
model = TFBertForSequenceClassification.from_pretrained('bert-base-multilingual-cased', config=config)

optimizer = tf.keras.optimizers.Adam(learning_rate=3e-05, epsilon=1e-08)
loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
metric = tf.keras.metrics.SparseCategoricalAccuracy(name='accuracy')
model.compile(optimizer=optimizer,
              loss=loss,
              metrics=[metric])

### import tokenizer
tokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")

### utility functions for text encoding
def return_id(str1, str2, length):

    inputs = tokenizer.encode_plus(str1, str2,
        add_special_tokens=True,
        max_length=length)

    input_ids =  inputs["input_ids"]
    input_masks = [1] * len(input_ids)
    input_segments = inputs["token_type_ids"]

    padding_length = length - len(input_ids)
    padding_id = tokenizer.pad_token_id

    input_ids = input_ids + ([padding_id] * padding_length)
    input_masks = input_masks + ([0] * padding_length)
    input_segments = input_segments + ([0] * padding_length)

    return [input_ids, input_masks, input_segments]

### encode 3 sentences
input_ids, input_masks, input_segments = [], [], []
for instance in ['hello hello', 'ciao ciao', 'marco marco']:

    ids, masks, segments = \
    return_id(instance, None, 100)

    input_ids.append(ids)
    input_masks.append(masks)
    input_segments.append(segments)

input_ = [np.asarray(input_ids, dtype=np.int32), 
          np.asarray(input_masks, dtype=np.int32), 
          np.asarray(input_segments, dtype=np.int32)]

### make prediction
model.predict(input_).shape # ===> (3,42)