To parse the RoBERTa NER (Named Entity Recognition) tokens and reconstruct full entities for each input element, you can follow a systematic approach. Below is a comprehensive guide, including a Python function that accomplishes this task.
Understanding the Data Structure
Your input data consists of a list of lists, where each sublist corresponds to an input text element and contains dictionaries representing the tokens identified by the RoBERTa model. Each token dictionary has the following keys:
entity: The type of entity (e.g., I-ORG, I-PER).
word: The token string, which may include the special character ▁ indicating the start of a new word (common in Byte-Pair Encoding (BPE) tokenizers like SentencePiece).
start and end: Character indices indicating the token's position in the original text.
score: Confidence score of the prediction.
Objective
The goal is to:
- Merge Subtokens into Full Entities: Combine tokens that belong to the same entity into complete words or phrases.
- Handle Word Boundaries: Use the
▁ character to determine when a new word starts.
- Organize Entities by Their Types: Group entities based on their types (e.g.,
ORG, PER, LOC, MISC).
Step-by-Step Solution
- Iterate Through Each Input Element: Process each sublist corresponding to an input text.
- Sort Tokens by Their Position: Ensure tokens are processed in the order they appear in the text.
- Group Tokens into Entities:
- Start a new group when encountering a token with a different entity type or a non-sequential position.
- Concatenate tokens to form complete entity names, respecting word boundaries.
- Clean and Combine Words:
- Remove the special
▁ character.
- Concatenate tokens appropriately (with spaces if they start new words).
Python Implementation
Here's a Python function that implements the above logic:
import re
def parse_roberta_entities(entities_list):
"""
Parses RoBERTa NER token outputs to reconstruct full entities.
Args:
entities_list (list): A list where each element is a list of token dictionaries for an input text.
Returns:
list: A list where each element is a list of reconstructed entities (as dictionaries with 'entity' and 'word').
"""
parsed_entities_per_input = []
for input_idx, token_list in enumerate(entities_list):
parsed_entities = []
current_entity = None # To hold the ongoing entity
current_words = []
current_entity_type = None
current_end = -1 # To track the end index of the current entity
# Sort tokens by their start index to ensure correct order
sorted_tokens = sorted(token_list, key=lambda x: x['start'])
for token in sorted_tokens:
entity_type = token['entity']
word = token['word']
start = token['start']
end = token['end']
# Determine if this token should start a new entity
if (current_entity_type != entity_type) or (start != current_end):
# If there's an ongoing entity, save it
if current_entity_type is not None and current_words:
full_entity = ''.join(current_words)
parsed_entities.append({'entity': current_entity_type, 'word': full_entity})
# Start a new entity
current_entity_type = entity_type
current_words = []
# Handle word boundaries
if word.startswith('▁'):
# If it's a new word, add a space if it's not the first word in the entity
clean_word = word.lstrip('▁')
if current_words:
current_words.append(' ')
current_words.append(clean_word)
else:
# Continuation of the previous word
current_words.append(word)
# Update the end index for the current entity
current_end = end
# After processing all tokens, save any remaining entity
if current_entity_type is not None and current_words:
full_entity = ''.join(current_words)
parsed_entities.append({'entity': current_entity_type, 'word': full_entity})
parsed_entities_per_input.append(parsed_entities)
return parsed_entities_per_input
# Example Usage
if __name__ == "__main__":
import numpy as np
# Example input data (abbreviated for brevity)
entities = [
[
{'end': 55, 'entity': 'I-ORG', 'index': 13, 'score': np.float32(0.9890971), 'start': 52, 'word': '▁Tax'},
{'end': 59, 'entity': 'I-ORG', 'index': 14, 'score': np.float32(0.9822499), 'start': 55, 'word': 'down'}
],
# ... (other input elements)
]
parsed = parse_roberta_entities(entities)
for idx, entities in enumerate(parsed):
print(f"Input {idx + 1}:")
for entity in entities:
print(f" - {entity['entity']}: {entity['word']}")
print()
Explanation of the Function
-
Initialization:
parsed_entities_per_input: List to store parsed entities for each input element.
current_entity, current_words, current_entity_type, current_end: Variables to track the ongoing entity.
-
Processing Each Input Element:
- Sorting Tokens: Ensure tokens are processed in their original order based on the
start index.
- Iterating Through Tokens:
- Starting a New Entity: If the current token's entity type differs from
current_entity_type or its start index doesn't match current_end, it's considered the start of a new entity.
- Handling Word Boundaries:
- If the token starts with
▁, it signifies a new word. A space is added before the word unless it's the first word in the entity.
- If not, the token is a continuation of the previous word without an added space.
- Updating Entity Tracking:
current_end is updated to the token's end index to maintain continuity.
-
Finalizing Entities:
- After all tokens are processed, any remaining entity is added to the
parsed_entities list.
-
Output Structure:
- The function returns a list where each element corresponds to an input text and contains a list of entities with their types and full names.
Example Output
Given the example input:
[
[
{'end': 55, 'entity': 'I-ORG', 'index': 13, 'score': np.float32(0.9890971), 'start': 52, 'word': '▁Tax'},
{'end': 59, 'entity': 'I-ORG', 'index': 14, 'score': np.float32(0.9822499), 'start': 55, 'word': 'down'}
]
]
The output will be:
Input 1:
- I-ORG: Tax down
Handling Edge Cases
- Single Token Entities: If an entity consists of a single token, it will be processed correctly.
- Multiple Entities of the Same Type: The function differentiates entities based on their start and end positions, allowing multiple entities of the same type within the same input.
- Non-sequential Tokens: Tokens that don't follow sequentially are treated as separate entities, even if they share the same entity type.
Customizations
- Output Formatting: You can modify the function to return entities in different formats, such as tuples (
(entity_type, entity_text)) or include additional information like start and end positions.
- Entity Filtering: To exclude certain entity types or filter based on confidence scores, incorporate conditional checks within the token processing loop.
Conclusion
By following the above approach, you can effectively parse RoBERTa NER token outputs to reconstruct full entities per input element. This method ensures that subtokens are accurately combined, word boundaries are respected, and entities are organized by their respective types.