Tensorflow 2.0 Hugging Face Transformers

概括:


我想微调 BERT 以在自定义数据集上进行句子分类。我遵循了一些我发现的例子,比如这个,这非常有帮助。我也看过这个要点。


我遇到的问题是,在对某些样本进行推理时,输出的维度超出了我的预期。


当我对 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哪个是编码标签。因为我进行推理,所以我提供的作为基本事实的内容当然不重要。


至尊宝的传说
浏览 77回答 2
2回答

森栏

我发现了问题——如果你在使用 Tensorflow 数据集(tf.data.Dataset)时得到意外的维度,可能是因为没有运行.batch。所以在我的例子中:features = convert_examples_to_tf_dataset(test_examples, tokenizer)添加:features = features.batch(BATCH_SIZE)使这项工作如我所料。所以,这不是与 相关的问题TFBertForSequenceClassification,只是因为我的输入不正确。我还想添加对这个答案的引用,这让我发现了问题。

子衿沉夜

我报告了我的示例,其中我尝试预测 3 个文本样本并获得 (3, 42) 作为输出形状### define modelconfig = 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 tokenizertokenizer = AutoTokenizer.from_pretrained("bert-base-multilingual-cased")### utility functions for text encodingdef 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 sentencesinput_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 predictionmodel.predict(input_).shape # ===> (3,42)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python