GithubHelp home page GithubHelp logo

guoqiangjia / instruct-ner Goto Github PK

View Code? Open in Web Editor NEW

This project forked from poteminr/instruct-ner

0.0 0.0 0.0 176 KB

Instruct LLMs for flat and nested NER. Fine-tuning Llama and Mistral models for instruction named entity recognition. (Instruction NER)

License: Apache License 2.0

Python 100.00%

instruct-ner's Introduction

image

Instruct NER

Solution of complex Named Entity Recognition tasks (and subtask Nested NER) based on modern Large Language Models (LLMs).

Table of contents

Insturct Dataset

You should form python dictionaries for every text and labels. Let's look at an simplified example from Russian Drug Reaction Corpus (RuDReC).

  • Input text: Это старый-добрый Римантадин, только в сиропе.
  • Labels: Римантадин - Drugname, сиропе - Drugform

1. Create Instruction - task description for LLM

Russian:

Ты решаешь задачу NER. Извлеки из текста слова, относящиеся к каждой из следующих сущностей: Drugname, Drugclass, DI, ADR, Finding.

English:

You are solving the NER problem. Extract from the text words related to each of the following entities: Drugname, Drugclass, DI, ADR, Finding.

2. Build dictionary with labels.

You can use one of two supported version.

With all entity types (hard to compute with large tagset)

raw_entities = {
    'Drugname': ['Римантадин'],
    'Drugclass': [],
    'Drugform': ['сиропе'],
    'DI': [],
    'ADR': [],
    'Finding': []
}

Only with mentioned entities (better for large tagset)

short_form_output=True (available with Nerel-BIO and MultiCoNER)
raw_entities = {
    'Drugname': ['Римантадин'],
    'Drugform': ['сиропе']
}

3. Create MODEL_INPUT_TEMPLATE.

MODEL_INPUT_TEMPLATE = {
'prompts_input': "### Задание: {instruction}\n### Вход: {inp}\n### Ответ: ",
'output_separator': "Ответ: "
}

Or english version

MODEL_INPUT_TEMPLATE = {
'prompts_input': "### Task: {instruction}\n### Input: {inp}\n### Answer: ",
'output_separator': "Answer: "
}

Automatically generate Instruction

instruction_ner/utils/instruct_dataset.py

class Instruction(TypedDict):
    instruction: str
    input: str
    output: str
    source: str   
    raw_entities: dict[str, list[str]]
    id: str

Example

{'instruction': 'Ты решаешь задачу NER. Извлеки из текста слова, относящиеся к каждой из следующих сущностей: Drugname, Drugclass, DI, ADR, Finding.',
 'input': 'Это старый-добрый Римантадин, только в сиропе.\n',
 'output': 'Drugname: Римантадин\nDrugclass: \nDrugform: сиропе\nDI: \nADR: \nFinding: \n',
 'source': '### Задание: Ты решаешь задачу NER. Извлеки из текста слова, относящиеся к каждой из следующих сущностей: Drugname, Drugclass, DI, ADR, Finding.\n### Вход: Это старый-добрый Римантадин, только в сиропе.\n### Ответ: ',
 'raw_entities': {'Drugname': ['Римантадин'],
  'Drugclass': [],
  'Drugform': ['сиропе'],
  'DI': [],
  'ADR': [],
  'Finding': []},
 'id': '1_2555494.tsv'}

Implemented datasets

instruction_ner/utils/

  1. Russian Drug Reaction Corpus (RuDReC)
  2. NEREL-BIO (Nested Named Entities)
  3. CoNLL-2003
  4. MultiCoNER II (2023) (HF, fine and coarse level mapping of the tags)

Automatic calculation of metrics

instruction_ner/metric.py

You can use the implemented functions with the output of inference_instruct calculate metrics.

import pandas as pd
from utils.rudrec.rudrec_utis import ENTITY_TYPES
from metric import calculate_metrics_from_dataframe

prediction = pd.read_json('prediction.json')
prediction.head(3)
id extracted target
0 8_1443820.tsv {'Drugname': [], 'Drugclass': [], 'Drugform': ['таблетки'], 'DI': [], 'ADR': [], 'Finding': []} {'Drugname': [], 'Drugclass': [], 'Drugform': ['таблетки'], 'DI': [], 'ADR': [], 'Finding': []}
1 1_2555494.tsv {'Drugname': ['Римантадин'], 'Drugclass': [], 'Drugform': ['сиропе'], 'DI': [], 'ADR': [], 'Finding': []} {'Drugname': ['Римантадин'], 'Drugclass': [], 'Drugform': ['сиропе'], 'DI': [], 'ADR': [], 'Finding': []}
2 1_618967.tsv {'Drugname': [], 'Drugclass': [], 'Drugform': [], 'DI': [], 'ADR': [], 'Finding': []} {'Drugname': [], 'Drugclass': [], 'Drugform': [], 'DI': [], 'ADR': [], 'Finding': []}
from metric import calculate_metrics_from_dataframe
metrics = calculate_metrics_from_dataframe(prediction, ENTITY_TYPES)
{'Drugname': {'precision': 0.9670250896057347,
  'recall': 0.9195637355146558,
  'f1': 0.9426974143955277}, ...}

Results

Tables with metrics for implemented datasets (link)

Restrictions

Instruction LLM for NER performs well on flat entities, but performs poorly on datasets with large tagset and nested entites. It's hard to output all entities in a single response due to performance limitations.

Thus, LLM and encoder model produce comparable results on flat-ner datasets with incredibly different training and inference times.

Models

and other models on HF such as T5 Llama: poteminr

instruct-ner's People

Contributors

poteminr avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.