/ Модель

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

Контекст
256 токенов
Лицензия
CC BY-NC-SA 4.0
Архитектура
span-marker · dense
Базовая модель
bert-base-multilingual-uncased
Опубликована
14 авг 2023

span-marker-bert-base-multilingual-uncased-multinerd

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

Многоязычная модель SpanMarker для распознавания людей, организаций и местоположений в тексте на десяти языках.

19скачиваний за 30 дней16лайковвеса обновлены21 дек 2023

Бенчмарки

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

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

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

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

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

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

Модель lxyuan/span-marker-bert-base-multilingual-uncased-multinerd — дообученная версия bert-base-multilingual-uncased с архитектурой SpanMarker, созданная в рамках воспроизведения работы Tom. Она предназначена для распознавания именованных сущностей в тексте: людей, организаций и местоположений.

Модель обучена на наборе Babelscape/multinerd и поддерживает немецкий, английский, испанский, французский, итальянский, нидерландский, польский, португальский, русский и китайский языки. В карточке приведён общий F1 91,88 на тестовой выборке; автор отмечает, что вариант без учёта регистра может уступать варианту с учётом регистра, поэтому рекомендует сравнивать их на целевых данных.

Модель распространяется по лицензии CC BY-NC-SA 4.0, которая ограничивает коммерческое использование. Результаты могут зависеть от языка и предметной области; README также отмечает чувствительность к точкам в контексте распознавания сущностей, связанных с едой.

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

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

Ограничения

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

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

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

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

Также подходит для

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

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

Открыть на Hugging Face

span-marker-bert-base-multilingual-uncased-multinerd

This model is a fine-tuned version of bert-base-multilingual-uncased on an Babelscape/multinerd dataset.

Is your data always capitalized correctly? Then consider using the cased variant of this model instead for better performance: lxyuan/span-marker-bert-base-multilingual-cased-multinerd.

This model achieves the following results on the evaluation set:

  • Loss: 0.0054
  • Overall Precision: 0.9275
  • Overall Recall: 0.9147
  • Overall F1: 0.9210
  • Overall Accuracy: 0.9842

Test set results:

  • test_loss: 0.0058621917851269245,
  • test_overall_accuracy: 0.9831472809849865,
  • test_overall_f1: 0.9187844693592546,
  • test_overall_precision: 0.9202802342397876,
  • test_overall_recall: 0.9172935588307115,
  • test_runtime: 2716.7472,
  • test_samples_per_second: 149.141,
  • test_steps_per_second: 4.661,

Note: This is a replication of Tom's work. In this work, we used slightly different hyperparameters: epochs=3 and gradient_accumulation_steps=2. We also switched to the uncased bert model to see if an uncased encoder model would perform better for commonly lowercased entities like, such as food. Please check the discussion here. Refer to the official model page to review their results and training script.

Results:

LanguagePrecisionRecallF1
all92.0391.7391.88
de94.9694.8794.91
en93.6993.7593.72
es91.1990.6990.94
fr91.3690.7491.05
it90.5192.5791.53
nl93.2392.1392.67
pl92.1791.5991.88
pt92.7091.5992.14
ru92.3192.3692.34
zh88.9187.5388.22

Below is a combined table that compares the results of the cased and uncased models for each language:

LanguageMetricCasedUncased
allPrecision92.4292.03
Recall92.8191.73
F192.6191.88
dePrecision95.0394.96
Recall95.0794.87
F195.0594.91
enPrecision95.0093.69
Recall95.4093.75
F195.2093.72
esPrecision92.0591.19
Recall91.3790.69
F191.7190.94
frPrecision92.3791.36
Recall91.4190.74
F191.8991.05
itPrecision91.4590.51
Recall93.1592.57
F192.2991.53
nlPrecision93.8593.23
Recall92.9892.13
F193.4192.67
plPrecision93.1392.17
Recall92.6691.59
F192.8991.88
ptPrecision93.6092.70
Recall92.5091.59
F193.0592.14
ruPrecision93.2592.31
Recall93.3292.36
F193.2992.34
zhPrecision89.4788.91
Recall88.4087.53
F188.9388.22

Short discussion: Upon examining the results, one might conclude that the cased version of the model is better than the uncased version, as it outperforms the latter across all languages. However, I recommend that users test both models on their specific datasets (or domains) to determine which one actually delivers better performance. My reasoning for this suggestion stems from a brief comparison I conducted on the FOOD (food) entities. I found that both cased and uncased models are sensitive to the full stop punctuation mark. We direct readers to the section: Quick Comparison on FOOD Entities.

Label set

ClassDescriptionExamples
PER (person)PeopleRay Charles, Jessica Alba, Leonardo DiCaprio, Roger Federer, Anna Massey.
ORG (organization)Associations, companies, agencies, institutions, nationalities and religious or political groupsUniversity of Edinburgh, San Francisco Giants, Google, Democratic Party.
LOC (location)Physical locations (e.g. mountains, bodies of water), geopolitical entities (e.g. cities, states), and facilities (e.g. bridges, buildings, airports).Rome, Lake Paiku, Chrysler Building, Mount Rushmore, Mississippi River.
ANIM (animal)Breeds of dogs, cats and other animals, including their scientific names.Maine Coon, African Wild Dog, Great White Shark, New Zealand Bellbird.
BIO (biological)Genus of fungus, bacteria and protoctists, families of viruses, and other biological entities.Herpes Simplex Virus, Escherichia Coli, Salmonella, Bacillus Anthracis.
CEL (celestial)Planets, stars, asteroids, comets, nebulae, galaxies and other astronomical objects.Sun, Neptune, Asteroid 187 Lamberta, Proxima Centauri, V838 Monocerotis.
DIS (disease)Physical, mental, infectious, non-infectious, deficiency, inherited, degenerative, social and self-inflicted diseases.Alzheimer’s Disease, Cystic Fibrosis, Dilated Cardiomyopathy, Arthritis.
EVE (event)Sport events, battles, wars and other events.American Civil War, 2003 Wimbledon Championships, Cannes Film Festival.
FOOD (food)Foods and drinks.Carbonara, Sangiovese, Cheddar Beer Fondue, Pizza Margherita.
INST (instrument)Technological instruments, mechanical instruments, musical instruments, and other tools.Spitzer Space Telescope, Commodore 64, Skype, Apple Watch, Fender Stratocaster.
MEDIA (media)Titles of films, books, magazines, songs and albums, fictional characters and languages.Forbes, American Psycho, Kiss Me Once, Twin Peaks, Disney Adventures.
PLANT (plant)Types of trees, flowers, and other plants, including their scientific names.Salix, Quercus Petraea, Douglas Fir, Forsythia, Artemisia Maritima.
MYTH (mythological)Mythological and religious entities.Apollo, Persephone, Aphrodite, Saint Peter, Pope Gregory I, Hercules.
TIME (time)Specific and well-defined time intervals, such as eras, historical periods, centuries, years and important days. No months and days of the week.Renaissance, Middle Ages, Christmas, Great Depression, 17th Century, 2012.
VEHI (vehicle)Cars, motorcycles and other vehicles.Ferrari Testarossa, Suzuki Jimny, Honda CR-X, Boeing 747, Fairey Fulmar.

Inference Example

# install span_marker
(env)$ pip install span_marker


from span_marker import SpanMarkerModel

model = SpanMarkerModel.from_pretrained("lxyuan/span-marker-bert-base-multilingual-uncased-multinerd")

description = "Singapore is renowned for its hawker centers offering dishes \
like Hainanese chicken rice and laksa, while Malaysia boasts dishes such as \
nasi lemak and rendang, reflecting its rich culinary heritage."

entities = model.predict(description)

entities
>>>
[
  {'span': 'Singapore', 'label': 'LOC', 'score': 0.9999247789382935, 'char_start_index': 0, 'char_end_index': 9},
  {'span': 'laksa', 'label': 'FOOD', 'score': 0.794235348701477, 'char_start_index': 93, 'char_end_index': 98},
  {'span': 'Malaysia', 'label': 'LOC', 'score': 0.9999157190322876, 'char_start_index': 106, 'char_end_index': 114}
]

# missed: Hainanese chicken rice as FOOD
# missed: nasi lemak as FOOD
# missed: rendang as FOOD

# note: Unfortunately, this uncased version still fails to pick up those commonly lowercased food entities and even misses out on the capitalized `Hainanese chicken rice` entity.

Quick test on Chinese

from span_marker import SpanMarkerModel

model = SpanMarkerModel.from_pretrained("lxyuan/span-marker-bert-base-multilingual-uncased-multinerd")

# translate to chinese
description = "Singapore is renowned for its hawker centers offering dishes \
like Hainanese chicken rice and laksa, while Malaysia boasts dishes such as \
nasi lemak and rendang, reflecting its rich culinary heritage."

zh_description = "新加坡因其小贩中心提供海南鸡饭和叻沙等菜肴而闻名, 而马来西亚则拥有椰浆饭和仁当等菜肴,反映了其丰富的烹饪传统."

entities = model.predict(zh_description)

entities
>>>
[
  {'span': '新加坡', 'label': 'LOC', 'score': 0.8477746248245239, 'char_start_index': 0, 'char_end_index': 3},
  {'span': '马来西亚', 'label': 'LOC', 'score': 0.7525337934494019, 'char_start_index': 27, 'char_end_index': 31}
]

# It only managed to capture two countries: Singapore and Malaysia.
# All other entities were missed out.
# Same prediction as the [uncased model](https://huggingface.co/lxyuan/span-marker-bert-base-multilingual-cased-multinerd)

Quick Comparison on FOOD Entities

In this quick comparison, we found that a full stop punctuation mark seems to help the uncased model identify food entities, regardless of whether they are capitalized or in uppercase. In contrast, the cased model doesn't respond well to full stops, and adding them would lower the prediction score.

from span_marker import SpanMarkerModel

cased_model = SpanMarkerModel.from_pretrained("lxyuan/span-marker-bert-base-multilingual-cased-multinerd")
uncased_model = SpanMarkerModel.from_pretrained("lxyuan/span-marker-bert-base-multilingual-uncased-multinerd")

# no full stop mark
uncased_model.predict("i love fried chicken and korea bbq")
>>> []

uncased_model.predict("i love fried chicken and korea BBQ") # Uppercase BBQ only
>>> []

uncased_model.predict("i love fried chicken and Korea BBQ") # Capitalize korea and uppercase BBQ
>>> []

# add full stop to get better result
uncased_model.predict("i love fried chicken and korea bbq.")
>>> [
  {'span': 'fried chicken', 'label': 'FOOD', 'score': 0.6531468629837036, 'char_start_index': 7, 'char_end_index': 20},
  {'span': 'korea bbq', 'label': 'FOOD', 'score': 0.9738698601722717, 'char_start_index': 25,'char_end_index': 34}
]

uncased_model.predict("i love fried chicken and korea BBQ.")
>>> [
  {'span': 'fried chicken', 'label': 'FOOD', 'score': 0.6531468629837036, 'char_start_index': 7, 'char_end_index': 20},
  {'span': 'korea BBQ', 'label': 'FOOD', 'score': 0.9738698601722717, 'char_start_index': 25, 'char_end_index': 34}
]

uncased_model.predict("i love fried chicken and Korea BBQ.")
>>> [
  {'span': 'fried chicken', 'label': 'FOOD', 'score': 0.6531468629837036, 'char_start_index': 7, 'char_end_index': 20},
  {'span': 'Korea BBQ', 'label': 'FOOD', 'score': 0.9738698601722717, 'char_start_index': 25, 'char_end_index': 34}
]



# no full stop mark
cased_model.predict("i love fried chicken and korea bbq")
>>> [
  {'span': 'korea bbq', 'label': 'FOOD', 'score': 0.5054221749305725, 'char_start_index': 25, 'char_end_index': 34}
]

cased_model.predict("i love fried chicken and korea BBQ")
>>> [
  {'span': 'korea BBQ', 'label': 'FOOD', 'score': 0.6987857222557068, 'char_start_index': 25, 'char_end_index': 34}
]

cased_model.predict("i love fried chicken and Korea BBQ")
>>> [
  {'span': 'Korea BBQ', 'label': 'FOOD', 'score': 0.9755308032035828, 'char_start_index': 25, 'char_end_index': 34}
]

# add a fullstop mark hurt the cased model prediction score a little bit
cased_model.predict("i love fried chicken and korea bbq.")
>>> []

cased_model.predict("i love fried chicken and korea BBQ.")
>>> [
  {'span': 'korea BBQ', 'label': 'FOOD', 'score': 0.5078140497207642, 'char_start_index': 25, 'char_end_index': 34}
]

cased_model.predict("i love fried chicken and Korea BBQ.")
>>> [
  {'span': 'Korea BBQ', 'label': 'FOOD', 'score': 0.895089328289032, 'char_start_index': 25, 'char_end_index': 34}
]

Training procedure

One can reproduce the result running this script

Training hyperparameters

The following hyperparameters were used during training:

  • learning_rate: 5e-05
  • train_batch_size: 32
  • eval_batch_size: 32
  • seed: 42
  • gradient_accumulation_steps: 2
  • total_train_batch_size: 64
  • optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
  • lr_scheduler_type: linear
  • lr_scheduler_warmup_ratio: 0.1
  • num_epochs: 3

Training results

Training LossEpochStepValidation LossOverall PrecisionOverall RecallOverall F1Overall Accuracy
0.01571.0503690.00480.91430.89860.90640.9807
0.0032.01007380.00470.92370.91260.91810.9835
0.00173.01511070.00540.92750.91470.92100.9842

Framework versions

  • Transformers 4.30.2
  • Pytorch 2.0.1+cu117
  • Datasets 2.14.3
  • Tokenizers 0.13.3

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

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

GPU в ailist

Универсальный рантайм

Нельзя запустить

Модели SpanMarker требуют отдельного рантайма.

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

0 моделей