Downloads · 30 days
6
0% of all-time downloads
andgonzalez/bert-uncased-slot-filling
bert-uncased-slot-filling is a token classification model from andgonzalez. Use it when you need labels on individual words, such as names. It is set up for transformers.
This BERT-based model is designed for slot filling tasks in natural language sentences, ideal for extracting specific information in applications like chatbots and virtual assistants.
Downloads · 30 days
6
0% of all-time downloads
All-time downloads
1.2K
Public
Parameters
109M
436 MB on disk
Likes
0
Public
Click a slice to open those files.
.safetensors436 MB · 100%
From the Hugging Face model README
This BERT-based model is designed for slot filling tasks in natural language sentences, ideal for extracting specific information in applications like chatbots and virtual assistants.
For example: input: Transfer $500 from checking to student savings output: transfer [$500:B-amount] from [checking:B-account-from] to [student:B-account-to] [savings:I-account-to]
The model was trained with dataset https://github.com/SunLemuria/JointBERT-Tensorflow1/blob/master/data/
Please make yourself familiar with BERT: BERT for Joint Intent Classification and Slot Filling https://arxiv.org/pdf/1902.10909.pdf
!pip install torch transformers
import os
import requests
import torch
from transformers import BertForTokenClassification, BertTokenizerFast
# URL y archivo para los slots
slots_url = 'https://huggingface.co/andgonzalez/bert-uncased-slot-filling/raw/main/slots.txt'
slots_file = 'slots.txt'
device = "cpu"
# Descargar y guardar los slots si no existen
if not os.path.exists(slots_file):
response = requests.get(slots_url)
response.raise_for_status()
with open(slots_file, 'w') as file:
file.write(response.text)
# Leer los slots
with open(slots_file, 'r') as file:
slot_labels = file.read().splitlines()
# Cargar el tokenizador y el modelo
tokenizer = BertTokenizerFast.from_pretrained('andgonzalez/bert-uncased-slot-filling')
model = BertForTokenClassification.from_pretrained('andgonzalez/bert-uncased-slot-filling')
# Ejemplo
sentence = "Transfer $500 from checking to student savings"
inputs = tokenizer(sentence, truncation=True, padding='max_length', max_length=20, return_tensors="pt")
inputs = {k: v.to(device) for k, v in inputs.items()}
with torch.no_grad():
model.eval()
outputs = model(**inputs)
# Procesar los logits para obtener predicciones
logits = outputs.logits
predictions = torch.argmax(logits, dim=2).squeeze().cpu().numpy()
words = tokenizer.convert_ids_to_tokens(inputs["input_ids"].squeeze().cpu().numpy())
# Inicializar skip_next
skip_next = False
# Formatear la oracion
formatted_sentence = []
for i, (word, pred) in enumerate(zip(words, predictions)):
if word not in ['[PAD]', '[SEP]', '[CLS]']:
label = slot_labels[pred]
if word == "$" and i + 1 < len(words) and words[i + 1].replace("##", "").isdigit():
next_word = words[i + 1].replace("##", "")
combined_word = word + next_word
formatted_word = f'[{combined_word}:{label}]'
formatted_sentence.append(formatted_word)
skip_next = True
elif skip_next:
skip_next = False
continue
elif not word.startswith("##"):
if label != 'O':
formatted_word = f'[{word}:{label}]'
else:
formatted_word = word
formatted_sentence.append(formatted_word)
formatted_sentence = ' '.join(formatted_sentence)
print(formatted_sentence)
