/ Модель

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

Контекст
512 токенов
Параметры
137 млн
Лицензия
MIT
Архитектура
bert · dense
Библиотека
transformers
Опубликована
28 окт 2026

bert-sentiment-classifier

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

Дообученная BERT-модель определяет положительную или отрицательную тональность англоязычных отзывов о фильмах.

120скачиваний за 30 дней0лайковвеса обновлены1 ноя 2026

Бенчмарки

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

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

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

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

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

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

Модель разработана ullahhafeez321 и представляет собой дообученную версию BERT Base Uncased для бинарной классификации тональности англоязычных отзывов о фильмах. Она относит отзыв к положительному или отрицательному классу и может использоваться в приложениях анализа отзывов и учебных проектах по NLP.

Это encoder-only Transformer на базе google-bert/bert-base-uncased с классификационной головой. Модель содержит 136,7 млн параметров, принимает текст длиной до 512 токенов и выдаёт метку класса и вероятности. На тестовом наборе из 2 000 отзывов IMDb автор сообщает точность 88,8%; также указаны ограничения на перенос в другие тематики и трудности с сарказмом, иронией и смешанной тональностью. Лицензия — MIT.

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

  • Определение тональности англоязычных отзывов о фильмах
  • Автоматическая сортировка отзывов IMDb на положительные и отрицательные
  • Добавление анализа тональности фильмов в приложение или сайт
  • Учебные проекты по классификации текста

Ограничения

Модель обучена на англоязычных отзывах IMDb и может хуже работать с текстами других тематик. Сарказм, ирония, неоднозначность и смешанная тональность затрудняют классификацию; автор также отмечает возможное переобучение.

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

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

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

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

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

Открыть на Hugging Face

BERT Sentiment Classifier

A fine-tuned BERT Base Uncased model for English movie review sentiment classification.

This model classifies movie reviews into two sentiment categories:

  • POSITIVE (1): The review expresses a positive opinion.
  • NEGATIVE (0): The review expresses a negative opinion.

The model was fine-tuned using the IMDb Movie Reviews dataset and evaluated on a separate test set containing 2,000 examples.

Model Details

PropertyDescription
Model architectureBERT Base Uncased
Base modelgoogle-bert/bert-base-uncased
TaskBinary Sentiment Classification
Number of classes2
Positive label1
Negative label0
Maximum sequence length192 tokens
FrameworkPyTorch
LibraryHugging Face Transformers

Dataset

The model was fine-tuned using the IMDb Movie Reviews Dataset.

The notebook uses the following dataset split:

DatasetNumber of samples
Training8,000
Validation1,000
Testing2,000
Total11,000

The dataset contains English movie reviews with binary sentiment labels:

  • 0: Negative
  • 1: Positive

The training set is used to fine-tune the model, the validation set is used to monitor training and evaluate checkpoints, and the test set is used for final performance evaluation.

Training Configuration

The model was fine-tuned for three epochs using the following configuration:

ParameterValue
Base modelBERT Base Uncased
Epochs3
Batch size16
Learning rate2e-5
Weight decay0.01
Warmup steps100
Maximum sequence length192
Random seed42
Best checkpoint metricValidation accuracy
Training frameworkPyTorch

A two-class classification head was added to the pretrained BERT encoder and fine-tuned for sentiment prediction.

Training Results

The following table shows the training progress across all three epochs.

EpochTraining LossValidation LossAccuracyPrecisionRecallF1-score
10.3764330.2594530.8960000.9193210.8677350.892784
20.1664790.3589830.8840000.8948450.8697390.882114
30.1344080.4451100.8940000.8875740.9018040.894632

Training loss decreased throughout training. However, validation loss increased after the first epoch. This may indicate overfitting, even though the validation accuracy remained relatively stable.

Final Validation Results

The final validation evaluation produced the following results:

MetricResult
Validation Loss0.259079
Accuracy89.70%
Precision91.95%
Recall86.97%
F1-score89.39%

Final Test Results

The final evaluation was performed on a separate test set containing 2,000 movie reviews, with 1,000 Negative and 1,000 Positive examples.

MetricResult
Test Loss0.259910
Accuracy88.80%
Precision91.54%
Recall85.50%
F1-score88.42%

The model correctly classified 1,776 out of 2,000 test examples.

Classification Report

ClassPrecisionRecallF1-scoreSupport
Negative0.86400.92100.89161,000
Positive0.91540.85500.88421,000
Macro Average0.88970.88800.88792,000
Weighted Average0.88970.88800.88792,000

Confusion Matrix

The confusion matrix shows the actual and predicted sentiment labels.

Actual / PredictedPredicted NegativePredicted Positive
Actual Negative92179
Actual Positive145855

Interpretation:

  • 921 Negative reviews were correctly classified.
  • 855 Positive reviews were correctly classified.
  • 79 Negative reviews were incorrectly classified as Positive.
  • 145 Positive reviews were incorrectly classified as Negative.

The model achieved higher recall for Negative reviews (92.10%) than Positive reviews (85.50%).

Model Architecture

This project uses an encoder-only transformer architecture.

BERT reads the input text and creates contextual representations of its tokens. The classification head uses these representations to predict the sentiment of the complete review.

The model follows this general workflow:

  1. Receive an English movie review.
  2. Tokenize the input text.
  3. Pass the tokens through the pretrained BERT encoder.
  4. Generate classification logits.
  5. Apply softmax to obtain class probabilities.
  6. Return the predicted sentiment and confidence score.

Usage

You can load this model directly using Hugging Face Transformers.

Install Dependencies

pip install transformers torch

Load the Model

import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

MODEL_NAME = "ullahhafeez321/bert-sentiment-classifier"

tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)

model.eval()

Make a Prediction

def predict_sentiment(text):

    inputs = tokenizer(
        text,
        return_tensors="pt",
        truncation=True,
        max_length=192
    )

    with torch.inference_mode():
        outputs = model(**inputs)

        probabilities = torch.softmax(
            outputs.logits,
            dim=-1
        )[0]

    predicted_id = int(probabilities.argmax())

    sentiment = model.config.id2label[predicted_id]

    confidence = float(probabilities[predicted_id]) * 100

    return {
        "text": text,
        "sentiment": sentiment,
        "confidence": round(confidence, 2)
    }


result = predict_sentiment(
    "This movie was excellent. I really enjoyed it!"
)

print(result)

Example Predictions

Input ReviewExpected Sentiment
This movie was absolutely wonderful!POSITIVE
This movie was terrible and boring.NEGATIVE
I loved every moment of this film.POSITIVE
I hated this movie. It was a waste of time.NEGATIVE

These examples are illustrative and are not guaranteed predictions.

Applications

This model can be integrated into:

  • Sentiment analysis websites
  • Movie review classification applications
  • Text classification projects
  • Python applications
  • Streamlit applications
  • Educational NLP projects

Limitations

  • The model was fine-tuned on English IMDb movie reviews.
  • It is primarily intended for movie-review sentiment classification.
  • It may not perform equally well on other domains, such as product reviews, news, or social media.
  • Sarcasm, irony, ambiguous language, and mixed sentiment can be difficult to classify.
  • Confidence scores are model probabilities, not guarantees of correctness.
  • Validation loss increased after the first epoch, suggesting possible overfitting.

Technologies Used

  • Python
  • PyTorch
  • Hugging Face Transformers
  • Hugging Face Datasets
  • Scikit-learn
  • IMDb Movie Reviews Dataset
  • Google BERT Base Uncased

Training Notebook

The training notebook includes:

  1. Library installation and environment setup.
  2. IMDb dataset loading and splitting.
  3. Pretrained BERT tokenizer and model initialization.
  4. Dataset tokenization.
  5. Model fine-tuning.
  6. Validation and test evaluation.
  7. Classification report and confusion matrix.
  8. Custom sentiment prediction.
  9. Saving and uploading the model to Hugging Face.

Project Integration

This model is also used as the sentiment classification component in my NLP Analysis Studio application, alongside a separate decoder-only Qwen model for Named Entity Recognition.

License

This project is released under the MIT License.

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

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

GPU в ailist

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

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

Подбираем GPU…

Класс архитектуры
BertForSequenceClassification
Ревизия весов
544d93d

0 моделей