模型概述
模型特點
模型能力
使用案例
🚀 NeuroBERT-Mini — 適用於邊緣AI、物聯網和設備端NLP的快速BERT模型
NeuroBERT-Mini是一款輕量級的NLP模型,它源自google/bert-base-uncased,專為邊緣和物聯網設備的即時推理進行了優化。該模型量化後僅約35MB,擁有約1000萬個參數,能在資源受限的環境(如移動應用、可穿戴設備、微控制器和智能家居設備)中實現高效的上下文語言理解。它具備低延遲和離線操作的特性,非常適合對隱私要求較高且網絡連接有限的應用場景。
🚀 快速開始
NeuroBERT-Mini
是一個從 google/bert-base-uncased 派生而來的輕量級 NLP 模型,針對邊緣和物聯網設備上的即時推理進行了優化。其量化後的大小約為 35MB,參數約為 1000 萬,能夠在資源受限的環境(如移動應用、可穿戴設備、微控制器和智能家居設備)中實現高效的上下文語言理解。該模型設計用於低延遲和離線操作,非常適合對隱私要求較高且網絡連接有限的應用場景。
✨ 主要特性
- 輕量級:約35MB的佔用空間,適合存儲容量有限的設備。
- 上下文理解:通過緊湊的架構捕捉語義關係。
- 離線能力:無需互聯網即可完全正常運行。
- 即時推理:針對CPU、移動NPU和微控制器進行了優化。
- 應用廣泛:支持掩碼語言建模(MLM)、意圖檢測、文本分類和命名實體識別(NER)。
📦 安裝指南
安裝所需的依賴項:
pip install transformers torch
確保您的環境支持Python 3.6+,並且有大約35MB的存儲空間用於存儲模型權重。
💻 使用示例
基礎用法
掩碼語言建模
預測與物聯網相關句子中缺失的單詞:
from transformers import pipeline
# 發揮模型的強大功能
mlm_pipeline = pipeline("fill-mask", model="boltuix/NeuroBERT-Mini")
# 測試模型的效果
result = mlm_pipeline("Please [MASK] the door before leaving.")
print(result[0]["sequence"]) # 輸出: "Please open the door before leaving."
文本分類
對物聯網命令進行意圖檢測或文本分類:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
# 加載分詞器和分類模型
model_name = "boltuix/NeuroBERT-Mini"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
model.eval()
# 示例輸入
text = "Turn off the fan"
# 對輸入進行分詞
inputs = tokenizer(text, return_tensors="pt")
# 獲取預測結果
with torch.no_grad():
outputs = model(**inputs)
probs = torch.softmax(outputs.logits, dim=1)
pred = torch.argmax(probs, dim=1).item()
# 定義標籤
labels = ["OFF", "ON"]
# 打印結果
print(f"Text: {text}")
print(f"Predicted intent: {labels[pred]} (Confidence: {probs[0][pred]:.4f})")
高級用法
微調模型
為了使NeuroBERT-Mini適應自定義的物聯網任務(例如特定的智能家居命令),可以按照以下步驟進行微調:
#!pip uninstall -y transformers torch datasets
#!pip install transformers==4.44.2 torch==2.4.1 datasets==3.0.1
import torch
from transformers import BertTokenizer, BertForSequenceClassification, Trainer, TrainingArguments
from datasets import Dataset
import pandas as pd
# 1. 準備示例物聯網數據集
data = {
"text": [
"Turn on the fan",
"Switch off the light",
"Invalid command",
"Activate the air conditioner",
"Turn off the heater",
"Gibberish input"
],
"label": [1, 1, 0, 1, 1, 0] # 1 表示有效的物聯網命令,0 表示無效
}
df = pd.DataFrame(data)
dataset = Dataset.from_pandas(df)
# 2. 加載分詞器和模型
model_name = "boltuix/NeuroBERT-Mini" # 使用 NeuroBERT-Mini
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2)
# 3. 對數據集進行分詞
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True, max_length=64) # 針對物聯網命令設置較短的最大長度
tokenized_dataset = dataset.map(tokenize_function, batched=True)
# 4. 設置 PyTorch 格式
tokenized_dataset.set_format("torch", columns=["input_ids", "attention_mask", "label"])
# 5. 定義訓練參數
training_args = TrainingArguments(
output_dir="./iot_neurobert_results",
num_train_epochs=5, # 對於小數據集增加訓練輪數
per_device_train_batch_size=2,
logging_dir="./iot_neurobert_logs",
logging_steps=10,
save_steps=100,
evaluation_strategy="no",
learning_rate=3e-5, # 針對 NeuroBERT-Mini 進行調整
)
# 6. 初始化訓練器
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_dataset,
)
# 7. 微調模型
trainer.train()
# 8. 保存微調後的模型
model.save_pretrained("./fine_tuned_neurobert_iot")
tokenizer.save_pretrained("./fine_tuned_neurobert_iot")
# 9. 示例推理
text = "Turn on the light"
inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=64)
model.eval()
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class = torch.argmax(logits, dim=1).item()
print(f"Predicted class for '{text}': {'Valid IoT Command' if predicted_class == 1 else 'Invalid Command'}")
📚 詳細文檔
評估
NeuroBERT-Mini在掩碼語言建模任務上使用了10個與物聯網相關的句子進行評估。模型會為每個掩碼詞預測前5個標記,如果預期的單詞在前5個預測中,則測試通過。
測試句子
句子 | 預期單詞 |
---|---|
She is a [MASK] at the local hospital. | nurse |
Please [MASK] the door before leaving. | shut |
The drone collects data using onboard [MASK]. | sensors |
The fan will turn [MASK] when the room is empty. | off |
Turn [MASK] the coffee machine at 7 AM. | on |
The hallway light switches on during the [MASK]. | night |
The air purifier turns on due to poor [MASK] quality. | air |
The AC will not run if the door is [MASK]. | open |
Turn off the lights after [MASK] minutes. | five |
The music pauses when someone [MASK] the room. | enters |
評估代碼
from transformers import AutoTokenizer, AutoModelForMaskedLM
import torch
# 加載模型和分詞器
model_name = "boltuix/NeuroBERT-Mini"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForMaskedLM.from_pretrained(model_name)
model.eval()
# 測試數據
tests = [
("She is a [MASK] at the local hospital.", "nurse"),
("Please [MASK] the door before leaving.", "shut"),
("The drone collects data using onboard [MASK].", "sensors"),
("The fan will turn [MASK] when the room is empty.", "off"),
("Turn [MASK] the coffee machine at 7 AM.", "on"),
("The hallway light switches on during the [MASK].", "night"),
("The air purifier turns on due to poor [MASK] quality.", "air"),
("The AC will not run if the door is [MASK].", "open"),
("Turn off the lights after [MASK] minutes.", "five"),
("The music pauses when someone [MASK] the room.", "enters")
]
results = []
# 運行測試
for text, answer in tests:
inputs = tokenizer(text, return_tensors="pt")
mask_pos = (inputs.input_ids == tokenizer.mask_token_id).nonzero(as_tuple=True)[1]
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits[0, mask_pos, :]
topk = logits.topk(5, dim=1)
top_ids = topk.indices[0]
top_scores = torch.softmax(topk.values, dim=1)[0]
guesses = [(tokenizer.decode([i]).strip().lower(), float(score)) for i, score in zip(top_ids, top_scores)]
results.append({
"sentence": text,
"expected": answer,
"predictions": guesses,
"pass": answer.lower() in [g[0] for g in guesses]
})
# 打印結果
for r in results:
status = "✔️ PASS" if r["pass"] else "❌ FAIL"
print(f"\n🔍 {r['sentence']}")
print(f"🎯 Expected: {r['expected']}")
print("📋 Top-5 Predictions (word : confidence):")
for word, score in r['predictions']:
print(f" - {word:12} | {score:.4f}")
print(status)
# 總結
pass_count = sum(r["pass"] for r in results)
print(f"\n🎉 Total Passed: {pass_count}/{len(tests)}")
示例結果(假設)
- 句子:She is a [MASK] at the local hospital.
預期:nurse
前5個:[doctor (0.35), nurse (0.30), surgeon (0.20), technician (0.10), assistant (0.05)]
結果:✔️ PASS - 句子:Turn off the lights after [MASK] minutes.
預期:five
前5個:[ten (0.40), two (0.25), three (0.20), fifteen (0.10), twenty (0.05)]
結果:❌ FAIL - 總通過數:~8/10(取決於微調情況)
該模型在物聯網相關的上下文中表現良好(例如,“sensors”、“off”、“open”),但對於像“five”這樣的數字術語可能需要進行微調。
評估指標
指標 | 數值(約) |
---|---|
準確率 | 約為BERT-base的92 - 97% |
F1分數 | 在MLM/NER任務中保持平衡 |
推理延遲 | 在樹莓派上小於40ms |
召回率 | 在輕量級模型中具有競爭力 |
注意:這些指標會根據硬件(例如,樹莓派4、安卓設備)和微調情況而有所不同。建議在目標設備上進行測試以獲得準確的結果。
使用場景
NeuroBERT-Mini專為計算和連接受限的邊緣和物聯網場景而設計。主要應用包括:
- 智能家居設備:解析諸如“Turn [MASK] the coffee machine”(預測為“on”)或“The fan will turn [MASK]”(預測為“off”)之類的命令。
- 物聯網傳感器:解釋傳感器相關的上下文,例如“The drone collects data using onboard [MASK]”(預測為“sensors”)。
- 可穿戴設備:即時意圖檢測,例如“The music pauses when someone [MASK] the room”(預測為“enters”)。
- 移動應用:離線聊天機器人或語義搜索,例如“She is a [MASK] at the hospital”(預測為“nurse”)。
- 語音助手:本地命令解析,例如“Please [MASK] the door”(預測為“shut”)。
- 玩具機器人:用於交互式玩具的輕量級命令理解。
- 健身追蹤器:本地文本反饋處理,例如情感分析。
- 汽車助手:無需雲API的離線命令消歧。
硬件要求
- 處理器:CPU、移動NPU或微控制器(例如,ESP32、樹莓派)
- 存儲:約35MB用於存儲模型權重(量化後以減小佔用空間)
- 內存:約80MB RAM用於推理
- 環境:離線或低連接環境
量化處理確保了高效的內存使用,使其適用於微控制器。
訓練數據
- 自定義物聯網數據集:精心策劃的數據,專注於物聯網術語、智能家居命令和傳感器相關的上下文(源自chatgpt-datasets)。這有助於提高在命令解析和設備控制等任務上的性能。
建議在特定領域的數據上進行微調以獲得最佳效果。
與其他模型的比較
模型 | 參數數量 | 大小 | 邊緣/物聯網關注度 | 支持的任務 |
---|---|---|---|---|
NeuroBERT-Mini | 約1000萬 | 約35MB | 高 | MLM、NER、分類 |
NeuroBERT-Tiny | 約500萬 | 約15MB | 高 | MLM、NER、分類 |
DistilBERT | 約6600萬 | 約200MB | 中等 | MLM、NER、分類 |
TinyBERT | 約1400萬 | 約50MB | 中等 | MLM、分類 |
NeuroBERT-Mini在大小和性能之間取得了平衡,非常適合比NeuroBERT-Tiny目標設備資源稍多的邊緣設備。
🔧 技術細節
模型信息
屬性 | 詳情 |
---|---|
模型類型 | 輕量級BERT(2層,隱藏層大小256,4個注意力頭) |
訓練數據 | 自定義物聯網數據集,專注於物聯網術語、智能家居命令和傳感器相關上下文 |
📄 許可證
MIT許可證:可免費用於個人和商業目的,可進行修改和分發。詳情請見 LICENSE。
致謝
- 基礎模型:google-bert/bert-base-uncased
- 優化者:boltuix,為邊緣AI應用進行了量化處理
- 庫:Hugging Face
transformers
團隊提供模型託管和工具
支持與社區
如果您有任何問題、疑問或想要貢獻代碼,請:
- 訪問 Hugging Face模型頁面
- 在 倉庫 中提出問題
- 參與Hugging Face上的討論或通過拉取請求進行貢獻
- 查看 Transformers文檔 獲取指導
瞭解更多
在Boltuix上探索有關BERT Mini的詳細信息和見解:
BERT Mini: Lightweight BERT for Edge AI
我們歡迎社區反饋,以進一步改進NeuroBERT-Mini在物聯網和邊緣應用中的性能!
標籤
#NeuroBERT-Mini
#edge-nlp
#lightweight-models
#on-device-ai
#offline-nlp
#mobile-ai
#intent-recognition
#text-classification
#ner
#transformers
#mini-transformers
#embedded-nlp
#smart-device-ai
#low-latency-models
#ai-for-iot
#efficient-bert
#nlp2025
#context-aware
#edge-ml
#smart-home-ai
#contextual-understanding
#voice-ai
#eco-ai



