/ Модель

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

Контекст
514 токенов
Параметры
454 млн
Лицензия
MIT
Архитектура
roberta · dense
Базовая модель
ruRoberta-large
Библиотека
transformers
Опубликована
19 авг 2024

ruRoberta-large-ru-go-emotions

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

Русская модель RoBERTa для многометочной классификации текста по 27 типам эмоций.

5 130скачиваний за 30 дней5лайковвеса обновлены20 фев 2025

Бенчмарки

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

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

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

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

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

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

Это русскоязычная модель fyaronskiy на базе ruRoberta-large от ai-forever, дообученная для многометочной классификации эмоций по тексту. Она распознаёт 27 типов эмоций и позволяет извлекать несколько эмоций из одного текста или проверять наличие выбранных эмоций.

Модель основана на архитектуре RoBERTa, содержит 454,1 млн параметров и принимает текст с контекстом до 514 токенов. Для запуска доступны веса safetensors и ONNX, включая вариант ONNX с квантизацией INT8; автор сообщает о более быстром выводе при почти сохранённом качестве у квантизированной версии.

Качество зависит от класса эмоций: на тестах лучше распознавались, например, восхищение, веселье и благодарность, а для некоторых менее представленных классов, включая горе и облегчение, результаты слабее. Модель распространяется по лицензии MIT.

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

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

Ограничения

Качество заметно различается между классами: эмоции с малым числом примеров, включая горе и облегчение, распознаются хуже. Результаты зависят от порогов классификации, настроенных на валидационной выборке.

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

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

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

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

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

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

Открыть на Hugging Face

This is the best russian opensource model for detecting all 27 types of emotions:

ModelF1 macroF1 macro weightedPrecision macroRecall macroSize
seara/rubert-tiny2-ru-go-emotions0.330.480.510.2929.2M
seara/rubert-base-cased-ru-go-emotions0.360.490.520.31178M
fyaronskiy/ruRoberta-large-ru-go-emotions default thresholds = 0.50.410.520.580.36355M
fyaronskiy/ruRoberta-large-ru-go-emotions best thresholds0.480.580.460.55355M
fyaronskiy/deberta-v1-base-russian-go-emotions0.480.570.460.54125M

Summary

This is ruRoberta-large model finetuned on ru_go_emotions dataset for multilabel classification. Model can be used to extract all emotions from text or detect certain emotions. Thresholds are selected on validation set by maximizing f1 macro over all labels.

The quality of the model varies greatly across all classes (look at the table with metrics below). There are classes like amusement, gratitude, where the model shows high recognition quality, and classes that pose difficulties for the model - grief, relief, that do have much fewer examples in the training data.

Also ONNX version of model and INT8 quantized model is available. information about them is posted in the last sections.

Usage

Using model with Huggingface Transformers:

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
tokenizer = AutoTokenizer.from_pretrained("fyaronskiy/ruRoberta-large-ru-go-emotions")
model = AutoModelForSequenceClassification.from_pretrained("fyaronskiy/ruRoberta-large-ru-go-emotions")

best_thresholds = [0.36734693877551017, 0.2857142857142857, 0.2857142857142857, 0.16326530612244897, 0.14285714285714285, 0.14285714285714285, 0.18367346938775508, 0.3469387755102041, 0.32653061224489793, 0.22448979591836732, 0.2040816326530612, 0.2857142857142857, 0.18367346938775508, 0.2857142857142857, 0.24489795918367346, 0.7142857142857142, 0.02040816326530612, 0.3061224489795918, 0.44897959183673464, 0.061224489795918366, 0.18367346938775508, 0.04081632653061224, 0.08163265306122448, 0.1020408163265306, 0.22448979591836732, 0.3877551020408163, 0.3469387755102041, 0.24489795918367346]
LABELS = ['admiration', 'amusement', 'anger', 'annoyance', 'approval', 'caring', 'confusion', 'curiosity', 'desire', 'disappointment', 'disapproval', 'disgust', 'embarrassment', 'excitement', 'fear', 'gratitude', 'grief', 'joy', 'love', 'nervousness', 'optimism', 'pride', 'realization', 'relief', 'remorse', 'sadness', 'surprise', 'neutral']
ID2LABEL = dict(enumerate(LABELS))

Here is how you can extract emotions contained in text:

def predict_emotions(text):
  inputs = tokenizer(text, truncation=True, add_special_tokens=True, max_length=128, return_tensors='pt')
  with torch.no_grad():
      logits = model(**inputs).logits
  probas = torch.sigmoid(logits).squeeze(dim=0)  
  class_binary_labels = (probas > torch.tensor(best_thresholds)).int()
  return [ID2LABEL[label_id] for label_id, value in enumerate(class_binary_labels) if value == 1]

print(predict_emotions('У вас отличный сервис и лучший кофе в городе, обожаю вашу кофейню!'))

#['admiration', 'love']

This is the way to get all emotions and their scores:

def predict(text):
    inputs = tokenizer(text, truncation=True, add_special_tokens=True, max_length=128, return_tensors='pt')
    with torch.no_grad():
        logits = model(**inputs).logits
    probas = torch.sigmoid(logits).squeeze(dim=0).tolist()
    probas = [round(proba, 3) for proba in probas]    
    
    labels2probas = dict(zip(LABELS, probas))
    probas_dict_sorted = dict(sorted(labels2probas.items(), key=lambda x: x[1], reverse=True))
    return probas_dict_sorted

print(predict('У вас отличный сервис и лучший кофе в городе, обожаю вашу кофейню!'))
'''{'admiration': 0.81,
 'love': 0.538,
 'joy': 0.041,
 'gratitude': 0.031,
 'approval': 0.026,
 'excitement': 0.023,
 'neutral': 0.009,
 'curiosity': 0.006,
 'amusement': 0.005,
 'desire': 0.005,
 'realization': 0.005,
 'caring': 0.004,
 'confusion': 0.004,
 'surprise': 0.004,
 'disappointment': 0.003,
 'disapproval': 0.003,
 'anger': 0.002,
 'annoyance': 0.002,
 'disgust': 0.002,
 'fear': 0.002,
 'grief': 0.002,
 'optimism': 0.002,
 'pride': 0.002,
 'relief': 0.002,
 'sadness': 0.002,
 'embarrassment': 0.001,
 'nervousness': 0.001,
 'remorse': 0.001}
'''

Eval results on test split of ru-go-emotions

precisionrecallf1-scoresupportthreshold
admiration0.630.750.695040.37
amusement0.760.910.832640.29
anger0.470.320.381980.29
annoyance0.330.390.363200.16
approval0.270.580.373510.14
caring0.320.590.411350.14
confusion0.410.520.461530.18
curiosity0.450.730.552840.35
desire0.540.310.40830.33
disappointment0.310.340.331510.22
disapproval0.310.570.402670.20
disgust0.440.400.421230.29
embarrassment0.480.380.42370.18
excitement0.290.430.341030.29
fear0.560.780.65780.24
gratitude0.950.850.893520.71
grief0.030.330.0560.02
joy0.480.580.531610.31
love0.730.840.782380.45
nervousness0.240.480.32230.06
optimism0.570.540.561860.18
pride0.670.380.48160.04
realization0.180.310.231450.08
relief0.300.270.29110.10
remorse0.530.840.65560.22
sadness0.560.530.551560.39
surprise0.550.570.561410.35
neutral0.590.790.6817870.24
micro avg0.500.660.576329
macro avg0.460.550.486329
weighted avg0.530.660.586329

ONNX and quantized versions of model

Full precision ONNX model (onnx/model.onnx) - 1.5x faster than Transformer model, quality is the same.

INT8 quantized model (onnx/model_quantized.onnx) - 2.5x faster than Transformer model, quality is almost the same.

In table below results of tests of inference of 5427 samples of test_set. I tested inference with batch_size 1 on Intel Xeon CPU with 2 vCPUs (Google Colab).

ModelSizef1 macroaccelerationTime of inference
Original model1.4 GB0.481x44 min 55 sec
onnx.model1.4 GB0.481.5x29 min 52 sec
model_quantized.onnx0.36 GB0.482.5x18 min 10 sec

How to use ONNX versions

Loading full precision model

from optimum.onnxruntime import ORTModelForSequenceClassification
model_id = "fyaronskiy/ruRoberta-large-ru-go-emotions"
file_name = "onnx/model.onnx"
model = ORTModelForSequenceClassification.from_pretrained(model_id, file_name=file_name)
tokenizer = AutoTokenizer.from_pretrained(model_id)

INT8 quantized model

model_id = "fyaronskiy/ruRoberta-large-ru-go-emotions"
file_name = "onnx/model_quantized.onnx"

model = ORTModelForSequenceClassification.from_pretrained(model_id, file_name=file_name)
tokenizer = AutoTokenizer.from_pretrained(model_id)

After loading, using ONNX models for inference is the same as for usual Transformer model:

best_thresholds = [0.36734693877551017, 0.2857142857142857, 0.2857142857142857, 0.16326530612244897, 0.14285714285714285, 0.14285714285714285, 0.18367346938775508, 0.3469387755102041, 0.32653061224489793, 0.22448979591836732, 0.2040816326530612, 0.2857142857142857, 0.18367346938775508, 0.2857142857142857, 0.24489795918367346, 0.7142857142857142, 0.02040816326530612, 0.3061224489795918, 0.44897959183673464, 0.061224489795918366, 0.18367346938775508, 0.04081632653061224, 0.08163265306122448, 0.1020408163265306, 0.22448979591836732, 0.3877551020408163, 0.3469387755102041, 0.24489795918367346]
LABELS = ['admiration', 'amusement', 'anger', 'annoyance', 'approval', 'caring', 'confusion', 'curiosity', 'desire', 'disappointment', 'disapproval', 'disgust', 'embarrassment', 'excitement', 'fear', 'gratitude', 'grief', 'joy', 'love', 'nervousness', 'optimism', 'pride', 'realization', 'relief', 'remorse', 'sadness', 'surprise', 'neutral']
ID2LABEL = dict(enumerate(LABELS))

def predict_emotions(text):
  inputs = tokenizer(text, truncation=True, add_special_tokens=True, max_length=128, return_tensors='pt')
  with torch.no_grad():
      logits = model(**inputs).logits
  probas = torch.sigmoid(logits).squeeze(dim=0)  
  class_binary_labels = (probas > torch.tensor(best_thresholds)).int()
  return [ID2LABEL[label_id] for label_id, value in enumerate(class_binary_labels) if value == 1]

print(predict_emotions('У вас отличный сервис и лучший кофе в городе, обожаю вашу кофейню!'))
#['admiration', 'love']

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

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

GPU в ailist

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

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

Подбираем GPU…

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

0 моделей