/ Модель

Характеристики

Контекст
512 токенов
Параметры
137 млн
Архитектура
bert · dense

scibert_scivocab_cased_ner_jnlpba

Разметка токеновТекст → label3 профессии

Дообученная на наборе JNLPBA модель SciBERT для выделения биомедицинских сущностей в научных текстах.

27скачиваний за 30 дней0лайковвеса обновлены19 мая 2021

Бенчмарки

Как модель справилась с задачами пользователей ailist и что о ней публикуют открытые лидерборды

Публичные оценки

Из открытых лидербордов. Сравнивайте результаты одного теста при одинаковых условиях — отсутствие оценки не значит, что модель хуже.

В подключённых источниках результатов для этой модели пока нет.

Что умеет модель

Описание составлено по карточке модели и метаданным Hugging Face

fran-martinez/scibert_scivocab_cased_ner_jnlpba — модель распознавания именованных сущностей на основе SciBERT, разработанного Allen Institute for AI и дообученного для задачи BioNLP/JNLPBA. SciBERT построен на архитектуре BERT и предварительно обучен на корпусе научных публикаций Semantic Scholar; для него используется специализированный словарь scivocab. Модель содержит 137,1 млн параметров и принимает последовательности длиной до 512 токенов.

Модель размечает слова и фрагменты текста в научных аннотациях, выделяя, в частности, белки, типы клеток и клеточные линии. В описанной оценке на данных JNLPBA она достигла макро F1 0,7498 на уровне сущностей и F1 0,8093 на уровне слов. Для обучения использовались 2 000 аннотаций PubMed; оценка проводилась на 404 аннотациях.

Модель предназначена для извлечения биомедицинских сущностей из научных текстов. В README отмечено, что результаты ниже приведённого показателя исходной работы Allen Institute for AI; одним из возможных объяснений называется отсутствие слоя CRF. Лицензия в предоставленных данных не указана.

Сценарии применения

  • извлечение названий белков из аннотаций PubMed
  • распознавание типов клеток в биомедицинских статьях
  • поиск клеточных линий в научных публикациях
  • автоматическая разметка биомедицинских сущностей в аннотациях

Ограничения

На уровне сущностей макро F1 составляет 0,7498, что ниже указанного в README результата исходной работы Allen Institute for AI (0,7728). README связывает возможное снижение качества с отсутствием слоя CRF; приведённые метрики относятся к оценке на JNLPBA.

Для каких профессий подходит3

Разделы каталога профессий, в задачах которых используется эта модель

Все профессии

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

SciBERT finetuned on JNLPA for NER downstream task

Language Model

SciBERT is a pretrained language model based on BERT and trained by the Allen Institute for AI on papers from the corpus of Semantic Scholar. Corpus size is 1.14M papers, 3.1B tokens. SciBERT has its own vocabulary (scivocab) that's built to best match the training corpus.

Downstream task

allenai/scibert_scivocab_cased has been finetuned for Named Entity Recognition (NER) dowstream task. The code to train the NER can be found here.

Data

The corpus used to fine-tune the NER is BioNLP / JNLPBA shared task.

  • Training data consist of 2,000 PubMed abstracts with term/word annotation. This corresponds to 18,546 samples (senteces).
  • Evaluation data consist of 404 PubMed abstracts with term/word annotation. This corresponds to 3,856 samples (sentences).

The classes (at word level) and its distribution (number of examples for each class) for training and evaluation datasets are shown below:

Class Label# training examples# evaluation examples
O382,96381,647
B-protein30,2695,067
I-protein24,8484,774
B-cell_type6,7181,921
I-cell_type8,7482,991
B-DNA9,5331,056
I-DNA15,7741,789
B-cell_line3,830500
I-cell_line7,3879,89
B-RNA951118
I-RNA1,530187

Model

An exhaustive hyperparameter search was done. The hyperparameters that provided the best results are:

  • Max length sequence: 128
  • Number of epochs: 6
  • Batch size: 32
  • Dropout: 0.3
  • Optimizer: Adam

The used learning rate was 5e-5 with a decreasing linear schedule. A warmup was used at the beggining of the training with a ratio of steps equal to 0.1 from the total training steps.

The model from the epoch with the best F1-score was selected, in this case, the model from epoch 5.

Evaluation

The following table shows the evaluation metrics calculated at span/entity level:

precisionrecallf1-score
cell_line0.52050.71000.6007
cell_type0.77360.74220.7576
protein0.69530.84590.7633
DNA0.69970.78940.7419
RNA0.69850.80510.7480
micro avg0.69840.80760.7490
macro avg0.70320.80760.7498

The macro F1-score is equal to 0.7498, compared to the value provided by the Allen Institute for AI in their paper, which is equal to 0.7728. This drop in performance could be due to several reasons, but one hypothesis could be the fact that the authors used an additional conditional random field, while this model uses a regular classification layer with softmax activation on top of SciBERT model.

At word level, this model achieves a precision of 0.7742, a recall of 0.8536 and a F1-score of 0.8093.

Model usage in inference

Use the pipeline:

from transformers import pipeline

text = "Mouse thymus was used as a source of glucocorticoid receptor from normal CS lymphocytes."

nlp_ner = pipeline("ner",
                   model='fran-martinez/scibert_scivocab_cased_ner_jnlpba',
                   tokenizer='fran-martinez/scibert_scivocab_cased_ner_jnlpba')

nlp_ner(text)

"""
Output:
---------------------------
[
{'word': 'glucocorticoid', 
'score': 0.9894881248474121, 
'entity': 'B-protein'}, 
 
{'word': 'receptor', 
'score': 0.989505410194397, 
'entity': 'I-protein'}, 

{'word': 'normal', 
'score': 0.7680378556251526, 
'entity': 'B-cell_type'}, 

{'word': 'cs', 
'score': 0.5176806449890137, 
'entity': 'I-cell_type'}, 

{'word': 'lymphocytes', 
'score': 0.9898491501808167, 
'entity': 'I-cell_type'}
]
"""

Or load model and tokenizer as follows:

import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification

# Example
text = "Mouse thymus was used as a source of glucocorticoid receptor from normal CS lymphocytes."

# Load model
tokenizer = AutoTokenizer.from_pretrained("fran-martinez/scibert_scivocab_cased_ner_jnlpba")
model = AutoModelForTokenClassification.from_pretrained("fran-martinez/scibert_scivocab_cased_ner_jnlpba")

# Get input for BERT
input_ids = torch.tensor(tokenizer.encode(text)).unsqueeze(0)

# Predict
with torch.no_grad():
  outputs = model(input_ids)

# From the output let's take the first element of the tuple.
# Then, let's get rid of [CLS] and [SEP] tokens (first and last)
predictions = outputs[0].argmax(axis=-1)[0][1:-1]

# Map label class indexes to string labels.
for token, pred in zip(tokenizer.tokenize(text), predictions):
  print(token, '->', model.config.id2label[pred.numpy().item()])

"""
Output:
---------------------------
mouse -> O
thymus -> O
was -> O
used -> O
as -> O
a -> O
source -> O
of -> O
glucocorticoid -> B-protein
receptor -> I-protein
from -> O
normal -> B-cell_type
cs -> I-cell_type
lymphocytes -> I-cell_type
. -> O
"""

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · token-classification

Можно запустить

Подбираем GPU…

Класс архитектуры
BertForTokenClassification
Ревизия весов
1904782

0 моделей