/ Модель

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

Контекст
514 токенов
Параметры
659 млн
Лицензия
BigScience OpenRAIL-M
Архитектура
xlm-roberta · dense
Опубликована
22 сен 2023

manifestoberta-xlm-roberta-56policy-topics-context-2023-1-1

Классификация текстаТекст → label3 профессии

Контекстная мультиязычная модель Manifesto Project классифицирует высказывания по 56 политическим темам схемы кодирования Manifesto Project.

178скачиваний за 30 дней14лайковвеса обновлены17 ноя 2023

Бенчмарки

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

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

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

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

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

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

Это контекстная модель XLM-RoBERTa, разработанная Manifesto Project и дообученная на примерно 1,6 млн размеченных высказываний из Manifesto Corpus версии 2023a. Она относит текст к одной из 56 политических тем по схеме кодирования Manifesto Project, описанной в Handbook 4. Модель имеет около 658,7 млн параметров, использует архитектуру XLM-RoBERTa для классификации последовательностей и принимает текст высказывания вместе с окружающим контекстом; для контекста при обучении использовалось до 200 токенов. Максимальная длина контекста модели — 514 токенов.

Контекстный вариант предназначен для классификации неоднозначных высказываний в политических манифестах: добавление окружающих предложений улучшило точность примерно на 7 процентных пунктов по сравнению с вариантом без контекста. Модель поддерживает языки предобучения XLM-RoBERTa, а лучше всего работает на 38 языках, представленных в Manifesto Corpus. На тестовом наборе из 199 046 высказываний контекстный вариант показал точность 0,64 и macro-F1 0,53. Для загрузки полной модели в Transformers требуется trust_remote_code=True. Лицензия — BigScience OpenRAIL-M.

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

  • классификация высказываний из политических манифестов по темам
  • анализ политических программ на нескольких языках
  • разметка политических текстов по схеме Manifesto Project
  • исследование распределения тем в предвыборных программах

Ограничения

Лучшие результаты ожидаются на 38 языках Manifesto Corpus; для остальных языков предобучения XLM-RoBERTa качество может быть ниже. На тестовом наборе точность составила 0,64, а macro-F1 — 0,53, поэтому предсказания могут быть ошибочными.

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

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

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

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

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

Открыть на Hugging Face

Model description

An xlm-roberta-large model fine-tuned on ~1,6 million annotated statements contained in the Manifesto Corpus (version 2023a). The model can be used to categorize any type of text into 56 different political topics according to the Manifesto Project's coding scheme (Handbook 4). It works for all languages the xlm-roberta model is pretrained on (overview), just note that it will perform best for the 38 languages contained in the Manifesto Corpus:

armenianbosnianbulgariancatalancroatian
czechdanishdutchenglishestonian
finnishfrenchgaliciangeorgiangerman
greekhebrewhungarianicelandicitalian
japanesekoreanlatvianlithuanianmacedonian
montenegrinnorwegianpolishportugueseromanian
russianserbianslovakslovenianspanish
swedishturkishukrainian

The context model variant additionally incorporates the surrounding sentences of a statement to improve the classification results for ambiguous sentences. (See Training Procedure for details)

Important

We slightly modified the Classification Head of the XLMRobertaModelForSequenceClassification model (removed the tanh activation and the intermediate linear layer) as that improved the model performance for this task considerably. To correctly load the full model, include the trust_remote_code=True argument when using the from_pretrained method.

How to use

import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer

model = AutoModelForSequenceClassification.from_pretrained("manifesto-project/manifestoberta-xlm-roberta-56policy-topics-context-2023-1-1", trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained("xlm-roberta-large")

sentence = "These principles are under threat."
context = "Human rights and international humanitarian law are fundamental pillars of a secure global system. These principles are under threat. Some of the world's most powerful states choose to sell arms to human-rights abusing states."
# For sentences without additional context, just use the sentence itself as the context.
# Example: context = "These principles are under threat."


inputs = tokenizer(sentence,
                   context,
                   return_tensors="pt",
                   max_length=300,  #we limited the input to 300 tokens during finetuning
                   padding="max_length",
                   truncation=True
                   )

logits = model(**inputs).logits

probabilities = torch.softmax(logits, dim=1).tolist()[0]
probabilities = {model.config.id2label[index]: round(probability * 100, 2) for index, probability in enumerate(probabilities)}
probabilities = dict(sorted(probabilities.items(), key=lambda item: item[1], reverse=True))
print(probabilities)
# {'201 - Freedom and Human Rights': 90.76, '107 - Internationalism: Positive': 5.82, '105 - Military: Negative': 0.66...

predicted_class = model.config.id2label[logits.argmax().item()]
print(predicted_class)
# 201 - Freedom and Human Rights

Training Procedure

Training of the model took place on all quasi-sentences of the Manifesto Corpus (version 2023a), minus 10% that were kept out of training for the final test and evaluation results. This results in a training dataset of 1,601,329 quasi-sentences. As our context-including model input poses the threat of data-leakage problems between train and test data, we refrained from randomly splitting quasi-sentences into train and test data. Instead, we randomly split the dataset on the manifesto level, so that 1779 manifestos and all their quasi-sentences were assigned to the train set and 198 to the test set.

As training parameters, we used the following settings: learning rate: 1e-5, weight decay: 0.01, epochs: 1, batch size: 4, gradient accumulation steps: 4 (effective batch size: 16).

Context

To adapt the model to the task of classifying statements in manifestos we made some modifications to the traditional training setup. Given that human annotators in the Manifesto Project are encouraged to use surrounding sentences to interpret ambiguous statements , we combined statements with their context for our model's input. Specifically, we used a sentence-pair input, where the single to-be-classified statement gets followed by the separator token followed by the whole bigger context of length 200 tokens, in which the statement to-be-classified is embedded. Here is an example:

"<s> We must right the wrongs in our democracy, </s> </s> To turn this crisis into a crucible, from which we will forge a stronger, brighter, and more equitable future. We must right the wrongs in our democracy, redress the systemic injustices that have long plagued our society,throw open the doors of opportunity for all Americans and reinvent our institutions at home and our leadership abroad. </s>".

The second part, which contains the context, is greedily filled until it contains 200 tokens. Our tests showed that including the context helped to improve the performance of the classification model considerably (~7% accuracy). We tried other approaches like using two XLM-RoBERTa models as a duo, where one receives the sentence and one the context, and a shared-layer model, where both inputs are fed separately trough the same model. Both variants performed similarly to our sentence pair approach, but lead to higher complexity and computing costs, which is why we ultimately opted for the sentence pair way to include the surrounding context.

Model Performance

The model was evaluated on a test set of 199,046 annotated manifesto statements.

Overall

AccuracyTop2_AccTop3_AccPrecisionRecallF1_MacroMCCCross-Entropy
Sentence Model0.570.730.810.490.430.450.551.5
Context Model0.640.810.880.540.520.530.621.15

Categories

CategoryPrecisionRecallF1n_test(%)n_predicted(%)
1010.500.480.490.30%0.29%
1020.560.610.580.09%0.10%
1030.510.360.420.28%0.20%
1040.780.810.791.57%1.64%
1050.690.700.690.34%0.34%
1060.590.570.580.33%0.32%
1070.680.660.672.24%2.17%
1080.660.680.671.20%1.24%
1090.520.390.450.17%0.13%
1100.630.680.650.36%0.38%
2010.580.590.592.16%2.20%
2020.620.630.623.25%3.28%
2030.460.470.470.19%0.19%
2040.610.370.460.25%0.15%
3010.660.710.682.13%2.29%
3020.380.250.300.17%0.11%
3030.580.600.595.12%5.31%
3040.670.650.661.38%1.34%
3050.590.570.582.32%2.22%
4010.450.360.401.50%1.21%
4020.610.580.592.73%2.60%
4030.560.510.533.59%3.25%
4040.300.150.200.58%0.28%
4050.430.510.470.18%0.21%
4060.380.460.420.26%0.31%
4070.560.520.540.40%0.38%
4080.280.170.211.34%0.79%
4090.370.210.270.24%0.14%
4100.530.500.522.22%2.08%
4110.730.750.748.32%8.53%
4120.260.200.220.58%0.45%
4130.490.630.550.29%0.37%
4140.580.550.561.38%1.32%
4150.140.230.180.05%0.07%
4160.520.490.502.45%2.35%
5010.690.780.734.77%5.35%
5020.780.840.813.08%3.32%
5030.610.630.625.96%6.11%
5040.710.760.7410.05%10.76%
5050.460.370.410.69%0.55%
5060.780.820.805.42%5.72%
5070.450.260.330.14%0.08%
6010.520.460.491.79%1.57%
6020.350.340.340.24%0.24%
6030.650.680.671.36%1.42%
6040.620.480.540.57%0.44%
6050.720.740.734.22%4.33%
6060.560.480.511.45%1.23%
6070.570.670.621.08%1.25%
6080.480.480.480.41%0.41%
7010.620.660.643.35%3.59%
7020.420.300.350.08%0.06%
7030.750.870.802.65%3.07%
7040.430.320.370.57%0.43%
7050.380.330.350.80%0.69%
7060.430.370.391.35%1.16%

Citation

Please cite the model as follows:

Burst, Tobias / Lehmann, Pola / Franzmann, Simon / Al-Gaddooa, Denise / Ivanusch, Christoph / Regel, Sven / Riethmüller, Felicia / Weßels, Bernhard / Zehnter, Lisa (2023): manifestoberta. Version 56topics.context.2023.1.1. Berlin: Wissenschaftszentrum Berlin für Sozialforschung (WZB) / Göttingen: Institut für Demokratieforschung (IfDem). https://doi.org/10.25522/manifesto.manifestoberta.56topics.context.2023.1.1

@misc{Burst:2023,
  Address = {Berlin / Göttingen},
  Author = {Burst, Tobias AND Lehmann, Pola AND Franzmann, Simon AND Al-Gaddooa, Denise AND Ivanusch, Christoph AND Regel, Sven AND Riethmüller, Felicia AND Weßels, Bernhard AND Zehnter, Lisa},
  Publisher = {Wissenschaftszentrum Berlin für Sozialforschung / Göttinger Institut für Demokratieforschung},
  Title = {manifestoberta. Version 56topics.context.2023.1.1},
  doi = {10.25522/manifesto.manifestoberta.56topics.context.2023.1.1},
  url = {https://doi.org/10.25522/manifesto.manifestoberta.56topics.context.2023.1.1},  
  Year = {2023},

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
CustomXLMRobertaModelForSequenceClassification
Ревизия весов
06c0467

0 моделей