/ Модель

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

Контекст
512 токенов
Параметры
12 млн
Лицензия
Apache 2.0
Архитектура
bert · dense
Базовая модель
bert_uncased_L-4_H-256_A-4
Библиотека
transformers
Опубликована
12 окт 2026

literary-bert-en-mini

Классификация текстаТекст → label3 профессии
81скачиваний за 30 дней1лайквеса обновлены25 окт 2026

Описание модели

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

Компактная модель BERT оценивает тональность отдельных английских литературных предложений по упорядоченной шкале от 1 до 10.

Literary Sentiment Ordinal BERT — Mini — это компактная англоязычная модель на основе BERT, разработанная автором репозитория susurofu для анализа тональности отдельных предложений в художественной литературе. Модель дообучена на энкодере google/bert_uncased_L-4_H-256_A-4 и содержит около 12 млн параметров. Она принимает текст и выдаёт оценку тональности по упорядоченной шкале от 1 (наиболее отрицательная) до 10 (наиболее положительная); обучение использовало псевдометки, созданные Gemma 4 31B. В README указан максимум обучения 128 токенов, тогда как метаданные сообщают нативный контекст 512 токенов.

Модель предназначена для исследовательского анализа эмоциональной окраски литературных предложений, сравнения валентности фрагментов и цифровых гуманитарных исследований. На независимой оценке предложений из «Старика и моря» Хемингуэя приведены метрики MAE 0,766 и точности в пределах одного балла 0,829. Это не универсальный классификатор и не инструмент для высокорисковых решений. Лицензия — Apache-2.0.

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

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

Ограничения

Модель обучена на автоматически созданных псевдометках, которые могут наследовать смещения учителя; оценка выполнена на одном литературном произведении, а модель не учитывает широкий контекст, иронию и изменения тональности на уровне повествования. Баллы шкалы 1–10 не являются калиброванными вероятностями и требуют интерпретации в контексте текста.

Публичные бенчмарки

Результаты из открытых лидербордов в сравнении с лидерами каталога

Публичных оценок пока нет

В подключённых источниках результатов этой модели не нашлось. Отсутствие оценки не значит, что модель хуже: её могли просто не проверять.

Источники: Hugging Face Leaderboards, Hugging Face Eval Results, Open LLM v2, MTEB, timm, Open ASR, EvalPlus

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

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

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

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

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

Открыть на Hugging Face

Literary Sentiment Ordinal BERT — Mini

This model is BERT-mini (11.3M parameters) fine-tuned for sentence-level sentiment analysis of English literary text using ten ordered sentiment levels (1 = most negative, 10 = most positive). It is one of five student configurations trained on Gemma 4 31B-generated pseudo-labels for literary sentences.

The training objective is cumulative-logit ordinal regression, rather than conventional three-class classification. The scalar score is the expected ordinal rating.

  • Original pretrained encoder: google/bert_uncased_L-4_H-256_A-4
  • Trained checkpoint: BERT-mini; maximum training input length: 128 tokens
  • Scores: 1–3 negative, 4–6 near-neutral, 7–10 positive (descriptive interpretation)
  • Checkpoint selected by minimum validation MAE, with Hemingway annotations kept out of training and selection

On the independent human-annotated Hemingway evaluation (n=1,923), this model achieved MAE 0.766, Kendall τ 0.402, Spearman ρ 0.472 and accuracy within ±1 0.829. On 305 reference-defined non-neutral sentences, it achieved MAE 0.969 and accuracy within ±1 0.708.

Important: this is a custom ordinal head. The model produces nine cumulative logits, not ten class logits. Do not use AutoModelForSequenceClassification or a default pipeline("sentiment-analysis") to interpret the outputs. Use the AutoModel example below; its trust_remote_code=True loads modeling_ordinal_bert.py from this repository. Review that file before running repository code.

Quick start

Install pip install torch transformers and use:

import torch
from transformers import AutoModel, AutoTokenizer

model_id = "susurofu/literary-bert-en-mini"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModel.from_pretrained(model_id, trust_remote_code=True).eval()

sentences = ["A wonderful day filled with joy.", "Everything was lost."]
inputs = tokenizer(sentences, padding=True, truncation=True,
                   max_length=128, return_tensors="pt")
with torch.inference_mode():
    scores = 1 + model(**inputs).logits.sigmoid().sum(dim=-1)
labels = scores.round().clamp(1, 10).int()
print(scores.tolist())  # continuous expected score in [1, 10]
print(labels.tolist())  # nearest integer rating (1..10)

torch.round follows the notebook's numpy.rint nearest-integer convention (half-to-even); typically the scores are noninteger. For GPU inference, move both model and tokenized tensors to the same device. See example_inference.py for a standalone version. The nine output logits represent P(Y > k) after sigmoid for thresholds k=1,...,9 and must not be passed through softmax/argmax.

Training data and supervision

  • 10,889 cleaned literary sentences from Project Gutenberg; an author/work sampling procedure and removal of short or structural passages were applied.
  • Labels assigned using Gemma 4 31B with each sentence annotated independently on the 1–10 scale. The teacher returned a JSON field Sentiment_score; hard integer pseudo-labels were used for training.
  • Stratified 80/10/10 train / validation / LLM-labeled test split: 8,711 / 1,089 / 1,089. These splits are distinct from the independent human-labeled test set.
  • The independent human evaluation consists of 1,923 sentences from Hemingway's The Old Man and the Sea, with reference scores averaged across two annotators. Hemingway was not used for model fine-tuning or checkpoint selection.
  • Teacher labels are imbalanced: 41.5% received score 5, and 57.9% received scores 4–6. The complete label frequencies (before splitting) are:
ScoreCountScoreCount
12396960
28007637
31,4368923
48219474
54,5191080

Architecture and training

The encoder produces a pooled representation, mapped to one latent sentiment score s(x). Nine trainable ordered thresholds θ₁ < ... < θ₉ are parameterized by a first threshold and cumulative softplus increments. The model returns:

logit_k = s(x) − θ_k, for k=1,...,9.

Training minimizes binary cross-entropy against nine cumulative binary targets 1[label > k]. At inference, E[Y|x] = 1 + Σ sigmoid(logit_k); the rounded rating is clipped to [1,10]. This is hard-label pseudo-labeling, not soft-logit distillation.

Training settingValue
Base encodergoogle/bert_uncased_L-4_H-256_A-4
Trainable parameters (approx.)11.3M
Learning rate2e-5
Weight decay0.01
Warmup ratio0.10
Maximum epochs3
Train / eval batch size16 / 32
Gradient accumulation1
Optimizer and schedulerHugging Face Trainer defaults (AdamW / linear scheduler)
Validation/checkpoint/logging intervalEvery 100 optimization steps
Checkpoint selectionLowest validation MAE
Maximum retained checkpoints6
Random seed1111
FP16Enabled when CUDA was available
Maximum tokenized length128
Selected checkpoint step1600

Evaluation: independent human-annotated Hemingway corpus

All sentences (n = 1,923). Each row reports metrics computed against the average of two human annotators. The table includes the teacher and external baseline results for context; those models are not included in this repository. The focus model is shown in bold. All numbers are from the supplied evaluation CSV (rounded to three decimals).

ModelMAE ↓Kendall τ ↑Spearman ρ ↑Pearson r ↑Prec. ±1 ↑Acc. ±1 ↑3-class macro P ↑3-class acc. ↑
Gemma 4 31B (teacher)0.8220.6040.6900.7110.4600.7410.5450.728
twt_roberta0.9720.4970.5680.6300.1760.6950.5740.806
twt_roberta_xlm1.2610.5050.5930.6260.1250.5300.5000.653
BERT-large0.7690.5890.6760.6850.6140.7870.5330.740
BERT-base0.7330.5800.6650.6920.7230.8150.5460.765
BERT-medium0.7520.4890.5680.6230.6590.8080.5640.800
BERT-small0.7170.4680.5410.5910.7080.8370.5570.805
BERT-mini0.7660.4020.4720.5160.7320.8290.5800.816
Constant-neutral baseline0.597———0.8410.8410.2940.881
ModelNegative P ↑Neutral P ↑Positive P ↑
Gemma 4 31B (teacher)0.1770.9720.487
twt_roberta0.2320.9600.530
twt_roberta_xlm0.1420.9600.397
BERT-large0.1940.9680.437
BERT-base0.2180.9710.449
BERT-medium0.2340.9480.510
BERT-small0.2330.9400.496
BERT-mini0.2000.9250.615
Constant-neutral baseline0.0000.8810.000

Non-neutral sentences (n = 305). This subset is selected using human reference scores below 4 or above 6. It measures performance on already-identified non-neutral sentences, not independent detection of such sentences.

ModelMAE ↓Spearman ρ ↑Pearson r ↑Prec. ±1 ↑Acc. ±1 ↑3-class macro P ↑3-class acc. ↑
Gemma 4 31B (teacher)1.1160.7910.8850.5220.6000.6060.669
twt_roberta1.6560.7450.7970.3060.2230.6240.636
twt_roberta_xlm1.6130.7750.8380.3010.3080.5690.610
BERT-large0.8870.7990.8770.5710.7110.5850.646
BERT-base0.7260.8260.8990.6980.8030.6290.675
BERT-medium0.9980.7850.8200.6690.6750.6050.570
BERT-small0.9820.7630.7940.6680.6980.5840.521
BERT-mini0.9690.7560.7840.6920.7080.6230.498
Constant-neutral baseline1.962——0.0000.0000.0830.249
ModelNegative P ↑Neutral P ↑Positive P ↑
Gemma 4 31B (teacher)0.5480.2711.000
twt_roberta0.5700.3210.980
twt_roberta_xlm0.5200.1960.990
BERT-large0.5380.2260.991
BERT-base0.5690.3280.991
BERT-medium0.5810.2600.974
BERT-small0.5580.2370.955
BERT-mini0.5880.2801.000
Constant-neutral baseline0.0000.2490.000

Metric definitions and interpretation

  • MAE is computed from the original continuous model predictions and original averaged human scores (lower is better). Kendall's τ, Spearman's ρ, and Pearson's r use these unrounded scores.
  • Accuracy (±1) is the proportion of samples with absolute error ≤ 1 in the original numerical scale.
  • Precision (±1) is a custom legacy measure: precision is calculated separately at each observed distinct predicted numerical value, counting predictions within ±1 of the reference as correct, then macro-averaged over those distinct values. On continuous predictions it is not conventional classification precision and may be sensitive to floating-point uniqueness. Interpret cautiously.
  • Three-class precision and accuracy are separate from ±1 metrics. Continuous predictions and averaged human scores are first rounded to integers using floor(score + 0.5) (half-up); scores 1–3 are negative, 4–6 neutral, and 7–10 positive. Macro precision averages the three per-class precision values, giving zero to classes without any predicted members.
  • Caution: The human test corpus is very neutral-skewed: 84.1% of reference scores are in [4,6]. A constant-neutral predictor achieves overall MAE 0.597, better than all models; its correlations are undefined. Therefore, use multiple metrics and inspect the non-neutral subset rather than ranking models by overall MAE alone. The constant-neutral row predicts a constant score 5.
  • Values across the two evaluation tables are not comparable without accounting for the different reference-selected subsets. RoBERTa results reflect their original numerical rescaling, rather than an ordinal model trained on 1–10 labels.

Performance on the held-out LLM-labeled test split (n = 1,089)

The following results measure agreement with the teacher-generated labels, not with Hemingway's human annotations.

ModelBest stepVal. MAETest MAETest RMSEExact acc.Acc. ±1QWKSpearman ρ
BERT-large16000.8470.8381.1960.4610.8140.7460.763
BERT-base6000.9710.9591.3120.4010.7710.6800.711
BERT-medium11001.0121.0781.5050.3720.7420.5930.567
BERT-small11001.0791.1421.5460.3600.6990.5290.532
BERT-mini16001.2191.2781.6330.2640.6610.4450.479

Intended use

Research on literary sentence sentiment, relative valence patterns, and exploratory Digital Humanities analysis of narrative text. Intended for English. Sentiment scoring is inherently interpretation-dependent; examine outputs in textual context before drawing literary conclusions. This model is not a general-purpose classifier for clinical, legal, or other high-stakes decision-making.

Limitations

  • Models were trained using automatically generated labels, which may inherit teacher biases (including topic-associated polarity).
  • Single-sentence annotation and modeling omit wider narrative context, irony, and discourse-level sentiment shifts.
  • The human-annotated evaluation covers one literary work; results do not guarantee similar performance across genres, dates, or authors.
  • The training setup used one fixed seed. Reported small differences between model sizes have no uncertainty estimates.
  • The 1–10 scale is ordinal: predicted values should not be treated as calibrated probabilities, and the expected score need not match an individual reader's interpretation.
  • Faster inference than the teacher is plausible given model size, but has not been benchmarked in the corresponding study.

Related model variants

BERT-tiny was trained during development but is not released because it converged to constant neutral predictions. The constant-neutral baseline remains in the evaluation tables for context.

License and Attribution

This model is released under the Apache License 2.0. It is fine-tuned from Google's BERT architecture (Apache 2.0) using literary sentences from Project Gutenberg annotated by Gemma 4 31B (Apache 2.0). The model may be used, modified, and redistributed under the terms of the Apache License 2.0.

Citation

@misc{suslov2026distilling,
  author    = {Suslov, Artem and Hashimoto, Takehiro},
  title     = {Distilling Literary Sentiment from LLM Annotations into an Ordinal BERT Model},
  year      = {2026},
  publisher = {Zenodo},
  doi       = {10.5281/zenodo.23554553},
  url       = {https://doi.org/10.5281/zenodo.23554553}
}

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
BertForOrdinalRegression
Ревизия весов
3f61ca7

0 моделей