亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Tensorflow 2.0 Hugging Face Transformers

Tensorflow 2.0 Hugging Face Transformers

至尊寶的傳說 2022-11-09 16:21:59
概括:我想微調 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哪個是編碼標簽。因為我進行推理,所以我提供的作為基本事實的內容當然不重要。
查看完整描述

2 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

我發現了問題——如果你在使用 Tensorflow 數據集(tf.data.Dataset)時得到意外的維度,可能是因為沒有運行.batch。

所以在我的例子中:

features = convert_examples_to_tf_dataset(test_examples, tokenizer)

添加:

features = features.batch(BATCH_SIZE)

使這項工作如我所料。所以,這不是與 相關的問題TFBertForSequenceClassification,只是因為我的輸入不正確。我還想添加對這個答案的引用,這讓我發現了問題。


查看完整回答
反對 回復 2022-11-09
?
子衿沉夜

TA貢獻1828條經驗 獲得超3個贊

我報告了我的示例,其中我嘗試預測 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)


查看完整回答
反對 回復 2022-11-09
  • 2 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號