This model is a fine-tuned version of
google/flan-t5-small
on 200 000 random (text, entity) combinations from the
Universal-NER/Pile-NER-type and
Universal-NER/Pile-NER-definition datasets.
flan-t5-small-ner can extract entities of specific types or definitions from text such as person, company, school, technology, and many more.
It builds upon the FLAN-T5 architecture, which has strong performance across natural language processing tasks.
1from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
2import torch
3
4model_path = "agentlans/flan-t5-small-ner"
5model = AutoModelForSeq2SeqLM.from_pretrained(model_path).to("cuda" if torch.cuda.is_available() else "cpu")
6tokenizer = AutoTokenizer.from_pretrained(model_path)
7
8def custom_split(s): # Processes the output from the model
9 parts = s.split("<|sep|>")
10 if not s.endswith("<|end|>"):
11 parts = parts[:-1] # If output is truncated, then don't include last item
12 else:
13 parts[-1] = parts[-1].replace("<|end|>", "") # Remove the marker tokens
14 return [p.strip() for p in parts if p.strip()]
15
16def find_entities(input_text, entity_type):
17 txt = entity_type + "<|sep|>" + input_text + "<|end|>" # Important: need exact input format
18 inputs = tokenizer(txt, return_tensors="pt").to(model.device)
19 outputs = model.generate(**inputs, max_new_tokens=100)
20 decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
21 return custom_split(decoded)
22
23# Example usage
24input_text = "In the bustling metropolis of New York City, Apple Inc. sponsored a conference where Dr. Elena Rodriguez presented groundbreaking research about neuroscience and AI."
25print(find_entities(input_text, "person")) # ['Elena Rodriguez']
26print(find_entities(input_text, "company")) # ['Apple Inc.']
27print(find_entities(input_text, "fruit")) # []
28print(find_entities(input_text, "subject")) # ['neuroscience', 'AI']