bert-base-uncased 微调的二分类灾情推文分类器(DISASTER / NOT_DISASTER),同时提供 Hugging Face transformers
与 transformers.js(ONNX)两种推理方式。
测试集 n = 762,正类 = DISASTER。
| 版本 | acc | F1 | precision | recall | 体积 |
|---|---|---|---|---|---|
| PyTorch (out/best) | 0.8478 | 0.8165 | 0.8459 | 0.7890 | 438 MB |
| ONNX fp32 | 0.8478 | 0.8165 | 0.8459 | 0.7890 | 438 MB |
| ONNX int8(逐通道动态量化) | 0.8294 | 0.7727 | 0.9020 | 0.6758 | 111 MB |
ONNX fp32 与 PyTorch 输出逐元素一致(max|diff| = 0.0000)。
| 项 | 值 |
|---|---|
| base model | bert-base-uncased |
| epochs | 3 |
| batch size | 32 |
| lr | 2e-5 |
| warmup ratio | 0.1 |
| max_len | 128 |
| seed | 42 |
| 训练耗时 | 175 s(RTX 4060 Ti 8GB) |
import { pipeline } from "https://cdn.jsdelivr.net/npm/@huggingface/transformers@3.5.1";
const clf = await pipeline("text-classification", "dylanqi27/disaster-tweet-bert", { dtype: "q8" });
console.log(await clf("Forest fire near La Ronge Sask. Canada"));
// [{ label: "DISASTER", score: 0.998 }]
dtype 可选 q8(111MB,默认,对应 onnx/model_quantized.onnx)或 fp32(438MB,对应 onnx/model.onnx)。
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
tok = AutoTokenizer.from_pretrained("dylanqi27/disaster-tweet-bert")
model = AutoModelForSequenceClassification.from_pretrained("dylanqi27/disaster-tweet-bert")
enc = tok(["Forest fire near La Ronge Sask. Canada"], return_tensors="pt", truncation=True, max_length=128)
with torch.no_grad():
probs = model(**enc).logits.softmax(-1)[0]
print(model.config.id2label[probs.argmax().item()], round(probs.max().item(), 4))
import onnxruntime as ort
sess = ort.InferenceSession("onnx/model_quantized.onnx")
# inputs: input_ids, attention_mask, token_type_ids(int64,dynamic batch/sequence)
# output: logits [batch, 2]
config.json # id2label: 0=NOT_DISASTER, 1=DISASTER
tokenizer.json
tokenizer_config.json
onnx/model.onnx # fp32, 438MB
onnx/model_quantized.onnx # int8 per-channel, 111MB
在线演示:https://huggingface.co/spaces/dylanqi27/disaster-tweet-demo-static
onnx/model.onnx 438 MBonnx/model_quantized.onnx 111 MBgoogle-bert/bert-base-uncased