Model Overview
Model Features
Model Capabilities
Use Cases
๐ EntityBERT Model
The boltuix/EntityBERT
model is a lightweight, fine - tuned transformer designed for Named Entity Recognition (NER). Built on the boltuix/bert - mini
base model, it's optimized for efficiency. This model can identify 36 entity types, such as people, organizations, locations, and dates, in English text. It's highly suitable for applications like information extraction, chatbots, and search enhancement.
๐ Quick Start
๐ป Usage Examples
Basic Usage
Run NER with the following Python code:
from transformers import AutoTokenizer, AutoModelForTokenClassification
import torch
# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("boltuix/EntityBERT")
model = AutoModelForTokenClassification.from_pretrained("boltuix/EntityBERT")
# Input text
text = "Elon Musk launched Tesla in California on March 2025."
inputs = tokenizer(text, return_tensors="pt")
# Run inference
with torch.no_grad():
outputs = model(**inputs)
predictions = outputs.logits.argmax(dim=-1)
# Map predictions to labels
tokens = tokenizer.convert_ids_to_tokens(inputs["input_ids"][0])
label_map = model.config.id2label
labels = [label_map[p.item()] for p in predictions[0]]
# Print results
for token, label in zip(tokens, labels):
if token not in tokenizer.all_special_tokens:
print(f"{token:15} โ {label}")
Example Output
Elon โ B - PERSON
Musk โ I - PERSON
launched โ O
Tesla โ B - ORG
in โ O
California โ B - GPE
on โ O
March โ B - DATE
2025 โ I - DATE
. โ O
๐ฆ Installation
pip install transformers torch pandas pyarrow seqeval
- Python: 3.8+
- Storage: ~15 MB for model weights, ~6.38 MB for dataset
- Optional:
seqeval
for evaluation,cuda
for GPU acceleration
Download Instructions ๐ฅ
- Model: boltuix/EntityBERT
โจ Features
๐ Model Details
- Dataset: [boltuix/conll2025 - ner](https://huggingface.co/datasets/boltuix/conll2025 - ner) (143,709 entries, 6.38 MB)
- Entity Types: 36 NER tags (18 entity categories with B - /I - tags + O)
- Training Examples: ~115,812 | Validation: ~15,680 | Test: ~12,217
- Domains: News, user - generated content, research corpora
- Tasks: Sentence - level and document - level NER
- Version: v1.0
๐ง Model Info
Property | Details |
---|---|
Developer | Boltuix |
License | Apache - 2.0 |
Language | English |
Model Type | Transformer - based Token Classification |
Trained | Before June 11, 2025 |
Base Model | boltuix/bert - mini |
Parameters | ~4.4M |
Size | ~15 MB |
๐ Useful Links
- Model Repository: boltuix/EntityBERT (placeholder, update with correct URL)
- Dataset: [boltuix/conll2025 - ner](https://huggingface.co/datasets/boltuix/conll2025 - ner)
- Hugging Face Docs: Transformers
- Demo: Coming Soon
๐ฏ Use Cases for NER
Direct Applications
- Information Extraction: Identify names (๐ค PERSON), locations (๐ GPE), and dates (๐๏ธ DATE) from articles, blogs, or reports.
- Chatbots & Virtual Assistants: Improve user query understanding by recognizing entities.
- Search Enhancement: Enable entity - based semantic search (e.g., โnews about Paris in 2025โ).
- Knowledge Graphs: Construct structured graphs connecting entities like ๐ข ORG and ๐ค PERSON.
Downstream Tasks
- Domain Adaptation: Fine - tune for specialized fields like medical ๐ฉบ, legal ๐, or financial ๐ธ NER.
- Multilingual Extensions: Retrain for non - English languages.
- Custom Entities: Adapt for niche domains (e.g., product IDs, stock tickers).
โ Limitations
- English - Only: Limited to English text out - of - the - box.
- Domain Bias: Trained on
boltuix/conll2025 - ner
, which may favor news and formal text, potentially weaker on informal or social media content. - Generalization: May struggle with rare or highly contextual entities not in the dataset.
๐ง Entity Labels
The model supports 36 NER tags from the boltuix/conll2025 - ner
dataset, using the BIO tagging scheme:
- B -: Beginning of an entity
- I -: Inside of an entity
- O: Outside of any entity
Tag Name | Purpose | Emoji |
---|---|---|
O | Outside of any named entity (e.g., "the", "is") | ๐ซ |
B - CARDINAL | Beginning of a cardinal number (e.g., "1000") | ๐ข |
B - DATE | Beginning of a date (e.g., "January") | ๐๏ธ |
B - EVENT | Beginning of an event (e.g., "Olympics") | ๐ |
B - FAC | Beginning of a facility (e.g., "Eiffel Tower") | ๐๏ธ |
B - GPE | Beginning of a geopolitical entity (e.g., "Tokyo") | ๐ |
B - LANGUAGE | Beginning of a language (e.g., "Spanish") | ๐ฃ๏ธ |
B - LAW | Beginning of a law or legal document (e.g., "Constitution") | ๐ |
B - LOC | Beginning of a non - GPE location (e.g., "Pacific Ocean") | ๐บ๏ธ |
B - MONEY | Beginning of a monetary value (e.g., "$100") | ๐ธ |
B - NORP | Beginning of a nationality/religious/political group (e.g., "Democrat") | ๐ณ๏ธ |
B - ORDINAL | Beginning of an ordinal number (e.g., "first") | ๐ฅ |
B - ORG | Beginning of an organization (e.g., "Microsoft") | ๐ข |
B - PERCENT | Beginning of a percentage (e.g., "50%") | ๐ |
B - PERSON | Beginning of a personโs name (e.g., "Elon Musk") | ๐ค |
B - PRODUCT | Beginning of a product (e.g., "iPhone") | ๐ฑ |
B - QUANTITY | Beginning of a quantity (e.g., "two liters") | โ๏ธ |
B - TIME | Beginning of a time (e.g., "noon") | โฐ |
B - WORK_OF_ART | Beginning of a work of art (e.g., "Mona Lisa") | ๐จ |
I - CARDINAL | Inside of a cardinal number | ๐ข |
I - DATE | Inside of a date (e.g., "2025" in "January 2025") | ๐๏ธ |
I - EVENT | Inside of an event name | ๐ |
I - FAC | Inside of a facility name | ๐๏ธ |
I - GPE | Inside of a geopolitical entity | ๐ |
I - LANGUAGE | Inside of a language name | ๐ฃ๏ธ |
I - LAW | Inside of a legal document title | ๐ |
I - LOC | Inside of a location | ๐บ๏ธ |
I - MONEY | Inside of a monetary value | ๐ธ |
I - NORP | Inside of a NORP entity | ๐ณ๏ธ |
I - ORDINAL | Inside of an ordinal number | ๐ฅ |
I - ORG | Inside of an organization name | ๐ข |
I - PERCENT | Inside of a percentage | ๐ |
I - PERSON | Inside of a personโs name | ๐ค |
I - PRODUCT | Inside of a product name | ๐ฑ |
I - QUANTITY | Inside of a quantity | โ๏ธ |
I - TIME | Inside of a time phrase | โฐ |
I - WORK_OF_ART | Inside of a work of art title | ๐จ |
Example:
Text: "Tesla opened in Shanghai on April 2025"
Tags: [B - ORG, O, O, B - GPE, O, B - DATE, I - DATE]
๐ Performance
Evaluated on the boltuix/conll2025 - ner
test split (~12,217 examples) using seqeval
:
Metric | Score |
---|---|
๐ฏ Precision | 0.84 |
๐ธ๏ธ Recall | 0.86 |
๐ถ F1 Score | 0.85 |
โ Accuracy | 0.91 |
Note: Performance may vary on different domains or text types.
๐ง Technical Details
โ๏ธ Training Setup
- Hardware: NVIDIA GPU
- Training Time: ~1.5 hours
- Parameters: ~4.4M
- Optimizer: AdamW
- Precision: FP32
- Batch Size: 16
- Learning Rate: 2e - 5
๐ง Training the Model
Fine - tune boltuix/bert - mini
on the boltuix/conll2025 - ner
dataset to replicate or extend EntityBERT
. Below is a simplified training script:
# ๐ ๏ธ Step 1: Install required libraries quietly
!pip install evaluate transformers datasets tokenizers seqeval pandas pyarrow -q
# ๐ซ Step 2: Disable Weights & Biases (WandB)
import os
os.environ["WANDB_MODE"] = "disabled"
# ๐ Step 2: Import necessary libraries
import pandas as pd
import datasets
import numpy as np
from transformers import BertTokenizerFast
from transformers import DataCollatorForTokenClassification
from transformers import AutoModelForTokenClassification
from transformers import TrainingArguments, Trainer
import evaluate
from transformers import pipeline
from collections import defaultdict
import json
# ๐ฅ Step 3: Load the CoNLL - 2025 NER dataset from Parquet
# Download : https://huggingface.co/datasets/boltuix/conll2025 - ner/blob/main/conll2025_ner.parquet
parquet_file = "conll2025_ner.parquet"
df = pd.read_parquet(parquet_file)
# ๐ Step 4: Convert pandas DataFrame to Hugging Face Dataset
conll2025 = datasets.Dataset.from_pandas(df)
# ๐ Step 5: Inspect the dataset structure
print("Dataset structure:", conll2025)
print("Dataset features:", conll2025.features)
print("First example:", conll2025[0])
# ๐ท๏ธ Step 6: Extract unique tags and create mappings
# Since ner_tags are strings, collect all unique tags
all_tags = set()
for example in conll2025:
all_tags.update(example["ner_tags"])
unique_tags = sorted(list(all_tags)) # Sort for consistency
num_tags = len(unique_tags)
tag2id = {tag: i for i, tag in enumerate(unique_tags)}
id2tag = {i: tag for i, tag in enumerate(unique_tags)}
print("Number of unique tags:", num_tags)
print("Unique tags:", unique_tags)
# ๐ง Step 7: Convert string ner_tags to indices
def convert_tags_to_ids(example):
example["ner_tags"] = [tag2id[tag] for tag in example["ner_tags"]]
return example
conll2025 = conll2025.map(convert_tags_to_ids)
# ๐ Step 8: Split dataset based on 'split' column
dataset_dict = {
"train": conll2025.filter(lambda x: x["split"] == "train"),
"validation": conll2025.filter(lambda x: x["split"] == "validation"),
"test": conll2025.filter(lambda x: x["split"] == "test")
}
conll2025 = datasets.DatasetDict(dataset_dict)
print("Split dataset structure:", conll2025)
# ๐ช Step 9: Initialize the tokenizer
tokenizer = BertTokenizerFast.from_pretrained("boltuix/bert - mini")
# ๐ Step 10: Tokenize an example text and inspect
example_text = conll2025["train"][0]
tokenized_input = tokenizer(example_text["tokens"], is_split_into_words=True)
tokens = tokenizer.convert_ids_to_tokens(tokenized_input["input_ids"])
word_ids = tokenized_input.word_ids()
print("Word IDs:", word_ids)
print("Tokenized input:", tokenized_input)
print("Length of ner_tags vs input IDs:", len(example_text["ner_tags"]), len(tokenized_input["input_ids"]))
# ๐ Step 11: Define function to tokenize and align labels
def tokenize_and_align_labels(examples, label_all_tokens=True):
"""
Tokenize inputs and align labels for NER tasks.
Args:
examples (dict): Dictionary with tokens and ner_tags.
label_all_tokens (bool): Whether to label all subword tokens.
Returns:
dict: Tokenized inputs with aligned labels.
"""
tokenized_inputs = tokenizer(examples["tokens"], truncation=True, is_split_into_words=True)
labels = []
for i, label in enumerate(examples["ner_tags"]):
word_ids = tokenized_inputs.word_ids(batch_index=i)
previous_word_idx = None
label_ids = []
for word_idx in word_ids:
if word_idx is None:
label_ids.append(-100) # Special tokens get -100
elif word_idx != previous_word_idx:
label_ids.append(label[word_idx]) # First token of word gets label
else:
label_ids.append(label[word_idx] if label_all_tokens else -100) # Subwords get label or -100
previous_word_idx = word_idx
labels.append(label_ids)
tokenized_inputs["labels"] = labels
return tokenized_inputs
# ๐งช Step 12: Test the tokenization and label alignment
q = tokenize_and_align_labels(conll2025["train"][0:1])
print("Tokenized and aligned example:", q)
# ๐ Step 13: Print tokens and their corresponding labels
for token, label in zip(tokenizer.convert_ids_to_tokens(q["input_ids"][0]), q["labels"][0]):
print(f"{token:_<40} {label}")
# ๐ง Step 14: Apply tokenization to the entire dataset
tokenized_datasets = conll2025.map(tokenize_and_align_labels, batched=True)
# ๐ค Step 15: Initialize the model with the correct number of labels
model = AutoModelForTokenClassification.from_pretrained("boltuix/bert - mini", num_labels=num_tags)
# โ๏ธ Step 16: Set up training arguments
args = TrainingArguments(
"boltuix/bert - ner",
eval_strategy="epoch", # Changed evaluation_strategy to eval_strategy
learning_rate=2e - 5,
per_device_train_batch_size=16,
per_device_eval_batch_size=16,
num_train_epochs=1,
weight_decay=0.01,
report_to="none"
)
# ๐ Step 17: Initialize data collator for dynamic padding
data_collator = DataCollatorForTokenClassification(tokenizer)
# ๐ Step 18: Load evaluation metric
metric = evaluate.load("seqeval")
# ๐ท๏ธ Step 19: Set label list and test metric computation
label_list = unique_tags
print("Label list:", label_list)
example = conll2025["train"][0]
labels = [label_list[i] for i in example["ner_tags"]]
print("Metric test:", metric.compute(predictions=[labels], references=[labels]))
# ๐ Step 20: Define function to compute evaluation metrics
def compute_metrics(eval_preds):
"""
Compute precision, recall, F1, and accuracy for NER.
Args:
eval_preds (tuple): Predicted logits and true labels.
Returns:
dict: Evaluation metrics.
"""
pred_logits, labels = eval_preds
pred_logits = np.argmax(pred_logits, axis=2)
predictions = [
[label_list[p] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(pred_logits, labels)
]
true_labels = [
[label_list[l] for (p, l) in zip(prediction, label) if l != -100]
for prediction, label in zip(pred_logits, labels)
]
results = metric.compute(predictions=predictions, references=true_labels)
return {
"precision": results["overall_precision"],
"recall": results["overall_recall"],
"f1": results["overall_f1"],
"accuracy": results["overall_accuracy"],
}
# ๐ Step 21: Initialize and train the trainer
trainer = Trainer(
model,
args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["validation"],
data_collator=data_collator,
tokenizer=tokenizer,
compute_metrics=compute_metrics
)
trainer.train()
# ๐พ Step 22: Save the fine - tuned model
model.save_pretrained("boltuix/bert - ner")
tokenizer.save_pretrained("tokenizer")
# ๐ Step 23: Update model configuration with label mappings
id2label = {str(i): label for i, label in enumerate(label_list)}
label2id = {label: str(i) for i, label in enumerate(label_list)}
config = json.load(open("boltuix/bert - ner/config.json"))
config["id2label"] = id2label
config["label2id"] = label2id
json.dump(config, open("boltuix/bert - ner/config.json", "w"))
# ๐ Step 24: Load the fine - tuned model
model_fine_tuned = AutoModelForTokenClassification.from_pretrained("boltuix/bert - ner")
# ๐ ๏ธ Step 25: Create a pipeline for NER inference
nlp = pipeline("token - classification", model=model_fine_tuned, tokenizer=tokenizer)
# ๐ Step 26: Perform NER on an example sentence
example = "On July 4th, 2023, President Joe Biden visited the United Nations headquarters in New York to deliver a speech about international law and donated $5 million to relief efforts."
ner_results = nlp(example)
print("NER results for first example:", ner_results)
# ๐ Step 27: Perform NER on a property address and format output
example = "This page contains information about the property located at 1275 Kinnear Rd, Columbus, OH, 43212."
ner_results = nlp(example)
# ๐งน Step 28: Process NER results into structured entities
entities = defaultdict(list)
current_entity = ""
current_type = ""
for item in ner_results:
entity = item["entity"]
word = item["word"]
if word.startswith("##"):
current_entity += word[2:] # Handle subword tokens
elif entity.startswith("B -"):
if current_entity and current_type:
entities[current_type].append(current_entity.strip())
current_type = entity[2:].lower()
current_entity = word
elif entity.startswith("I -") and entity[2:].lower() == current_type:
current_entity += " " + word # Continue same entity
else:
if current_entity and current_type:
entities[current_type].append(current_entity.strip())
current_entity = ""
current_type = ""
# Append final entity if exists
if current_entity and current_type:
entities[current_type].append(current_entity.strip())
# ๐ค Step 29: Output the final JSON
final_json = dict(entities)
print("Structured NER output:")
print(json.dumps(final_json, indent=2))
๐ ๏ธ Tips
- Hyperparameters: Experiment with
learning_rate
(1e - 5 to 5e - 5) ornum_train_epochs
(2 - 5). - GPU: Use
fp16=True
for faster training. - Custom Data: Modify the script for custom NER datasets.
โฑ๏ธ Expected Training Time
- ~1.5 hours on an NVIDIA GPU (e.g., T4) for ~115,812 examples, 3 epochs, batch size 16.
๐ Carbon Impact
- Emissions: ~40g COโeq (estimated via ML Impact tool for 1.5 hours on GPU).
๐ License
This project is licensed under the Apache - 2.0 license.






