![Revisit consent button](../images/body-df29beacd7496220cc94.svg)
We value your privacy
We use cookies to enhance your browsing experience, serve personalised ads or content, and analyse our traffic. By clicking "Accept All", you consent to our use of cookies.
Customise Reject All Accept All
Customise Consent Preferences ![](../images/body-2159bb67f3de8ad870eb.svg)
We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.
The cookies that are categorised as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... Show more
NecessaryAlways Active
Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.
  * Cookie
BCTempID
  * Duration
10 minutes
  * Description
No description available.


  * Cookie
__cf_bm
  * Duration
1 hour
  * Description
This cookie, set by Cloudflare, is used to support Cloudflare Bot Management. 


  * Cookie
AWSALBCORS
  * Duration
7 days
  * Description
Amazon Web Services set this cookie for load balancing.


  * Cookie
_cfuvid
  * Duration
session
  * Description
Cloudflare sets this cookie to track users across sessions to optimize user experience by maintaining session consistency and providing personalized services


  * Cookie
li_gc
  * Duration
6 months
  * Description
Linkedin set this cookie for storing visitor's consent regarding using cookies for non-essential purposes.


  * Cookie
__hssrc
  * Duration
session
  * Description
This cookie is set by Hubspot whenever it changes the session cookie. The __hssrc cookie set to 1 indicates that the user has restarted the browser, and if the cookie does not exist, it is assumed to be a new session.


  * Cookie
__hssc
  * Duration
1 hour
  * Description
HubSpot sets this cookie to keep track of sessions and to determine if HubSpot should increment the session number and timestamps in the __hstc cookie.


  * Cookie
wpEmojiSettingsSupports
  * Duration
session
  * Description
WordPress sets this cookie when a user interacts with emojis on a WordPress site. It helps determine if the user's browser can display emojis properly.


  * Cookie
BCSessionID
  * Duration
1 year 1 month 4 days
  * Description
Blueconic sets this cookie as a unique identifier for the BlueConic profile.


  * Cookie
_octo
  * Duration
1 year
  * Description
No description available.


  * Cookie
logged_in
  * Duration
1 year
  * Description
No description available.


  * Cookie
__Secure-YEC
  * Duration
past
  * Description
YouTube sets this cookie to stores the user's video player preferences using embedded YouTube video


  * Cookie
__eoi
  * Duration
6 months
  * Description
Description is currently not available.


  * Cookie
AWSALBTGCORS
  * Duration
7 days
  * Description
No description available.


  * Cookie
login-status-p
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
AWSALBTG
  * Duration
7 days
  * Description
No description available.


  * Cookie
csrf_token
  * Duration
session
  * Description
No description available.


  * Cookie
token_v2
  * Duration
1 day
  * Description
Description is currently not available.


  * Cookie
D
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
PHPSESSID
  * Duration
session
  * Description
This cookie is native to PHP applications. The cookie stores and identifies a user's unique session ID to manage user sessions on the website. The cookie is a session cookie and will be deleted when all the browser windows are closed.


  * Cookie
VISITOR_PRIVACY_METADATA
  * Duration
6 months
  * Description
YouTube sets this cookie to store the user's cookie consent state for the current domain. 


  * Cookie
cookietest
  * Duration
session
  * Description
The cookietest cookie is typically used to determine whether the user's browser accepts cookies, essential for website functionality and user experience.


  * Cookie
__Host-airtable-session
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
__Host-airtable-session.sig
  * Duration
1 year
  * Description
This cookie is used to enable us to integrate the services of Airtable.


  * Cookie
m
  * Duration
1 year 1 month 4 days
  * Description
Stripe sets this cookie for fraud prevention purposes. It identifies the device used to access the website, allowing the website to be formatted accordingly.


  * Cookie
BIGipServer*
  * Duration
session
  * Description
Marketo sets this cookie to collect information about the user's online activity and build a profile about their interests to provide advertisements relevant to the user. 


  * Cookie
__cfruid
  * Duration
session
  * Description
Cloudflare sets this cookie to identify trusted web traffic.


  * Cookie
_GRECAPTCHA
  * Duration
6 months
  * Description
Google Recaptcha service sets this cookie to identify bots to protect the website against malicious spam attacks.


  * Cookie
__Secure-YNID
  * Duration
6 months
  * Description
Google cookie used to protect user security and prevent fraud, especially during the login process.


  * Cookie
cookieyes-consent
  * Duration
1 year
  * Description
CookieYes sets this cookie to remember users' consent preferences so that their preferences are respected on subsequent visits to this site. It does not collect or store any personal information about the site visitors.


Functional
Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.
  * Cookie
lidc
  * Duration
1 day
  * Description
LinkedIn sets the lidc cookie to facilitate data center selection.


  * Cookie
brw
  * Duration
1 year
  * Description
No description available.


  * Cookie
brwConsent
  * Duration
5 minutes
  * Description
Description is currently not available.


  * Cookie
WMF-Uniq
  * Duration
1 year
  * Description
Description is currently not available.


  * Cookie
loom_anon_comment
  * Duration
1 year
  * Description
No description available.


  * Cookie
loom_referral_video
  * Duration
session
  * Description
Description is currently not available.


  * Cookie
VISITOR_INFO1_LIVE
  * Duration
6 months
  * Description
A cookie set by YouTube to measure bandwidth that determines whether the user gets the new or old player interface.


  * Cookie
yt-remote-connected-devices
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
ytidb::LAST_RESULT_ENTRY_KEY
  * Duration
Never Expires
  * Description
The cookie ytidb::LAST_RESULT_ENTRY_KEY is used by YouTube to store the last search result entry that was clicked by the user. This information is used to improve the user experience by providing more relevant search results in the future.


  * Cookie
yt-remote-device-id
  * Duration
Never Expires
  * Description
YouTube sets this cookie to store the user's video preferences using embedded YouTube videos.


  * Cookie
yt-remote-session-name
  * Duration
session
  * Description
The yt-remote-session-name cookie is used by YouTube to store the user's video player preferences using embedded YouTube video.


  * Cookie
yt-remote-fast-check-period
  * Duration
session
  * Description
The yt-remote-fast-check-period cookie is used by YouTube to store the user's video player preferences for embedded YouTube videos.


  * Cookie
yt-remote-session-app
  * Duration
session
  * Description
The yt-remote-session-app cookie is used by YouTube to store user preferences and information about the interface of the embedded YouTube video player.


  * Cookie
yt-remote-cast-available
  * Duration
session
  * Description
The yt-remote-cast-available cookie is used to store the user's preferences regarding whether casting is available on their YouTube video player.


  * Cookie
yt-remote-cast-installed
  * Duration
session
  * Description
The yt-remote-cast-installed cookie is used to store the user's video player preferences using embedded YouTube video.


  * Cookie
cp_session
  * Duration
3 months
  * Description
Codepen sets this cookie for Help systems found in the website.


  * Cookie
loid
  * Duration
1 year 1 month 4 days
  * Description
This cookie is set by the Reddit. The cookie enables the sharing of content from the website onto the social media platform.


Analytics
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.
  * Cookie
__hstc
  * Duration
6 months
  * Description
Hubspot set this main cookie for tracking visitors. It contains the domain, initial timestamp (first visit), last timestamp (last visit), current timestamp (this visit), and session number (increments for each subsequent session).


  * Cookie
hubspotutk
  * Duration
6 months
  * Description
HubSpot sets this cookie to keep track of the visitors to the website. This cookie is passed to HubSpot on form submission and used when deduplicating contacts.


  * Cookie
_ga
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to calculate visitor, session and campaign data and track site usage for the site's analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognise unique visitors.


  * Cookie
_ga_*
  * Duration
1 year 1 month 4 days
  * Description
Google Analytics sets this cookie to store and count page views.


  * Cookie
__Host-psifi.analyticsTrace
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
__Host-psifi.analyticsTraceV2
  * Duration
6 hours
  * Description
Description is currently not available.


  * Cookie
_gh_sess
  * Duration
session
  * Description
GitHub sets this cookie for temporary application and framework state between pages like what step the user is on in a multiple step form.


  * Cookie
YSC
  * Duration
session
  * Description
YSC cookie is set by Youtube and is used to track the views of embedded videos on Youtube pages.


  * Cookie
ajs_anonymous_id
  * Duration
1 year
  * Description
This cookie is set by Segment to count the number of people who visit a certain site by tracking if they have visited before.


  * Cookie
vuid
  * Duration
1 year 1 month 4 days
  * Description
Vimeo installs this cookie to collect tracking information by setting a unique ID to embed videos on the website. 


Performance
Performance cookies are used to understand and analyse the key performance indexes of the website which helps in delivering a better user experience for the visitors.
  * Cookie
AWSALB
  * Duration
7 days
  * Description
AWSALB is an application load balancer cookie set by Amazon Web Services to map the session to the target.


  * Cookie
acq
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
acq.sig
  * Duration
past
  * Description
Description is currently not available.


  * Cookie
ptc
  * Duration
2 years
  * Description
No description available.


Advertisement
Advertisement cookies are used to provide visitors with customised advertisements based on the pages you visited previously and to analyse the effectiveness of the ad campaigns.
  * Cookie
muc_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to collect user behaviour and interaction data to optimize the website.


  * Cookie
guest_id_marketing
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
guest_id_ads
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor.


  * Cookie
personalization_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to integrate and share features for social media and also store information about how the user uses the website, for tracking and targeting.


  * Cookie
guest_id
  * Duration
1 year 1 month 4 days
  * Description
Twitter sets this cookie to identify and track the website visitor. It registers if a user is signed in to the Twitter platform and collects information about ad preferences.


  * Cookie
bcookie
  * Duration
1 year
  * Description
LinkedIn sets this cookie from LinkedIn share buttons and ad tags to recognize browser IDs.


  * Cookie
__Secure-ROLLOUT_TOKEN
  * Duration
6 months
  * Description
YouTube sets this cookie to manage feature rollout and experimentation. It helps Google control which new features or interface changes are shown to users as part of testing and staged rollouts, ensuring consistent experience for a given user during an experiment.


  * Cookie
yt.innertube::nextId
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
yt.innertube::requests
  * Duration
Never Expires
  * Description
YouTube sets this cookie to register a unique ID to store data on what videos from YouTube the user has seen.


  * Cookie
session_tracker
  * Duration
session
  * Description
This cookie is set by the Reddit. This cookie is used to identify trusted web traffic. It also helps in adverstising on the website.


  * Cookie
edgebucket
  * Duration
session
  * Description
Reddit sets this cookie to save the information about a log-on Reddit user, for the purpose of advertisement recommendations and updating the content.


  * Cookie
did
  * Duration
1 year
  * Description
Arbor sets this cookie to show targeted ads to site visitors.This cookie expires after 2 months or 1 year.


Uncategorised
Other uncategorised cookies are those that are being analysed and have not been classified into a category as yet.
No cookies to display.
Reject All Save My Preferences Accept All
Toggle Search[](https://towardsdatascience.com/)Toggle Mobile Navigation
[](https://towardsdatascience.com/)
Publish AI, ML & data-science insights to a global community of data professionals.
Sign in[Submit an Article](https://write.insightmediagroup.io)
[Latest](https://towardsdatascience.com/latest/)[Editor's Picks](https://towardsdatascience.com/tag/editors-pick/)[Newsletter](https://towardsdatascience.com/tag/the-variable/)[ShipAI](https://towardsdatascience.com/shipai/)
* * *
[Write For TDS](https://towardsdatascience.com/submissions/)
[LinkedIn](https://www.linkedin.com/company/towards-data-science/)[X](https://x.com/TDataScience)Toggle Search
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
# How to Fine-Tune an SLM for Emotion Recognition
Python tutorial for fine-tuning a Mistral Small 3.1 on an imbalanced training set to classify 15 emotions in social media communication
[Petr Koráb](https://towardsdatascience.com/author/petrkorab/)
June 5, 20269 min read
![](../images/000.png)
Image created by GPT 5.3
## Introduction
Recent small language models (SLMs) fine-tuned for [sentiment classification](https://huggingface.co/models?pipeline_tag=text-generation&num_parameters=min:6B&sort=trending&search=sentiment+llama) infer sentiment as a single score, capturing the overall emotional tone of the text. For many use cases, the positive-negative classification does not tell the full story a company needs. Emotion recognition models go further, decomposing sentiment into emotion classes (_“anger”, “approval”, “disappointment”_ , etc.) and assigning probabilities to a set of emotions in the text. It is then possible to model emotional content in datasets that a company receives (customer tickets, emails, brand-related discussions), and react swiftly to changing conditions.
For one of our recent projects, modeling emotions in online media, we required an emotion recognition model with open weights and a flexible license, maintaining high transparency standards, and, of course, benefiting from the lower costs associated with open models. We subjectively prefer European models, but Hugging Face did not offer a [Mistral alternative with](https://huggingface.co/models?sort=trending&search=emotion+mistral) a developed model card. One possible reason is that the most detailed training set for emotion recognition, the 28-emotion [GoEmotions datase](https://research.google/blog/goemotions-a-dataset-for-fine-grained-emotion-classification/)t, is highly [class-imbalanced](https://latitude.so/blog/fine-tuning-llms-on-imbalanced-data-best-practices). Fine-tuning an SLM on a high-class-imbalance data set that performs decently on the test requires a deeper focus.
We treated the class-imbalance problem by a combination of three techniques: (1) **undersampling** the most represented emotional category, (2) **synthetically expanding** the **minority classes** with [Nature’s 2025 ISMOTE](https://www.nature.com/articles/s41598-025-09506-w) algorithm, and (3) **weighting** the **loss function.** With this combination of techniques, [_MistralSmall-3.1.GoEmotions_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions), now released on Hugging Face, infers most target emotions relevant to our project with F1 > 0.7.
This article explains in detail how to fine-tune an open-weight SLM. We’ll also figure out: 
  * _How to preprocess class-imbalanced data for LLM fine-tuning with the_[ _2025 ISMOTE_](https://www.nature.com/articles/s41598-025-09506-w) _algorithm._
  * _How to decompose sentiment into emotion categories by finetuning a Small Language Model for emotion recognition in text data._


Learn this step by step with the interactive [Machine Learning](https://roadmap.sh/machine-learning) roadmap.
## 2. Data
[GoEmotions](https://github.com/google-research/google-research/tree/master/goemotions) is a human-annotated dataset of 58k Reddit comments extracted from English-language subreddits and labeled with [27 emotion categories](https://github.com/google-research/google-research/blob/master/goemotions/data/emotions.txt) and a _“neutral”_ label. It is a **multi-label classification dataset** in which each comment may be labeled with multiple TRUEs for emotions (e.g., _“Hitting me. That just added another funny dynamic to it even though I wasn’t actually trying to hit her”_ is True for _“amusement”_ , and _“annoyance”_).
The dataset was released on [TensorFlow Datasets](https://www.tensorflow.org/datasets/catalog/goemotions) under the Apache 2.0 License and contains 54,263 labeled texts. Here is what it looks like:
![](../images/001.png)
Image 1. GoEmotions dataset. Image by author.
After a quick check, we can see a high-class imbalance in the data where the _neutral_ category prevails:
![](../images/002.png)
Image 2. Class imbalance in GoEmotions dataset. Image by author.
## 3. Training set preprocessing
> __Our goal is to develop a classifier to identify 15 emotions in general-language texts. Training on class-imbalanced data can introduce bias, as the fine-tuned model tends to favor the majority class and perform worse on the minority ones, so preprocessing is essential.__
We used a combination of methods for the **training set;** the validation and test sets remained unchanged to address class imbalance and maximize performance on the target emotions (_fear, sadness, disgust, disapproval, annoyance, anger, disappointment, optimism, amusement, surprise, admiration, excitement, confusion, joy, love_): 
  * We thinned the data by randomly filtering the _“neutral”_ rows.
  * We generated synthetic samples for the least-represented emotional categories using _ISMOTE (Improved Synthetic Minority Over-sampling Technique)_.


The _ISMOTE_ algorithm extends the common SMOTE technique by (1) expanding the sample generation space and (2) improving sampling distribution. The synthetically generated samples then have more realistic data distributions than those produced by the original method.
![](../images/body-d8e9b0b2c266c14a4706.png)
Image 3. The flowchart of the ISMOTE algorithm. Source: [Scientific Reports.](https://www.nature.com/articles/s41598-025-09506-w/figures/3)
By reducing the majority class and synthetically expanding the minority categories to 4000 samples, we constructed a relatively balanced set for fine-tuning. The code for ISMOTE oversampling is [here.](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions/tree/main)
![](../images/body-d96d37abaf82578949da.png)
Image 4. Label relative frequency , train (augmented), validation, and test sets. Image by author.
## 4. SLM Fine-tuning
Among Mistral’s models, we chose the _Small_ class ([Small-3.1-24B-Instruct-2503](https://huggingface.co/mistralai/Mistral-Small-3.1-24B-Instruct-2503)), which fits our GPU and provides the multilingual capabilities we need for the classifier. The [Unsloth](https://unsloth.ai/docs) framework makes the finetuning steps uncomplicated and faster than with [Transformers](https://pypi.org/project/transformers/):
_**1. Data loading**_  _—_ _loading preprocessed training set, validation, and test sets._ We use a 60:20:20 split.
_**2. Loading**_ _the_ _**base model**_ _— loading the Small-3.1–24B-Instruct-2503 locally._
_**3.**__Apply_ _**LoRA**_ _—_[ _lowering hardware requirements_](https://www.ibm.com/think/topics/lora) _._
_**4. Multilabel wrapper with focal loss function**_ _— updates the trainer for multilabel classification. Also adds focal loss to weight the loss function for a selected set of emotions, prioritizing their performance._
_**5. Evaluation metrics**_ _and_ _**training args**_ _— specifying the evaluation metrics and hyperparameters for model training._
_**6.**__Model_ _**training**_ _— trainer formulation and launch._
_**7. Evaluation**_ _— evaluating the best model performance on the test set._
## 4.1. Coding 
Here is the code implementation.
### 4.1.1. Data loading
python

```
# Loading augmented train, validation and test sets
BASE = r"augmented"

def load_split(path: str) -> Dataset:
    with open(path, encoding="utf-8") as f:
        d = json.load(f)
    return Dataset.from_dict({"input_embeds": d["X"], "labels": d["y"]})

train_dataset = load_split(f"{BASE}/train.json")
val_dataset   = load_split(f"{BASE}/val.json")
test_dataset  = load_split(f"{BASE}/test.json")

# Formulate embedding dimension
EMBED_DIM = len(train_dataset[0]["input_embeds"])

# Return Pytorch tensors
train_dataset.set_format("torch")
val_dataset.set_format("torch")
test_dataset.set_format("torch")
```

### 4.1.2. Loading the base model 
python

```
# Load base model with Unsloth FastLanguageModel
MODEL_NAME = "unsloth/Mistral-Small-3.1-24B-Instruct-2503"

base_model, _ = FastLanguageModel.from_pretrained(
    model_name=MODEL_NAME,
    max_seq_length=2,
    load_in_4bit=True,
    dtype=torch.bfloat16,
)
```

### 4.1.3. Apply LoRA
python

```
# Aply Low-rank adaptation (LoRA) 
base_model = FastLanguageModel.get_peft_model(
    base_model,
    r=16,
    lora_alpha=32,
    lora_dropout=0,
    bias="none",
    target_modules=[
        "q_proj", "k_proj", "v_proj", "o_proj",
        "gate_proj", "up_proj", "down_proj",
    ],
    use_gradient_checkpointing="unsloth",
    random_state = 3407,
    use_rslora = False, 
)
```

### 4.1.4. Multilabel wrapper with focal loss function
python

```
# Focal loss weights for preffered labels  
FOCAL_ALPHA_DEFAULT   = 0.25
FOCAL_ALPHA_PREFERRED = 0.75

PREFERRED_LABELS = {
    "fear", "sadness", "disgust", "disapproval", "annoyance",
    "anger", "disappointment", "optimism", "amusement", "surprise",
    "admiration", "excitement", "confusion","joy","love"
}

FOCAL_ALPHA_PER_LABEL: list[float] = [
    FOCAL_ALPHA_PREFERRED if lbl in PREFERRED_LABELS else FOCAL_ALPHA_DEFAULT
    for lbl in EMOTION_LABELS
]

"Per-label weighted focal binary cross-entropy for multi-label problems"
class FocalLossWithAlpha(nn.Module):
        def __init__(self, alpha: list[float], gamma: float = 2.0):
        super().__init__()
        self.register_buffer("alpha", torch.tensor(alpha, dtype=torch.float32))
        self.gamma = gamma
    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        probs   = torch.sigmoid(logits)
        p_t     = probs * targets + (1.0 - probs) * (1.0 - targets)
        alpha_t = self.alpha * targets + (1.0 - self.alpha) * (1.0 - targets)
        focal_w = alpha_t * (1.0 - p_t) ** self.gamma
        bce     = nn.functional.binary_cross_entropy_with_logits(
            logits, targets, reduction="none"
        )
        return (focal_w * bce).mean()

```

python

```
# Multilabel classification wrapper with focal loss class weighting
class MistralForMultiLabel(nn.Module):
    is_loaded_in_4bit = True

    def __init__(self, backbone: nn.Module, num_labels: int,
                 hidden_size: int, embed_dim: int):
        super().__init__()
        self.backbone = backbone
        _device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.projection = nn.Sequential(
            nn.Linear(embed_dim, hidden_size // 2),
            nn.GELU(),
            nn.Linear(hidden_size // 2, hidden_size),
        ).to(_device)
        self.dropout    = nn.Dropout(0.1).to(_device)
        self.classifier = nn.Linear(hidden_size, num_labels).to(_device)
        self.focal_loss = FocalLossWithAlpha(FOCAL_ALPHA_PER_LABEL).to(_device)

    def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None):
        self.backbone.gradient_checkpointing_enable(gradient_checkpointing_kwargs)

    def gradient_checkpointing_disable(self):
        self.backbone.gradient_checkpointing_disable()

    def forward(
        self,
        input_embeds: torch.Tensor,
        labels: torch.Tensor | None = None,
        **kwargs,
    ):
        B = input_embeds.size(0)
        projected = self.projection(input_embeds).unsqueeze(1)
        attn_mask = torch.ones(B, 1, device=input_embeds.device)

        outputs = self.backbone.base_model.model.model(
            inputs_embeds=projected,
            attention_mask=attn_mask,
            output_hidden_states=True,
        )
        pooled = outputs.hidden_states[-1][:, 0, :]
        logits = self.classifier(self.dropout(pooled))

        loss = self.focal_loss(logits, labels.float()) if labels is not None else None
        return {"loss": loss, "logits": logits}
```

### 4.1.5. Evaluation metrics and training args
python

```
# Specifiy the evaluation function
def compute_metrics(eval_pred):
    logits, labels = eval_pred
    probs = torch.sigmoid(torch.tensor(logits)).numpy()
    preds = (probs >= 0.5).astype(int)
    labels = labels.astype(int)

    from sklearn.metrics import accuracy_score

    exact_accuracy  = accuracy_score(labels, preds)
    macro_f1        = f1_score(labels, preds, average="macro", zero_division=0)
    micro_f1        = f1_score(labels, preds, average="micro", zero_division=0)
    macro_precision = precision_score(labels, preds, average="macro", zero_division=0)
    macro_recall    = recall_score(labels, preds, average="macro", zero_division=0)

    per_class_f1        = f1_score(labels, preds, average=None, zero_division=0)
    per_class_recall    = recall_score(labels, preds, average=None, zero_division=0)
    per_class_precision = precision_score(labels, preds, average=None, zero_division=0)
    per_class_accuracy  = (preds == labels).mean(axis=0)

    per_class_metrics = {}
    for i, emotion in enumerate(EMOTION_LABELS):
        per_class_metrics[f"f1_{emotion}"]        = float(per_class_f1[i])
        per_class_metrics[f"recall_{emotion}"]    = float(per_class_recall[i])
        per_class_metrics[f"precision_{emotion}"] = float(per_class_precision[i])
        per_class_metrics[f"accuracy_{emotion}"]  = float(per_class_accuracy[i])

    return {
        "exact_accuracy":   exact_accuracy,
        "macro_f1":         macro_f1,
        "micro_f1":         micro_f1,
        "macro_precision":  macro_precision,
        "macro_recall":     macro_recall,
        **per_class_metrics,
    }
```

python

```
# Specify hyperparameters
training_args = TrainingArguments(
    output_dir=OUTPUT_DIR,            # where checkpoints and logs are written
    eval_strategy="epoch",            # run evaluation once per epoch
    save_strategy="epoch",            # save checkpoint once per epoch
    per_device_train_batch_size=8,    # samples per GPU per step
    per_device_eval_batch_size=16,    # larger batch is fine — no gradients
    gradient_accumulation_steps=4,    # effective batch = 8 × 4 = 32
    num_train_epochs=15,              # total passes over the training data
    learning_rate=1e-4,               # peak LR after warmup
    bf16=True,                        # bfloat16 mixed precision
    optim="adamw_8bit",               # 8-bit AdamW
    warmup_ratio=0.05,                # first 5 % of steps ramp LR from 0 to peak
    lr_scheduler_type="cosine",       # cosine decay from peak LR to ~0
    logging_steps=25,                 # print loss/LR to console every 25 steps
    logging_first_step=True,          # also log step 1 to catch early instability
    load_best_model_at_end=True,      # restore best checkpoint after training ends
    metric_for_best_model="macro_f1", # criterion used to select the best checkpoint
    greater_is_better=True,           # higher macro_f1 is better in evaluation
    gradient_checkpointing=False,    
    remove_unused_columns=False,      # keep input_embeds column
    save_total_limit=15,              # keep all checkpoints on disk to load the best model
    weight_decay=0.01,                # L2 regularisation on all trainable parameters
)
```

### 4.1.6. Model training
python

```
# Set-up the trainer for multilabel finetuning
class MultiLabelTrainer(Trainer):
    def compute_loss(self, model, inputs, return_outputs=False, **kwargs):
        labels = inputs.pop("labels")
        outputs = model(**inputs, labels=labels)
        loss = outputs["loss"]
        return (loss, outputs) if return_outputs else loss

    def _save_checkpoint(self, model, trial, metrics=None):
        super()._save_checkpoint(model, trial)
        ckpt_dir = self._get_output_dir(trial)
        # Save head
        torch.save({
            "projection": model.projection.state_dict(),
            "classifier":  model.classifier.state_dict(),
        }, os.path.join(ckpt_dir, "head_weights.pt"))
        # Save LoRA adapter explicitly (bypasses bitsandbytes serialization issues)
        model.backbone.save_pretrained(os.path.join(ckpt_dir, "lora_adapter"))

    def _load_best_model(self):
        best_ckpt = self.state.best_model_checkpoint
        if not best_ckpt:
            return
        # Restore head
        head_path = os.path.join(best_ckpt, "head_weights.pt")
        if os.path.exists(head_path):
            head = torch.load(head_path, map_location="cpu")
            self.model.projection.load_state_dict(head["projection"])
            self.model.classifier.load_state_dict(head["classifier"])
            print(f"Head restored from: {best_ckpt}")
        else:
            print(f"WARNING: head_weights.pt not found in {best_ckpt}")
        # Restore LoRA adapter
        lora_path = os.path.join(best_ckpt, "lora_adapter")
        if os.path.exists(lora_path):
            from peft import PeftModel
            self.model.backbone.load_adapter(lora_path, adapter_name="default")
            print(f"LoRA restored from: {best_ckpt}")
        else:
            print(f"WARNING: lora_adapter/ not found in {best_ckpt}")

# Launch the trainer
trainer = MultiLabelTrainer(
    model=model,
    args=training_args,
    train_dataset=train_dataset,
    eval_dataset=val_dataset,
    compute_metrics=compute_metrics,
)

# Launch training
trainer.train()
```

Fine-tuning for 15 epochs took 9 hours and 30 minutes on a machine with an NVIDIA RTX 6000 GPU and 192 GB of VRAM, with the best model loaded at the end.
### 4.1.7. Model evaluation
Let's show the performance on the test dataset. The standard statistics for model evaluation per class are **F1** , **Precision** , and **Recall**. We can see relatively good performance on the target emotions, with F1 scores over 0.7, for most categories. Full performance is on the [model card](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions).  
| **Emotion**  | **Precision**  | **Recall**  | **F1**  | **N**  |  
| --- | --- | --- | --- | --- |  
| admiration  | 0.7415  | 0.6354  | 0.6844  | 993  |  
| amusement  | 0.7810  | 0.7422  | 0.7611  | 543  |  
| anger  | 0.7423  | 0.7367  | 0.7395  | 395  |  
| annoyance  | 0.7049  | 0.5452  | 0.6148  | 609  |  
| confusion  | 0.7576  | 0.8251  | 0.7899  | 303  |  
| disappointment  | 0.8487  | 0.8459  | 0.8473  | 305  |  
| disapproval  | 0.7208  | 0.5841  | 0.6453  | 517  |  
| disgust  | 0.8396  | 0.9368  | 0.8856  | 190  |  
| excitement  | 0.8240  | 0.9366  | 0.8767  | 205  |  
| fear  | 0.9112  | 0.9686  | 0.9390  | 159  |  
| joy  | 0.7577  | 0.8024  | 0.7794  | 339  |  
| love  | 0.7424  | 0.7903  | 0.7656  | 496  |  
| optimism  | 0.8145  | 0.7636  | 0.7882  | 368  |  
| sadness  | 0.8534  | 0.8899  | 0.8713  | 327  |  
| surprise  | 0.8456  | 0.8555  | 0.8505  | 256  |  
| **Macro precision**  | **0.8295**  |   |   |   |  
| **Macro recall**  | **0.8184**  |   |   |   |  
| **Micro F1**  | **0.7527**  |   |   |   |  
| **Macro F1**  | **0.8215**  |   |   |   |  
## 5. Summary
Let’s now summarize the key points of the article. The requirements and full code are in this [repo](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions).
  * **Emotion recognition** modeling extends sentiment analysis by decomposing the overall sentiment score into its emotional components.
  * **MistralSmall-3.1.GoEmotions** is on [_Hugging Face_](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)[ ](https://huggingface.co/TextMiningStories/Mistral-Small-3.1-24B-goemotions)under the Apache 2.0 license. The [repo ](https://github.com/PetrKorab/MistralSmall-3.1.GoEmotions)also includes the inference guideline.
  * **Deployment use cases** are [brand and social monitoring](https://www.meegle.com/en_us/topics/affective-computing/emotion-recognition-in-marketing-campaigns), and [email categorization](https://cobbai.com/blog/email-classification-ai-support).


_**Petr Koráb**_ _is the founder of Text Mining Stories,_ a Prague-based development & consultancy company. Learn more about the cutting-edge NLP on [our blog.](https://textminingstories.com/blog/)
_**AI statement**_. Some parts of the code were reviewed by Sonnet 4.6 (Cursor). No text was generated using AI.
_**Acknowledgements**_ _._ The National Bank of Slovakia Foundation supported this development. I thank Martin Feldkircher, Václav Jež, and Michala Moravcová for comments and suggestions.
## References
[1] Ying Li, Yali Yang, Peihua Song, Lian Duan, Rui Ren. 2025. An improved SMOTE algorithm for enhanced imbalanced data classification by expanding sample generation space.[_Scientific Reports, 15_](https://www.nature.com/articles/s41598-025-09506-w)[(](https://www.nature.com/articles/s41598-025-09506-w)[_23521)._](https://www.nature.com/articles/s41598-025-09506-w)
[2] Yinhan Liu _, Jiatao Gu_ , Naman Goyal, Xian Li, Sergey Edunov  
Marjan Ghazvininejad, Mike Lewis, Luke Zettlemoyer. 2020. [_Multilingual Denoising Pre-training for Neural Machine Translation_](https://aclanthology.org/2020.tacl-1.47.pdf). Transactions of the Association for Computational Linguistics, 8, pp. 726–742.
## Register Now to Continue Reading
### Unlock Towards Data Science with a Free Account
All articles on Towards Data Science are available to registered users. Create a free account today to access this article and thousands more.
Register for freeSign in to your account
* * *
![](../images/body-9e78938b5e8b0a70213c.jpeg)
Written By
## [Petr Koráb](https://towardsdatascience.com/author/petrkorab/)
[See all from Petr Koráb](https://towardsdatascience.com/author/petrkorab/)
[Emotion Recognition](https://towardsdatascience.com/tag/emotion-recognition/)[Fine Tuning](https://towardsdatascience.com/tag/fine-tuning/)[Llm](https://towardsdatascience.com/tag/llm/)[Sentiment Classification](https://towardsdatascience.com/tag/sentiment-classification/)[Small Language Model](https://towardsdatascience.com/tag/small-language-model/)
Share This Article
  * [](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)
  * [](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&title=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)
  * [](https://x.com/share?url=https%3A%2F%2Ftowardsdatascience.com%2Fhow-to-fine-tune-an-slm-for-emotion-recognition%2F&text=How%20to%20Fine-Tune%20an%20SLM%20for%20Emotion%20Recognition)


Towards Data Science is a community publication. Submit your insights to reach our global audience and earn through the TDS Author Payment Program.
[Write for TDS](https://towardsdatascience.com/submissions/)
## Related Articles
  * [![](../images/003.jpg)](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)
## [Stop Choosing Between Local and Cloud LLMs: A Field Guide to Hybrid Patterns](https://towardsdatascience.com/stop-choosing-between-local-and-cloud-llms-a-field-guide-to-hybrid-patterns/)
[LLM Applications](https://towardsdatascience.com/category/artificial-intelligence/llm-applications/)
A hands-on walkthrough of a hybrid local-cloud workflow using Gemma 4 and GPT-5.4, with reasoning and structured outputs
[Shuai Guo](https://towardsdatascience.com/author/shuaiguo/)
June 30, 202616 min read
  * [![](../images/004.png)](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)
## [Transformer-XL Review: Beyond Fixed-Length Contexts](https://towardsdatascience.com/transformer-xl-review-beyond-fixed-length-contexts-d4fe1d6d3c0e/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Review of "Transformer-XL: Attentive Language Models Beyond a Fixed-Length Context"
[Jiajin Li](https://towardsdatascience.com/author/lijj36/)
October 12, 20207 min read
  * [![](../images/005.jpg)](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)
## [Building a simple Agent with Tools and Toolkits in LangChain](https://towardsdatascience.com/building-a-simple-agent-with-tools-and-toolkits-in-langchain-77e0f9bd1fa5/)
[](https://towardsdatascience.com/how-to-fine-tune-an-slm-for-emotion-recognition/)
Get familiar with the building blocks of Agents in LangChain
[Sami Maameri](https://towardsdatascience.com/author/ssmaameri/)
April 10, 202413 min read
  * [![](../images/006.png)](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)
## [Google's MusicLM: from text description to music](https://towardsdatascience.com/googles-musiclm-from-text-description-to-music-23794ab6955c/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
A new model is generating impressive music from just text prompt
[Salvatore Raieli](https://towardsdatascience.com/author/salvatore-raieli/)
February 1, 20237 min read
  * [![](../images/007.gif)](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)
## [State of Video Generation](https://towardsdatascience.com/state-of-video-generation-76595bf75f46/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Overview of latest developments in the Video Generation area: From LLMs to MultyDiffusion. Paper's insights and Outstanding questions.
[Nikita Kiselov](https://towardsdatascience.com/author/nikita_kiselov/)
February 16, 202416 min read
  * [![](../images/008.jpg)](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)
## [Understanding ARIMA Models using PyCaret's Time Series Module - Part 1](https://towardsdatascience.com/understanding-arima-models-using-pycarets-time-series-module-part-1-692e10ca02f2/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
📚 Introduction
[Nikhil Gupta](https://towardsdatascience.com/author/ngupta13/)
November 14, 202110 min read
  * [![](../images/009.jpg)](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)
## [How to Build Graph Transformers with O(N) Complexity](https://towardsdatascience.com/how-to-build-graph-transformers-with-o-n-complexity-d507e103d30a/)
[Machine Learning](https://towardsdatascience.com/category/artificial-intelligence/machine-learning/)
Tutorial on Large-Graph Transformers
[Qitian Wu](https://towardsdatascience.com/author/qitianwu228/)
April 19, 20238 min read
  * [![](../images/010.png)](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)
## [LLM Routing - Intuitively and Exhaustively Explained](https://towardsdatascience.com/llm-routing-intuitively-and-exhaustively-explained-5b0789fe27aa/)
[Artificial Intelligence](https://towardsdatascience.com/category/artificial-intelligence/)
Dynamically Choosing the Right LLM
[Daniel Warfield](https://towardsdatascience.com/author/danielwarfield1/)
November 22, 202459 min read
  * [![](../images/011.jpg)](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)
## [6 RAG question-parsing mistakes we keep seeing in production](https://towardsdatascience.com/the-untaught-lessons-of-rag-question-parsing-structure-before-you-search/)
[Large Language Model](https://towardsdatascience.com/category/large-language-model/)
Enterprise Document Intelligence [Vol.1 #6ter] - Six positions on the question-parsing brick that contradict the mainstream RAG playbook
[Angela and Kezhan Shi](https://towardsdatascience.com/author/angela.shi/)
July 2, 202611 min read


  * [YouTube](https://www.youtube.com/c/TowardsDataScience)
  * [X](https://x.com/TDataScience)
  * [LinkedIn](https://www.linkedin.com/company/towards-data-science/)
  * [Threads](https://www.threads.net/@towardsdatascience)
  * [Bluesky](https://bsky.app/profile/towardsdatascience.com)


[](https://towardsdatascience.com/)
Your home for data science and AI. The world's leading publication for data science, data analytics, data engineering, machine learning, and artificial intelligence professionals.
Subscribe to Our Newsletter[Write For TDS](https://towardsdatascience.com/submissions/)•[About](https://towardsdatascience.com/about-towards-data-science-d691af11cc2f/)•[Advertise](https://contact.towardsdatascience.com/advertise-with-towards-data-science)•[Privacy Policy](https://towardsdatascience.com/privacy-policy/)•[Terms of Use](https://towardsdatascience.com/website-terms-of-use/)
© Insight Media Group, LLC 2026•[The New Stack](https://thenewstack.io)•[roadmap.sh](https://roadmap.sh)•[Creator Network](https://insightmediagroup.io/creator-network)
